commit_id
stringlengths 40
40
| project
stringclasses 91
values | commit_message
stringlengths 9
4.65k
| type
stringclasses 3
values | url
stringclasses 91
values | git_diff
stringlengths 555
2.23M
|
|---|---|---|---|---|---|
b1cdf8765d0d958217fe65568631c4be776eaaba
|
Delta Spike
|
DELTASPIKE-458 lookup UserTransaction via @Resource
Fallback to JNDI only if the injected UserTransaction
is not available (null)
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java
index f08087a59..556b6d8a0 100644
--- a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java
+++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java
@@ -24,6 +24,7 @@
import org.apache.deltaspike.jpa.api.transaction.TransactionConfig;
import org.apache.deltaspike.jpa.impl.transaction.context.EntityManagerEntry;
+import javax.annotation.Resource;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Alternative;
import javax.persistence.EntityManager;
@@ -55,6 +56,9 @@ public class BeanManagedUserTransactionStrategy extends ResourceLocalTransaction
private transient TransactionConfig transactionConfig;
+ @Resource
+ private UserTransaction userTransaction;
+
@Override
protected EntityManagerEntry createEntityManagerEntry(
EntityManager entityManager, Class<? extends Annotation> qualifier)
@@ -158,6 +162,11 @@ protected void beforeProceed(EntityManagerEntry entityManagerEntry)
protected UserTransaction resolveUserTransaction()
{
+ if (userTransaction != null)
+ {
+ return userTransaction;
+ }
+
return JndiUtils.lookup(USER_TRANSACTION_JNDI_NAME, UserTransaction.class);
}
|
17cf114310d01eb41045872d12758bff2c452d93
|
hbase
|
HBASE-5857 RIT map in RS not getting cleared- while region opening--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1329470 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
index 408cfbe5664e..025fc53d0e9a 100644
--- a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -2485,9 +2485,9 @@ public RegionOpeningState openRegion(HRegionInfo region, int versionOfOfflineNod
}
LOG.info("Received request to open region: " +
region.getRegionNameAsString());
+ HTableDescriptor htd = this.tableDescriptors.get(region.getTableName());
this.regionsInTransitionInRS.putIfAbsent(region.getEncodedNameAsBytes(),
true);
- HTableDescriptor htd = this.tableDescriptors.get(region.getTableName());
// Need to pass the expected version in the constructor.
if (region.isRootRegion()) {
this.service.submit(new OpenRootHandler(this, this, region, htd,
diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java b/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java
index c8e523f5e56e..8c3f67e1e490 100644
--- a/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java
+++ b/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java
@@ -47,9 +47,13 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
+import org.mockito.Mockito;
+import org.mockito.internal.util.reflection.Whitebox;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertFalse;
/**
* Test open and close of regions using zk.
@@ -308,6 +312,30 @@ public void testRSAlreadyProcessingRegion() throws Exception {
LOG.info("Done with testCloseRegion");
}
+ /**
+ * If region open fails with IOException in openRegion() while doing tableDescriptors.get()
+ * the region should not add into regionsInTransitionInRS map
+ * @throws Exception
+ */
+ @Test
+ public void testRegionOpenFailsDueToIOException() throws Exception {
+ HRegionInfo REGIONINFO = new HRegionInfo(Bytes.toBytes("t"),
+ HConstants.EMPTY_START_ROW, HConstants.EMPTY_START_ROW);
+ HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(0);
+ TableDescriptors htd = Mockito.mock(TableDescriptors.class);
+ Object orizinalState = Whitebox.getInternalState(regionServer,"tableDescriptors");
+ Whitebox.setInternalState(regionServer, "tableDescriptors", htd);
+ Mockito.doThrow(new IOException()).when(htd).get((byte[]) Mockito.any());
+ try {
+ regionServer.openRegion(REGIONINFO);
+ fail("It should throw IOException ");
+ } catch (IOException e) {
+ }
+ Whitebox.setInternalState(regionServer, "tableDescriptors", orizinalState);
+ assertFalse("Region should not be in RIT",
+ regionServer.getRegionsInTransitionInRS().containsKey(REGIONINFO.getEncodedNameAsBytes()));
+ }
+
private static void waitUntilAllRegionsAssigned()
throws IOException {
HTable meta = new HTable(TEST_UTIL.getConfiguration(),
|
8a07f772e2d36b759f4d5ab6f213fbb0869a1766
|
orientdb
|
Fixed issue with inner class and Object Database- interface--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/object/src/main/java/com/orientechnologies/orient/object/enhancement/OObjectEntityEnhancer.java b/object/src/main/java/com/orientechnologies/orient/object/enhancement/OObjectEntityEnhancer.java
index f4e5e89df7d..db4864a47d8 100644
--- a/object/src/main/java/com/orientechnologies/orient/object/enhancement/OObjectEntityEnhancer.java
+++ b/object/src/main/java/com/orientechnologies/orient/object/enhancement/OObjectEntityEnhancer.java
@@ -49,281 +49,286 @@
*/
public class OObjectEntityEnhancer {
- private static final OObjectEntityEnhancer instance = new OObjectEntityEnhancer();
+ private static final OObjectEntityEnhancer instance = new OObjectEntityEnhancer();
- public static final String ENHANCER_CLASS_PREFIX = "orientdb_";
+ public static final String ENHANCER_CLASS_PREFIX = "orientdb_";
- public OObjectEntityEnhancer() {
- }
+ public OObjectEntityEnhancer() {
+ }
- @SuppressWarnings("unchecked")
- public <T> T getProxiedInstance(final String iClass, final OEntityManager entityManager, final ODocument doc, Object... iArgs) {
- final Class<T> clazz = (Class<T>) entityManager.getEntityClass(iClass);
- return getProxiedInstance(clazz, doc, iArgs);
- }
+ @SuppressWarnings("unchecked")
+ public <T> T getProxiedInstance(final String iClass, final OEntityManager entityManager, final ODocument doc, Object... iArgs) {
+ final Class<T> clazz = (Class<T>) entityManager.getEntityClass(iClass);
+ return getProxiedInstance(clazz, doc, iArgs);
+ }
- @SuppressWarnings("unchecked")
- public <T> T getProxiedInstance(final String iClass, final Object iEnclosingInstance, final OEntityManager entityManager,
- final ODocument doc, Object... iArgs) {
- final Class<T> clazz = (Class<T>) entityManager.getEntityClass(iClass);
- return getProxiedInstance(clazz, iEnclosingInstance, doc, iArgs);
- }
+ @SuppressWarnings("unchecked")
+ public <T> T getProxiedInstance(final String iClass, final Object iEnclosingInstance, final OEntityManager entityManager,
+ final ODocument doc, Object... iArgs) {
+ final Class<T> clazz = (Class<T>) entityManager.getEntityClass(iClass);
+ return getProxiedInstance(clazz, iEnclosingInstance, doc, iArgs);
+ }
- public <T> T getProxiedInstance(final Class<T> iClass, final ODocument doc, Object... iArgs) {
- return getProxiedInstance(iClass, null, doc, iArgs);
- }
+ public <T> T getProxiedInstance(final Class<T> iClass, final ODocument doc, Object... iArgs) {
+ return getProxiedInstance(iClass, null, doc, iArgs);
+ }
- @SuppressWarnings("unchecked")
- public <T> T getProxiedInstance(final Class<T> iClass, Object iEnclosingInstance, final ODocument doc, Object... iArgs) {
- if (iClass == null) {
- throw new OSerializationException("Type " + doc.getClassName()
- + " cannot be serialized because is not part of registered entities. To fix this error register this class");
- }
- final Class<T> c;
- boolean isInnerClass = iClass.getEnclosingClass() != null;
- if (Proxy.class.isAssignableFrom(iClass)) {
- c = iClass;
- } else {
- ProxyFactory f = new ProxyFactory();
- f.setSuperclass(iClass);
- f.setFilter(new MethodFilter() {
- public boolean isHandled(Method m) {
- final String methodName = m.getName();
- try {
- return (isSetterMethod(methodName, m) || isGetterMethod(methodName, m) || methodName.equals("equals") || methodName
- .equals("hashCode"));
- } catch (NoSuchFieldException nsfe) {
- OLogManager.instance().warn(this, "Error handling the method %s in class %s", nsfe, m.getName(), iClass.getName());
- return false;
- } catch (SecurityException se) {
- OLogManager.instance().warn(this, "", se, m.getName(), iClass.getName());
- return false;
- }
- }
- });
- c = f.createClass();
- }
- MethodHandler mi = new OObjectProxyMethodHandler(doc);
- try {
- T newEntity;
- if (iArgs != null && iArgs.length > 0) {
- if (isInnerClass) {
- if (iEnclosingInstance == null) {
- iEnclosingInstance = iClass.getEnclosingClass().newInstance();
- }
- Object[] newArgs = new Object[iArgs.length + 1];
- newArgs[0] = iEnclosingInstance;
- for (int i = 0; i < iArgs.length; i++) {
- newArgs[i + 1] = iArgs[i];
- }
- iArgs = newArgs;
- }
- Constructor<T> constructor = null;
- for (Constructor<?> constr : c.getConstructors()) {
- boolean found = true;
- if (constr.getParameterTypes().length == iArgs.length) {
- for (int i = 0; i < constr.getParameterTypes().length; i++) {
- Class<?> parameterType = constr.getParameterTypes()[i];
- if (parameterType.isPrimitive()) {
- if (!isPrimitiveParameterCorrect(parameterType, iArgs[i])) {
- found = false;
- break;
- }
- } else if (iArgs[i] != null && !parameterType.isAssignableFrom(iArgs[i].getClass())) {
- found = false;
- break;
- }
- }
- } else {
- continue;
- }
- if (found) {
- constructor = (Constructor<T>) constr;
- break;
- }
- }
- if (constructor != null) {
- newEntity = (T) constructor.newInstance(iArgs);
- initDocument(iClass, newEntity, doc, (ODatabaseObject) ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner());
- } else {
- if (iEnclosingInstance != null)
- newEntity = createInstanceNoParameters(c, iEnclosingInstance);
- else
- newEntity = createInstanceNoParameters(c, iClass);
- }
- } else {
- if (iEnclosingInstance != null)
- newEntity = createInstanceNoParameters(c, iEnclosingInstance);
- else
- newEntity = createInstanceNoParameters(c, iClass);
- }
- ((Proxy) newEntity).setHandler(mi);
- if (OObjectEntitySerializer.hasBoundedDocumentField(iClass))
- OObjectEntitySerializer.setFieldValue(OObjectEntitySerializer.getBoundedDocumentField(iClass), newEntity, doc);
- return newEntity;
- } catch (InstantiationException ie) {
- OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), ie);
- } catch (IllegalAccessException iae) {
- OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), iae);
- } catch (IllegalArgumentException iae) {
- OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), iae);
- } catch (SecurityException se) {
- OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), se);
- } catch (InvocationTargetException ite) {
- OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), ite);
- } catch (NoSuchMethodException nsme) {
- OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), nsme);
- }
- return null;
- }
+ @SuppressWarnings("unchecked")
+ public <T> T getProxiedInstance(final Class<T> iClass, Object iEnclosingInstance, final ODocument doc, Object... iArgs) {
+ if (iClass == null) {
+ throw new OSerializationException("Type " + doc.getClassName()
+ + " cannot be serialized because is not part of registered entities. To fix this error register this class");
+ }
+ final Class<T> c;
+ boolean isInnerClass = iClass.getEnclosingClass() != null;
+ if (Proxy.class.isAssignableFrom(iClass)) {
+ c = iClass;
+ } else {
+ ProxyFactory f = new ProxyFactory();
+ f.setSuperclass(iClass);
+ f.setFilter(new MethodFilter() {
+ public boolean isHandled(Method m) {
+ final String methodName = m.getName();
+ try {
+ return (isSetterMethod(methodName, m) || isGetterMethod(methodName, m) || methodName.equals("equals") || methodName
+ .equals("hashCode"));
+ } catch (NoSuchFieldException nsfe) {
+ OLogManager.instance().warn(this, "Error handling the method %s in class %s", nsfe, m.getName(), iClass.getName());
+ return false;
+ } catch (SecurityException se) {
+ OLogManager.instance().warn(this, "", se, m.getName(), iClass.getName());
+ return false;
+ }
+ }
+ });
+ c = f.createClass();
+ }
+ MethodHandler mi = new OObjectProxyMethodHandler(doc);
+ try {
+ T newEntity;
+ if (iArgs != null && iArgs.length > 0) {
+ if (isInnerClass) {
+ if (iEnclosingInstance == null) {
+ iEnclosingInstance = iClass.getEnclosingClass().newInstance();
+ }
+ Object[] newArgs = new Object[iArgs.length + 1];
+ newArgs[0] = iEnclosingInstance;
+ for (int i = 0; i < iArgs.length; i++) {
+ newArgs[i + 1] = iArgs[i];
+ }
+ iArgs = newArgs;
+ }
+ Constructor<T> constructor = null;
+ for (Constructor<?> constr : c.getConstructors()) {
+ boolean found = true;
+ if (constr.getParameterTypes().length == iArgs.length) {
+ for (int i = 0; i < constr.getParameterTypes().length; i++) {
+ Class<?> parameterType = constr.getParameterTypes()[i];
+ if (parameterType.isPrimitive()) {
+ if (!isPrimitiveParameterCorrect(parameterType, iArgs[i])) {
+ found = false;
+ break;
+ }
+ } else if (iArgs[i] != null && !parameterType.isAssignableFrom(iArgs[i].getClass())) {
+ found = false;
+ break;
+ }
+ }
+ } else {
+ continue;
+ }
+ if (found) {
+ constructor = (Constructor<T>) constr;
+ break;
+ }
+ }
+ if (constructor != null) {
+ newEntity = (T) constructor.newInstance(iArgs);
+ initDocument(iClass, newEntity, doc, (ODatabaseObject) ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner());
+ } else {
+ if (iEnclosingInstance != null)
+ newEntity = createInstanceNoParameters(c, iEnclosingInstance);
+ else
+ newEntity = createInstanceNoParameters(c, iClass);
+ }
+ } else {
+ if (iEnclosingInstance != null)
+ newEntity = createInstanceNoParameters(c, iEnclosingInstance);
+ else
+ newEntity = createInstanceNoParameters(c, iClass);
+ }
+ ((Proxy) newEntity).setHandler(mi);
+ if (OObjectEntitySerializer.hasBoundedDocumentField(iClass))
+ OObjectEntitySerializer.setFieldValue(OObjectEntitySerializer.getBoundedDocumentField(iClass), newEntity, doc);
+ return newEntity;
+ } catch (InstantiationException ie) {
+ OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), ie);
+ } catch (IllegalAccessException iae) {
+ OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), iae);
+ } catch (IllegalArgumentException iae) {
+ OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), iae);
+ } catch (SecurityException se) {
+ OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), se);
+ } catch (InvocationTargetException ite) {
+ OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), ite);
+ } catch (NoSuchMethodException nsme) {
+ OLogManager.instance().error(this, "Error creating proxied instance for class " + iClass.getName(), nsme);
+ }
+ return null;
+ }
- public static synchronized OObjectEntityEnhancer getInstance() {
- return instance;
- }
+ public static synchronized OObjectEntityEnhancer getInstance() {
+ return instance;
+ }
- private boolean isSetterMethod(String fieldName, Method m) throws SecurityException, NoSuchFieldException {
- if (!fieldName.startsWith("set") || !checkIfFirstCharAfterPrefixIsUpperCase(fieldName, "set"))
- return false;
- if (m.getParameterTypes() != null && m.getParameterTypes().length != 1)
- return false;
- return !OObjectEntitySerializer.isTransientField(m.getDeclaringClass(), getFieldName(m));
- }
+ private boolean isSetterMethod(String fieldName, Method m) throws SecurityException, NoSuchFieldException {
+ if (!fieldName.startsWith("set") || !checkIfFirstCharAfterPrefixIsUpperCase(fieldName, "set"))
+ return false;
+ if (m.getParameterTypes() != null && m.getParameterTypes().length != 1)
+ return false;
+ return !OObjectEntitySerializer.isTransientField(m.getDeclaringClass(), getFieldName(m));
+ }
- private boolean isGetterMethod(String fieldName, Method m) throws SecurityException, NoSuchFieldException {
- int prefixLength;
- if (fieldName.startsWith("get") && checkIfFirstCharAfterPrefixIsUpperCase(fieldName, "get"))
- prefixLength = "get".length();
- else if (fieldName.startsWith("is") && checkIfFirstCharAfterPrefixIsUpperCase(fieldName, "is"))
- prefixLength = "is".length();
- else
- return false;
- if (m.getParameterTypes() != null && m.getParameterTypes().length > 0)
- return false;
- if (fieldName.length() <= prefixLength)
- return false;
- return !OObjectEntitySerializer.isTransientField(m.getDeclaringClass(), getFieldName(m));
- }
+ private boolean isGetterMethod(String fieldName, Method m) throws SecurityException, NoSuchFieldException {
+ int prefixLength;
+ if (fieldName.startsWith("get") && checkIfFirstCharAfterPrefixIsUpperCase(fieldName, "get"))
+ prefixLength = "get".length();
+ else if (fieldName.startsWith("is") && checkIfFirstCharAfterPrefixIsUpperCase(fieldName, "is"))
+ prefixLength = "is".length();
+ else
+ return false;
+ if (m.getParameterTypes() != null && m.getParameterTypes().length > 0)
+ return false;
+ if (fieldName.length() <= prefixLength)
+ return false;
+ return !OObjectEntitySerializer.isTransientField(m.getDeclaringClass(), getFieldName(m));
+ }
- protected String getFieldName(Method m) {
- if (m.getName().startsWith("get"))
- return getFieldName(m.getName(), "get");
- else if (m.getName().startsWith("set"))
- return getFieldName(m.getName(), "set");
- else
- return getFieldName(m.getName(), "is");
- }
+ protected String getFieldName(Method m) {
+ if (m.getName().startsWith("get"))
+ return getFieldName(m.getName(), "get");
+ else if (m.getName().startsWith("set"))
+ return getFieldName(m.getName(), "set");
+ else
+ return getFieldName(m.getName(), "is");
+ }
- protected String getFieldName(String methodName, String prefix) {
- StringBuffer fieldName = new StringBuffer();
- fieldName.append(Character.toLowerCase(methodName.charAt(prefix.length())));
- for (int i = (prefix.length() + 1); i < methodName.length(); i++) {
- fieldName.append(methodName.charAt(i));
- }
- return fieldName.toString();
- }
+ protected String getFieldName(String methodName, String prefix) {
+ StringBuffer fieldName = new StringBuffer();
+ fieldName.append(Character.toLowerCase(methodName.charAt(prefix.length())));
+ for (int i = (prefix.length() + 1); i < methodName.length(); i++) {
+ fieldName.append(methodName.charAt(i));
+ }
+ return fieldName.toString();
+ }
- private boolean checkIfFirstCharAfterPrefixIsUpperCase(String methodName, String prefix) {
- return methodName.length() > prefix.length() ? Character.isUpperCase(methodName.charAt(prefix.length())) : false;
- }
+ private boolean checkIfFirstCharAfterPrefixIsUpperCase(String methodName, String prefix) {
+ return methodName.length() > prefix.length() ? Character.isUpperCase(methodName.charAt(prefix.length())) : false;
+ }
- private boolean isPrimitiveParameterCorrect(Class<?> primitiveClass, Object parameterValue) {
- if (parameterValue == null)
- return false;
- final Class<?> parameterClass = parameterValue.getClass();
- if (Integer.TYPE.isAssignableFrom(primitiveClass))
- return Integer.class.isAssignableFrom(parameterClass);
- else if (Double.TYPE.isAssignableFrom(primitiveClass))
- return Double.class.isAssignableFrom(parameterClass);
- else if (Float.TYPE.isAssignableFrom(primitiveClass))
- return Float.class.isAssignableFrom(parameterClass);
- else if (Long.TYPE.isAssignableFrom(primitiveClass))
- return Long.class.isAssignableFrom(parameterClass);
- else if (Short.TYPE.isAssignableFrom(primitiveClass))
- return Short.class.isAssignableFrom(parameterClass);
- else if (Byte.TYPE.isAssignableFrom(primitiveClass))
- return Byte.class.isAssignableFrom(parameterClass);
- return false;
- }
+ private boolean isPrimitiveParameterCorrect(Class<?> primitiveClass, Object parameterValue) {
+ if (parameterValue == null)
+ return false;
+ final Class<?> parameterClass = parameterValue.getClass();
+ if (Integer.TYPE.isAssignableFrom(primitiveClass))
+ return Integer.class.isAssignableFrom(parameterClass);
+ else if (Double.TYPE.isAssignableFrom(primitiveClass))
+ return Double.class.isAssignableFrom(parameterClass);
+ else if (Float.TYPE.isAssignableFrom(primitiveClass))
+ return Float.class.isAssignableFrom(parameterClass);
+ else if (Long.TYPE.isAssignableFrom(primitiveClass))
+ return Long.class.isAssignableFrom(parameterClass);
+ else if (Short.TYPE.isAssignableFrom(primitiveClass))
+ return Short.class.isAssignableFrom(parameterClass);
+ else if (Byte.TYPE.isAssignableFrom(primitiveClass))
+ return Byte.class.isAssignableFrom(parameterClass);
+ return false;
+ }
- @SuppressWarnings({ "rawtypes", "unchecked" })
- protected void initDocument(Class<?> iClass, Object iInstance, ODocument iDocument, ODatabaseObject db)
- throws IllegalArgumentException, IllegalAccessException {
- for (Class<?> currentClass = iClass; currentClass != Object.class;) {
- for (Field f : currentClass.getDeclaredFields()) {
- if (f.getName().equals("this$0"))
- continue;
- if (!f.isAccessible()) {
- f.setAccessible(true);
- }
- Object o = f.get(iInstance);
- if (o != null) {
- if (OObjectEntitySerializer.isSerializedType(f)) {
- if (o instanceof List<?>) {
- List<?> list = new ArrayList();
- iDocument.field(f.getName(), list);
- o = new OObjectCustomSerializerList(OObjectEntitySerializer.getSerializedType(f), iDocument, list, (List<?>) o);
- f.set(iInstance, o);
- } else if (o instanceof Set<?>) {
- Set<?> set = new HashSet();
- iDocument.field(f.getName(), set);
- o = new OObjectCustomSerializerSet(OObjectEntitySerializer.getSerializedType(f), iDocument, set, (Set<?>) o);
- f.set(iInstance, o);
- } else if (o instanceof Map<?, ?>) {
- Map<?, ?> map = new HashMap();
- iDocument.field(f.getName(), map);
- o = new OObjectCustomSerializerMap(OObjectEntitySerializer.getSerializedType(f), iDocument, map, (Map<?, ?>) o);
- f.set(iInstance, o);
- } else {
- o = OObjectEntitySerializer.serializeFieldValue(o.getClass(), o);
- iDocument.field(f.getName(), o);
- }
- } else {
- iDocument.field(f.getName(), OObjectEntitySerializer.typeToStream(o, OType.getTypeByClass(f.getType()), db, iDocument));
- }
- }
- }
- currentClass = currentClass.getSuperclass();
- }
- }
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ protected void initDocument(Class<?> iClass, Object iInstance, ODocument iDocument, ODatabaseObject db)
+ throws IllegalArgumentException, IllegalAccessException {
+ for (Class<?> currentClass = iClass; currentClass != Object.class;) {
+ for (Field f : currentClass.getDeclaredFields()) {
+ if (f.getName().equals("this$0"))
+ continue;
+ if (!f.isAccessible()) {
+ f.setAccessible(true);
+ }
+ Object o = f.get(iInstance);
+ if (o != null) {
+ if (OObjectEntitySerializer.isSerializedType(f)) {
+ if (o instanceof List<?>) {
+ List<?> list = new ArrayList();
+ iDocument.field(f.getName(), list);
+ o = new OObjectCustomSerializerList(OObjectEntitySerializer.getSerializedType(f), iDocument, list, (List<?>) o);
+ f.set(iInstance, o);
+ } else if (o instanceof Set<?>) {
+ Set<?> set = new HashSet();
+ iDocument.field(f.getName(), set);
+ o = new OObjectCustomSerializerSet(OObjectEntitySerializer.getSerializedType(f), iDocument, set, (Set<?>) o);
+ f.set(iInstance, o);
+ } else if (o instanceof Map<?, ?>) {
+ Map<?, ?> map = new HashMap();
+ iDocument.field(f.getName(), map);
+ o = new OObjectCustomSerializerMap(OObjectEntitySerializer.getSerializedType(f), iDocument, map, (Map<?, ?>) o);
+ f.set(iInstance, o);
+ } else {
+ o = OObjectEntitySerializer.serializeFieldValue(o.getClass(), o);
+ iDocument.field(f.getName(), o);
+ }
+ } else {
+ iDocument.field(f.getName(), OObjectEntitySerializer.typeToStream(o, OType.getTypeByClass(f.getType()), db, iDocument));
+ }
+ }
+ }
+ currentClass = currentClass.getSuperclass();
+ }
+ }
- protected <T> T createInstanceNoParameters(Class<T> iProxiedClass, Class<?> iOriginalClass) throws SecurityException,
- NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
- T instanceToReturn = null;
- final Class<?> enclosingClass = iOriginalClass.getEnclosingClass();
+ protected <T> T createInstanceNoParameters(Class<T> iProxiedClass, Class<?> iOriginalClass) throws SecurityException,
+ NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
+ T instanceToReturn = null;
+ final Class<?> enclosingClass = iOriginalClass.getEnclosingClass();
- if (enclosingClass != null) {
- Object instanceOfEnclosingClass = createInstanceNoParameters(enclosingClass, enclosingClass);
+ if (enclosingClass != null) {
+ Object instanceOfEnclosingClass = createInstanceNoParameters(enclosingClass, enclosingClass);
- Constructor<T> ctor = iProxiedClass.getConstructor(enclosingClass);
+ Constructor<T> ctor = iProxiedClass.getConstructor(enclosingClass);
- if (ctor != null) {
- instanceToReturn = ctor.newInstance(instanceOfEnclosingClass);
- }
- } else {
- instanceToReturn = iProxiedClass.newInstance();
- }
+ if (ctor != null) {
+ instanceToReturn = ctor.newInstance(instanceOfEnclosingClass);
+ }
+ } else {
+ try {
+ instanceToReturn = iProxiedClass.newInstance();
+ } catch (InstantiationException e) {
+ OLogManager.instance().error(this, "Cannot create an instance of the enclosing class '%s'", iOriginalClass);
+ throw e;
+ }
+ }
- return instanceToReturn;
+ return instanceToReturn;
- }
+ }
- protected <T> T createInstanceNoParameters(Class<T> iProxiedClass, Object iEnclosingInstance) throws SecurityException,
- NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
- T instanceToReturn = null;
- final Class<?> enclosingClass = iEnclosingInstance.getClass();
+ protected <T> T createInstanceNoParameters(Class<T> iProxiedClass, Object iEnclosingInstance) throws SecurityException,
+ NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
+ T instanceToReturn = null;
+ final Class<?> enclosingClass = iEnclosingInstance.getClass();
- if (enclosingClass != null) {
+ if (enclosingClass != null) {
- Constructor<T> ctor = iProxiedClass.getConstructor(enclosingClass);
+ Constructor<T> ctor = iProxiedClass.getConstructor(enclosingClass);
- if (ctor != null) {
- instanceToReturn = ctor.newInstance(iEnclosingInstance);
- }
- } else {
- instanceToReturn = iProxiedClass.newInstance();
- }
+ if (ctor != null) {
+ instanceToReturn = ctor.newInstance(iEnclosingInstance);
+ }
+ } else {
+ instanceToReturn = iProxiedClass.newInstance();
+ }
- return instanceToReturn;
+ return instanceToReturn;
- }
+ }
}
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DictionaryTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DictionaryTest.java
index 441c66d4c95..e99182ebd63 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DictionaryTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DictionaryTest.java
@@ -25,12 +25,14 @@
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ORecordFlat;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;
-import com.orientechnologies.orient.object.enhancement.ExactEntity;
@Test(groups = "dictionary")
public class DictionaryTest {
private String url;
+ public DictionaryTest() {
+ }
+
@Parameters(value = "url")
public DictionaryTest(String iURL) {
url = iURL;
@@ -129,14 +131,29 @@ public void testDictionaryInTx() throws IOException {
database.close();
}
+ public class ObjectDictionaryTest {
+ private String name;
+
+ public ObjectDictionaryTest() {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+ }
+
@Test(dependsOnMethods = "testDictionaryMassiveCreate")
public void testDictionaryWithPOJOs() throws IOException {
OObjectDatabaseTx database = new OObjectDatabaseTx(url);
database.open("admin", "admin");
- database.getEntityManager().registerEntityClass(ExactEntity.class);
+ database.getEntityManager().registerEntityClass(ObjectDictionaryTest.class);
Assert.assertNull(database.getDictionary().get("testKey"));
- database.getDictionary().put("testKey", new ExactEntity());
+ database.getDictionary().put("testKey", new ObjectDictionaryTest());
Assert.assertNotNull(database.getDictionary().get("testKey"));
database.close();
|
ba475c843b6e0af795c00b77c75f49689dc0a999
|
arquillian$arquillian-graphene
|
ARQGRA-84: added support for JQuery selectors
Original vision to support only Sizzle selectors was not working with
HTMLUnit driver therefore added JQyery selectors 1.2.6.
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/.gitignore b/.gitignore
index b6d4b94e1..0e7054f40 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,4 @@ test-output
.classpath
.settings
.project
+chromedriver.log
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/JQuerySelectorsPageExtensionTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/JQuerySelectorsPageExtensionTestCase.java
new file mode 100644
index 000000000..f3172b4e0
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/JQuerySelectorsPageExtensionTestCase.java
@@ -0,0 +1,178 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.ftest.page.extension;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.net.URL;
+import java.util.List;
+
+import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.enricher.findby.ByJQuery;
+import org.jboss.arquillian.graphene.spi.annotations.FindBy;
+import org.jboss.arquillian.junit.Arquillian;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.NoSuchElementException;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebDriverException;
+import org.openqa.selenium.WebElement;
+
+/**
+ * @author <a href="mailto:[email protected]">Juraj Huska</a>
+ */
+@RunWith(Arquillian.class)
+public class JQuerySelectorsPageExtensionTestCase {
+
+ @FindBy(jquery = ":header")
+ private WebElement webElementByJQuery;
+
+ @FindBy(jquery = ":header")
+ private List<WebElement> listOfWebElementsByJQuery;
+
+ @FindBy(jquery = "div:eq(1)")
+ private JQuerySelectorTestPageFragment jquerySelectorTestPageFragment;
+
+ @FindBy(jquery = "div:eq(1)")
+ private List<JQuerySelectorTestPageFragment> listOfJQueryPageFragments;
+
+ @Drone
+ private WebDriver browser;
+
+ private static String EXPECTED_JQUERY_TEXT_1 = "Hello jquery selectors!";
+ private static String EXPECTED_JQUERY_TEXT_2 = "Nested div with foo class.";
+ private static String EXPECTED_NO_SUCH_EL_EX_MSG = "Cannot locate elements using";
+ private static String EXPECTED_WRONG_SELECTOR_MSG = "Check out whether it is correct!";
+
+ public void loadPage() {
+ URL page = this.getClass().getClassLoader()
+ .getResource("org/jboss/arquillian/graphene/ftest/page/extension/sampleJQueryLocator.html");
+ browser.get(page.toString());
+ }
+
+ @Test
+ public void testFindByWrongSelector() {
+ loadPage();
+
+ @SuppressWarnings("unused")
+ WebElement element = null;
+
+ try {
+ element = browser.findElement(ByJQuery.jquerySelector(":notExistingSelector"));
+ } catch (WebDriverException ex) {
+ // desired state
+ assertTrue("The exception thrown after locating element by non existing selector is wrong!", ex.getMessage()
+ .contains(EXPECTED_WRONG_SELECTOR_MSG));
+ return;
+ }
+
+ fail("There should be webdriver exception thrown when locating element by wrong selector!");
+ }
+
+ @Test
+ public void testFindNonExistingElement() {
+ loadPage();
+
+ try {
+ @SuppressWarnings("unused")
+ WebElement nonExistingElement = browser.findElement(ByJQuery.jquerySelector(":contains('non existing string')"));
+ } catch (NoSuchElementException ex) {
+ // this is desired state
+ assertTrue("Error message of NoSuchElementException is wrong!", ex.getMessage()
+ .contains(EXPECTED_NO_SUCH_EL_EX_MSG));
+ return;
+ }
+
+ fail("There was not thrown NoSuchElementException when trying to locate non existed element!");
+ }
+
+ @Test
+ public void testFindingWebElementFromAnotherWebElement() {
+ loadPage();
+
+ WebElement root = browser.findElement(ByJQuery.jquerySelector("#root:visible"));
+
+ WebElement div = root.findElement(ByJQuery.jquerySelector(".foo:visible"));
+
+ assertNotNull("The div element should be found!", div);
+ assertEquals("The element was not referenced from parent WebElement correctly!", EXPECTED_JQUERY_TEXT_2, div.getText());
+ }
+
+ @Test
+ public void testJQuerySelectorCallingFindByDirectly() {
+ loadPage();
+
+ ByJQuery headerBy = new ByJQuery(":header");
+ WebElement headerElement = browser.findElement(headerBy);
+
+ assertNotNull(headerElement);
+ assertEquals("h1", headerElement.getTagName());
+ }
+
+ @Test
+ public void testFindByOnWebElement() {
+ loadPage();
+
+ assertNotNull(webElementByJQuery);
+ assertEquals("h1", webElementByJQuery.getTagName());
+ }
+
+ @Test
+ public void testFindByOnListOfWebElement() {
+ loadPage();
+
+ assertNotNull(listOfWebElementsByJQuery);
+ assertEquals("h1", listOfWebElementsByJQuery.get(0).getTagName());
+ }
+
+ @Test
+ public void testFindByOnPageFragment() {
+ loadPage();
+
+ assertNotNull(jquerySelectorTestPageFragment);
+ assertEquals(EXPECTED_JQUERY_TEXT_1, jquerySelectorTestPageFragment.getJQueryLocator().getText());
+ }
+
+ @Test
+ public void testFindByOnListOfPageFragments() {
+ loadPage();
+
+ assertNotNull(listOfJQueryPageFragments);
+ assertEquals(EXPECTED_JQUERY_TEXT_1, listOfJQueryPageFragments.get(0).getJQueryLocator().getText());
+ }
+
+ /* *************
+ * Page Fragment
+ */
+ public class JQuerySelectorTestPageFragment {
+
+ @FindBy(jquery = "div:contains('jquery selectors')")
+ private WebElement jqueryLocator;
+
+ public WebElement getJQueryLocator() {
+ return jqueryLocator;
+ }
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/SizzleJSPageExtensionTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/SizzleJSPageExtensionTestCase.java
deleted file mode 100644
index bb84963c8..000000000
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/SizzleJSPageExtensionTestCase.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, 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.arquillian.graphene.ftest.page.extension;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.net.URL;
-import java.util.List;
-
-import org.jboss.arquillian.drone.api.annotation.Drone;
-import org.jboss.arquillian.graphene.enricher.annotation.ByJQuery;
-import org.jboss.arquillian.graphene.spi.annotations.FindBy;
-import org.jboss.arquillian.junit.Arquillian;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
-
-/**
- * @author <a href="mailto:[email protected]">Juraj Huska</a>
- */
-@RunWith(Arquillian.class)
-public class SizzleJSPageExtensionTestCase {
-
- @FindBy(jquery = ":header")
- private WebElement webElementBySizzle;
-
- @FindBy(jquery = ":header")
- private List<WebElement> listOfWebElementsBySizzle;
-
- @FindBy(jquery = "div:first")
- private SizzleTestPageFragment sizzleTestPageFragment;
-
- @FindBy(jquery = "div:first")
- private List<SizzleTestPageFragment> listOfSizzlePageFragments;
-
- @Drone
- private WebDriver browser;
-
- private static String EXPECTED_SIZZLE_TEXT = "Hello sizzle locators!";
-
- public void loadPage() {
- URL page = this.getClass().getClassLoader()
- .getResource("org/jboss/arquillian/graphene/ftest/page/extension/sample.html");
- browser.get(page.toString());
- }
-
- @Test
- public void testSizzleJSPageExtensionInstalled() {
- loadPage();
-
- ByJQuery htmlBy = new ByJQuery("html");
- WebElement htmlElement = browser.findElement(htmlBy);
-
- assertNotNull(htmlElement);
- assertEquals("html", htmlElement.getTagName());
- }
-
- @Test
- public void testFindByOnWebElementSizzleLocator() {
- loadPage();
-
- assertNotNull(webElementBySizzle);
- assertEquals("h1", webElementBySizzle.getTagName());
- }
-
- @Test
- public void testFindByOnListOfWebElementSizzleLocator() {
- loadPage();
-
- assertNotNull(listOfWebElementsBySizzle);
- assertEquals("h1", listOfWebElementsBySizzle.get(0).getTagName());
- }
-
- @Test
- public void testFindByOnPageFragmentBySizzleLocator() {
- loadPage();
-
- assertNotNull(sizzleTestPageFragment);
- assertEquals(EXPECTED_SIZZLE_TEXT, sizzleTestPageFragment.getSizzleLocator().getText());
- }
-
- @Test
- public void testFindByOnListOfPageFragments() {
- loadPage();
-
- assertNotNull(listOfSizzlePageFragments);
- assertEquals(EXPECTED_SIZZLE_TEXT, listOfSizzlePageFragments.get(0).getSizzleLocator().getText());
- }
-
- /* *************
- * Page Fragment
- */
- public class SizzleTestPageFragment {
-
- @FindBy(jquery = "div:contains(sizzle locators)")
- private WebElement sizzleLocator;
-
- public WebElement getSizzleLocator() {
- return sizzleLocator;
- }
- }
-}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sample.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sample.html
index febc81c19..4ca19adfe 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sample.html
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sample.html
@@ -4,8 +4,5 @@
</head>
<body>
<h1>Hello World!</h1>
- <div>
- <div>Hello sizzle locators!</div>
- </div>
</body>
</html>
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sampleJQueryLocator.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sampleJQueryLocator.html
new file mode 100644
index 000000000..91a76bf28
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/page/extension/sampleJQueryLocator.html
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html>
+<head>
+</head>
+<body>
+ <h1>Hello World!</h1>
+ <div class="foo">Outer div with foo class.</div>
+ <div id="root">
+ <div>Hello jquery selectors!</div>
+ <div class="foo">Nested div with foo class.</div>
+ </div>
+</body>
+</html>
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
index 513d274d2..353cc0354 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
@@ -29,8 +29,8 @@
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.spi.ServiceLoader;
-import org.jboss.arquillian.graphene.enricher.annotation.FindByUtilities;
import org.jboss.arquillian.graphene.enricher.exception.PageFragmentInitializationException;
+import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities;
import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
import org.jboss.arquillian.graphene.spi.annotations.Root;
import org.openqa.selenium.By;
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
index b6f3b1ac0..cb608f712 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
@@ -24,8 +24,8 @@
import java.lang.reflect.Field;
import java.util.List;
-import org.jboss.arquillian.graphene.enricher.annotation.FindByUtilities;
import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException;
+import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/ByJQuery.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
similarity index 51%
rename from graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/ByJQuery.java
rename to graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
index e0bd43568..9dfbce493 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/ByJQuery.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
@@ -19,16 +19,21 @@
* 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.arquillian.graphene.enricher.annotation;
+package org.jboss.arquillian.graphene.enricher.findby;
import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext;
import org.jboss.arquillian.graphene.page.extension.SizzleJSPageExtension;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
+import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.SearchContext;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
/**
@@ -45,18 +50,61 @@ public ByJQuery(String jquerySelector) {
}
public static ByJQuery jquerySelector(String selector) {
- if(selector == null) {
- throw new IllegalArgumentException("Can not find elements when jquerySelector is null!");
+ if (selector == null) {
+ throw new IllegalArgumentException("Cannot find elements when jquerySelector is null!");
}
return new ByJQuery(selector);
}
+ @Override
+ public String toString() {
+ return "By.jquerySelector " + jquerySelector;
+ }
+
@SuppressWarnings("unchecked")
@Override
public List<WebElement> findElements(SearchContext context) {
+ installSizzleJSExtension();
+
+ List<WebElement> elements = null;
+
+ try {
+ // the element is referenced from parent web element
+ if (context instanceof WebElement) {
+ elements = (List<WebElement>) executor.executeScript(
+ "return $(\"" + jquerySelector + "\", arguments[0]).get()", (WebElement) context);
+ } else if (context instanceof WebDriver) { // element is not referenced from parent
+ elements = (List<WebElement>) executor.executeScript("return $(\"" + jquerySelector + "\").get()");
+ } else { // other unknown case
+ Logger
+ .getLogger(this.getClass().getName())
+ .log(
+ Level.SEVERE,
+ "Cannot determine the SearchContext you are passing to the findBy/s method! It is not instance of WebDriver nor WebElement! It is: "
+ + context);
+ }
+ } catch (Exception ex) {
+ throw new WebDriverException("Can not locate element using selector " + jquerySelector
+ + " Check out whether it is correct!", ex);
+ }
+
+ if (elements == null || elements.size() == 0) {
+ throw new NoSuchElementException("Cannot locate elements using: " + jquerySelector);
+ }
+
+ return elements;
+ }
+
+ @Override
+ public WebElement findElement(SearchContext context) {
+ installSizzleJSExtension();
+
+ return this.findElements(context).get(0);
+ }
+
+ private void installSizzleJSExtension() {
SizzleJSPageExtension pageExtension = new SizzleJSPageExtension();
GraphenePageExtensionsContext.getRegistryProxy().register(pageExtension);
GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtension.getName()).install();
-
- return (List<WebElement>) executor.executeScript("return window.Sizzle('" + jquerySelector + "')");
- }}
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/FindByUtilities.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/FindByUtilities.java
rename to graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
index 299c45932..916cd28a4 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/annotation/FindByUtilities.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher.annotation;
+package org.jboss.arquillian.graphene.enricher.findby;
import java.lang.reflect.Field;
import java.util.List;
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/SizzleJSPageExtension.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/SizzleJSPageExtension.java
index f06ab2fca..795c4beb7 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/SizzleJSPageExtension.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/SizzleJSPageExtension.java
@@ -39,12 +39,12 @@ public String getName() {
@Override
public JavaScript getExtensionScript() {
- return JavaScript.fromResource("com/sizzlejs/sizzle.js");
+ return JavaScript.fromResource("com/jquery/jquery-1.2.6.min.js");
}
@Override
public JavaScript getInstallationDetectionScript() {
- return JavaScript.fromString("return ((typeof window.Sizzle != 'undefined') && (window.Sizzle() != null))");
+ return JavaScript.fromString("return ((typeof $ != 'undefined') && ($() != null))");
}
@Override
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/jquery/jquery-1.2.6.min.js b/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/jquery/jquery-1.2.6.min.js
new file mode 100644
index 000000000..82b98e1d7
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/jquery/jquery-1.2.6.min.js
@@ -0,0 +1,32 @@
+/*
+ * jQuery 1.2.6 - New Wave Javascript
+ *
+ * Copyright (c) 2008 John Resig (jquery.com)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
+ * $Rev: 5685 $
+ */
+(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else
+return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
+return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
+selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
+return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
+this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
+return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
+jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&©&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
+script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
+for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
+for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
+jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
+ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&¬xml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&¬xml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&¬xml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
+while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
+while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
+for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
+jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
+xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
+jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
+for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
+s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
+e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/sizzlejs/sizzle.js b/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/sizzlejs/sizzle.js
deleted file mode 100644
index 3e3caed4b..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/javascript/com/sizzlejs/sizzle.js
+++ /dev/null
@@ -1,1710 +0,0 @@
-/*!
- * Sizzle CSS Selector Engine
- * Copyright 2012 jQuery Foundation and other contributors
- * Released under the MIT license
- * http://sizzlejs.com/
- */
-(function( window, undefined ) {
-
-var cachedruns,
- assertGetIdNotName,
- Expr,
- getText,
- isXML,
- contains,
- compile,
- sortOrder,
- hasDuplicate,
- outermostContext,
-
- strundefined = "undefined",
-
- // Used in sorting
- MAX_NEGATIVE = 1 << 31,
- baseHasDuplicate = true,
-
- expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
-
- Token = String,
- document = window.document,
- docElem = document.documentElement,
- dirruns = 0,
- done = 0,
- pop = [].pop,
- push = [].push,
- slice = [].slice,
- // Use a stripped-down indexOf if a native one is unavailable
- indexOf = [].indexOf || function( elem ) {
- var i = 0,
- len = this.length;
- for ( ; i < len; i++ ) {
- if ( this[i] === elem ) {
- return i;
- }
- }
- return -1;
- },
-
- // Augment a function for special use by Sizzle
- markFunction = function( fn, value ) {
- fn[ expando ] = value == null || value;
- return fn;
- },
-
- createCache = function() {
- var cache = {},
- keys = [];
-
- return markFunction(function( key, value ) {
- // Only keep the most recent entries
- if ( keys.push( key ) > Expr.cacheLength ) {
- delete cache[ keys.shift() ];
- }
-
- // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
- return (cache[ key + " " ] = value);
- }, cache );
- },
-
- classCache = createCache(),
- tokenCache = createCache(),
- compilerCache = createCache(),
-
- // Regex
-
- // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
- whitespace = "[\\x20\\t\\r\\n\\f]",
- // http://www.w3.org/TR/css3-syntax/#characters
- characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
-
- // Loosely modeled on CSS identifier characters
- // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
- // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
- identifier = characterEncoding.replace( "w", "w#" ),
-
- // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
- operators = "([*^$|!~]?=)",
- attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
- "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
-
- // Prefer arguments not in parens/brackets,
- // then attribute selectors and non-pseudos (denoted by :),
- // then anything else
- // These preferences are here to reduce the number of selectors
- // needing tokenize in the PSEUDO preFilter
- pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
-
- // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
- rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
-
- rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
- rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
- rpseudo = new RegExp( pseudos ),
-
- // Easily-parseable/retrievable ID or TAG or CLASS selectors
- rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
-
- rsibling = /[\x20\t\r\n\f]*[+~]/,
-
- rheader = /h\d/i,
- rinputs = /input|select|textarea|button/i,
-
- rbackslash = /\\(?!\\)/g,
-
- matchExpr = {
- "ID": new RegExp( "^#(" + characterEncoding + ")" ),
- "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
- "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
- "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
- "ATTR": new RegExp( "^" + attributes ),
- "PSEUDO": new RegExp( "^" + pseudos ),
- "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
- "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
- "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
- // For use in libraries implementing .is()
- // We use this for POS matching in `select`
- "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
- whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
- },
-
- // Support
-
- // Used for testing something on an element
- assert = function( fn ) {
- var div = document.createElement("div");
-
- try {
- return fn( div );
- } catch (e) {
- return false;
- } finally {
- // release memory in IE
- div = null;
- }
- },
-
- // Check if getElementsByTagName("*") returns only elements
- assertTagNameNoComments = assert(function( div ) {
- div.appendChild( document.createComment("") );
- return !div.getElementsByTagName("*").length;
- }),
-
- // Check if getAttribute returns normalized href attributes
- assertHrefNotNormalized = assert(function( div ) {
- div.innerHTML = "<a href='#'></a>";
- return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
- div.firstChild.getAttribute("href") === "#";
- }),
-
- // Check if attributes should be retrieved by attribute nodes
- assertAttributes = assert(function( div ) {
- div.innerHTML = "<select></select>";
- var type = typeof div.lastChild.getAttribute("multiple");
- // IE8 returns a string for some attributes even when not present
- return type !== "boolean" && type !== "string";
- }),
-
- // Check if getElementsByClassName can be trusted
- assertUsableClassName = assert(function( div ) {
- // Opera can't find a second classname (in 9.6)
- div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
- if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
- return false;
- }
-
- // Safari 3.2 caches class attributes and doesn't catch changes
- div.lastChild.className = "e";
- return div.getElementsByClassName("e").length === 2;
- }),
-
- // Check if getElementById returns elements by name
- // Check if getElementsByName privileges form controls or returns elements by ID
- assertUsableName = assert(function( div ) {
- // Inject content
- div.id = expando + 0;
- div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
- docElem.insertBefore( div, docElem.firstChild );
-
- // Test
- var pass = document.getElementsByName &&
- // buggy browsers will return fewer than the correct 2
- document.getElementsByName( expando ).length === 2 +
- // buggy browsers will return more than the correct 0
- document.getElementsByName( expando + 0 ).length;
- assertGetIdNotName = !document.getElementById( expando );
-
- // Cleanup
- docElem.removeChild( div );
-
- return pass;
- });
-
-// If slice is not available, provide a backup
-try {
- slice.call( docElem.childNodes, 0 )[0].nodeType;
-} catch ( e ) {
- slice = function( i ) {
- var elem,
- results = [];
- for ( ; (elem = this[i]); i++ ) {
- results.push( elem );
- }
- return results;
- };
-}
-
-function Sizzle( selector, context, results, seed ) {
- results = results || [];
- context = context || document;
- var match, elem, xml, m,
- nodeType = context.nodeType;
-
- if ( !selector || typeof selector !== "string" ) {
- return results;
- }
-
- if ( nodeType !== 1 && nodeType !== 9 ) {
- return [];
- }
-
- xml = isXML( context );
-
- if ( !xml && !seed ) {
- if ( (match = rquickExpr.exec( selector )) ) {
- // Speed-up: Sizzle("#ID")
- if ( (m = match[1]) ) {
- if ( nodeType === 9 ) {
- elem = context.getElementById( m );
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- if ( elem && elem.parentNode ) {
- // Handle the case where IE, Opera, and Webkit return items
- // by name instead of ID
- if ( elem.id === m ) {
- results.push( elem );
- return results;
- }
- } else {
- return results;
- }
- } else {
- // Context is not a document
- if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
- contains( context, elem ) && elem.id === m ) {
- results.push( elem );
- return results;
- }
- }
-
- // Speed-up: Sizzle("TAG")
- } else if ( match[2] ) {
- push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
- return results;
-
- // Speed-up: Sizzle(".CLASS")
- } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
- push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
- return results;
- }
- }
- }
-
- // All others
- return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
-}
-
-Sizzle.matches = function( expr, elements ) {
- return Sizzle( expr, null, null, elements );
-};
-
-Sizzle.matchesSelector = function( elem, expr ) {
- return Sizzle( expr, null, null, [ elem ] ).length > 0;
-};
-
-// Returns a function to use in pseudos for input types
-function createInputPseudo( type ) {
- return function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === type;
- };
-}
-
-// Returns a function to use in pseudos for buttons
-function createButtonPseudo( type ) {
- return function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return (name === "input" || name === "button") && elem.type === type;
- };
-}
-
-// Returns a function to use in pseudos for positionals
-function createPositionalPseudo( fn ) {
- return markFunction(function( argument ) {
- argument = +argument;
- return markFunction(function( seed, matches ) {
- var j,
- matchIndexes = fn( [], seed.length, argument ),
- i = matchIndexes.length;
-
- // Match elements found at the specified indexes
- while ( i-- ) {
- if ( seed[ (j = matchIndexes[i]) ] ) {
- seed[j] = !(matches[j] = seed[j]);
- }
- }
- });
- });
-}
-
-/**
- * Utility function for retrieving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-getText = Sizzle.getText = function( elem ) {
- var node,
- ret = "",
- i = 0,
- nodeType = elem.nodeType;
-
- if ( nodeType ) {
- if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
- // Use textContent for elements
- // innerText usage removed for consistency of new lines (see #11153)
- if ( typeof elem.textContent === "string" ) {
- return elem.textContent;
- } else {
- // Traverse its children
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
- ret += getText( elem );
- }
- }
- } else if ( nodeType === 3 || nodeType === 4 ) {
- return elem.nodeValue;
- }
- // Do not include comment or processing instruction nodes
- } else {
-
- // If no nodeType, this is expected to be an array
- for ( ; (node = elem[i]); i++ ) {
- // Do not traverse comment nodes
- ret += getText( node );
- }
- }
- return ret;
-};
-
-isXML = Sizzle.isXML = function( elem ) {
- // documentElement is verified for cases where it doesn't yet exist
- // (such as loading iframes in IE - #4833)
- var documentElement = elem && (elem.ownerDocument || elem).documentElement;
- return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-// Element contains another
-contains = Sizzle.contains = docElem.contains ?
- function( a, b ) {
- var adown = a.nodeType === 9 ? a.documentElement : a,
- bup = b && b.parentNode;
- return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
- } :
- docElem.compareDocumentPosition ?
- function( a, b ) {
- return b && !!( a.compareDocumentPosition( b ) & 16 );
- } :
- function( a, b ) {
- while ( (b = b.parentNode) ) {
- if ( b === a ) {
- return true;
- }
- }
- return false;
- };
-
-Sizzle.attr = function( elem, name ) {
- var val,
- xml = isXML( elem );
-
- if ( !xml ) {
- name = name.toLowerCase();
- }
- if ( (val = Expr.attrHandle[ name ]) ) {
- return val( elem );
- }
- if ( xml || assertAttributes ) {
- return elem.getAttribute( name );
- }
- val = elem.getAttributeNode( name );
- return val ?
- typeof elem[ name ] === "boolean" ?
- elem[ name ] ? name : null :
- val.specified ? val.value : null :
- null;
-};
-
-Expr = Sizzle.selectors = {
-
- // Can be adjusted by the user
- cacheLength: 50,
-
- createPseudo: markFunction,
-
- match: matchExpr,
-
- // IE6/7 return a modified href
- attrHandle: assertHrefNotNormalized ?
- {} :
- {
- "href": function( elem ) {
- return elem.getAttribute( "href", 2 );
- },
- "type": function( elem ) {
- return elem.getAttribute("type");
- }
- },
-
- find: {
- "ID": assertGetIdNotName ?
- function( id, context, xml ) {
- if ( typeof context.getElementById !== strundefined && !xml ) {
- var m = context.getElementById( id );
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- return m && m.parentNode ? [m] : [];
- }
- } :
- function( id, context, xml ) {
- if ( typeof context.getElementById !== strundefined && !xml ) {
- var m = context.getElementById( id );
-
- return m ?
- m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
- [m] :
- undefined :
- [];
- }
- },
-
- "TAG": assertTagNameNoComments ?
- function( tag, context ) {
- if ( typeof context.getElementsByTagName !== strundefined ) {
- return context.getElementsByTagName( tag );
- }
- } :
- function( tag, context ) {
- var results = context.getElementsByTagName( tag );
-
- // Filter out possible comments
- if ( tag === "*" ) {
- var elem,
- tmp = [],
- i = 0;
-
- for ( ; (elem = results[i]); i++ ) {
- if ( elem.nodeType === 1 ) {
- tmp.push( elem );
- }
- }
-
- return tmp;
- }
- return results;
- },
-
- "NAME": assertUsableName && function( tag, context ) {
- if ( typeof context.getElementsByName !== strundefined ) {
- return context.getElementsByName( name );
- }
- },
-
- "CLASS": assertUsableClassName && function( className, context, xml ) {
- if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
- return context.getElementsByClassName( className );
- }
- }
- },
-
- relative: {
- ">": { dir: "parentNode", first: true },
- " ": { dir: "parentNode" },
- "+": { dir: "previousSibling", first: true },
- "~": { dir: "previousSibling" }
- },
-
- preFilter: {
- "ATTR": function( match ) {
- match[1] = match[1].replace( rbackslash, "" );
-
- // Move the given value to match[3] whether quoted or unquoted
- match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
-
- if ( match[2] === "~=" ) {
- match[3] = " " + match[3] + " ";
- }
-
- return match.slice( 0, 4 );
- },
-
- "CHILD": function( match ) {
- /* matches from matchExpr["CHILD"]
- 1 type (only|nth|...)
- 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
- 3 xn-component of xn+y argument ([+-]?\d*n|)
- 4 sign of xn-component
- 5 x of xn-component
- 6 sign of y-component
- 7 y of y-component
- */
- match[1] = match[1].toLowerCase();
-
- if ( match[1] === "nth" ) {
- // nth-child requires argument
- if ( !match[2] ) {
- Sizzle.error( match[0] );
- }
-
- // numeric x and y parameters for Expr.filter.CHILD
- // remember that false/true cast respectively to 0/1
- match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
- match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
-
- // other types prohibit arguments
- } else if ( match[2] ) {
- Sizzle.error( match[0] );
- }
-
- return match;
- },
-
- "PSEUDO": function( match ) {
- var unquoted, excess;
- if ( matchExpr["CHILD"].test( match[0] ) ) {
- return null;
- }
-
- if ( match[3] ) {
- match[2] = match[3];
- } else if ( (unquoted = match[4]) ) {
- // Only check arguments that contain a pseudo
- if ( rpseudo.test(unquoted) &&
- // Get excess from tokenize (recursively)
- (excess = tokenize( unquoted, true )) &&
- // advance to the next closing parenthesis
- (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
-
- // excess is a negative index
- unquoted = unquoted.slice( 0, excess );
- match[0] = match[0].slice( 0, excess );
- }
- match[2] = unquoted;
- }
-
- // Return only captures needed by the pseudo filter method (type and argument)
- return match.slice( 0, 3 );
- }
- },
-
- filter: {
- "ID": assertGetIdNotName ?
- function( id ) {
- id = id.replace( rbackslash, "" );
- return function( elem ) {
- return elem.getAttribute("id") === id;
- };
- } :
- function( id ) {
- id = id.replace( rbackslash, "" );
- return function( elem ) {
- var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
- return node && node.value === id;
- };
- },
-
- "TAG": function( nodeName ) {
- if ( nodeName === "*" ) {
- return function() { return true; };
- }
- nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
-
- return function( elem ) {
- return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
- };
- },
-
- "CLASS": function( className ) {
- var pattern = classCache[ expando ][ className + " " ];
-
- return pattern ||
- (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
- classCache( className, function( elem ) {
- return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
- });
- },
-
- "ATTR": function( name, operator, check ) {
- return function( elem ) {
- var result = Sizzle.attr( elem, name );
-
- if ( result == null ) {
- return operator === "!=";
- }
- if ( !operator ) {
- return true;
- }
-
- result += "";
-
- return operator === "=" ? result === check :
- operator === "!=" ? result !== check :
- operator === "^=" ? check && result.indexOf( check ) === 0 :
- operator === "*=" ? check && result.indexOf( check ) > -1 :
- operator === "$=" ? check && result.substr( result.length - check.length ) === check :
- operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
- operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
- false;
- };
- },
-
- "CHILD": function( type, argument, first, last ) {
-
- if ( type === "nth" ) {
- return function( elem ) {
- var node, diff,
- parent = elem.parentNode;
-
- if ( first === 1 && last === 0 ) {
- return true;
- }
-
- if ( parent ) {
- diff = 0;
- for ( node = parent.firstChild; node; node = node.nextSibling ) {
- if ( node.nodeType === 1 ) {
- diff++;
- if ( elem === node ) {
- break;
- }
- }
- }
- }
-
- // Incorporate the offset (or cast to NaN), then check against cycle size
- diff -= last;
- return diff === first || ( diff % first === 0 && diff / first >= 0 );
- };
- }
-
- return function( elem ) {
- var node = elem;
-
- switch ( type ) {
- case "only":
- case "first":
- while ( (node = node.previousSibling) ) {
- if ( node.nodeType === 1 ) {
- return false;
- }
- }
-
- if ( type === "first" ) {
- return true;
- }
-
- node = elem;
-
- /* falls through */
- case "last":
- while ( (node = node.nextSibling) ) {
- if ( node.nodeType === 1 ) {
- return false;
- }
- }
-
- return true;
- }
- };
- },
-
- "PSEUDO": function( pseudo, argument ) {
- // pseudo-class names are case-insensitive
- // http://www.w3.org/TR/selectors/#pseudo-classes
- // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
- // Remember that setFilters inherits from pseudos
- var args,
- fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
- Sizzle.error( "unsupported pseudo: " + pseudo );
-
- // The user may use createPseudo to indicate that
- // arguments are needed to create the filter function
- // just as Sizzle does
- if ( fn[ expando ] ) {
- return fn( argument );
- }
-
- // But maintain support for old signatures
- if ( fn.length > 1 ) {
- args = [ pseudo, pseudo, "", argument ];
- return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
- markFunction(function( seed, matches ) {
- var idx,
- matched = fn( seed, argument ),
- i = matched.length;
- while ( i-- ) {
- idx = indexOf.call( seed, matched[i] );
- seed[ idx ] = !( matches[ idx ] = matched[i] );
- }
- }) :
- function( elem ) {
- return fn( elem, 0, args );
- };
- }
-
- return fn;
- }
- },
-
- pseudos: {
- "not": markFunction(function( selector ) {
- // Trim the selector passed to compile
- // to avoid treating leading and trailing
- // spaces as combinators
- var input = [],
- results = [],
- matcher = compile( selector.replace( rtrim, "$1" ) );
-
- return matcher[ expando ] ?
- markFunction(function( seed, matches, context, xml ) {
- var elem,
- unmatched = matcher( seed, null, xml, [] ),
- i = seed.length;
-
- // Match elements unmatched by `matcher`
- while ( i-- ) {
- if ( (elem = unmatched[i]) ) {
- seed[i] = !(matches[i] = elem);
- }
- }
- }) :
- function( elem, context, xml ) {
- input[0] = elem;
- matcher( input, null, xml, results );
- return !results.pop();
- };
- }),
-
- "has": markFunction(function( selector ) {
- return function( elem ) {
- return Sizzle( selector, elem ).length > 0;
- };
- }),
-
- "contains": markFunction(function( text ) {
- return function( elem ) {
- return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
- };
- }),
-
- "enabled": function( elem ) {
- return elem.disabled === false;
- },
-
- "disabled": function( elem ) {
- return elem.disabled === true;
- },
-
- "checked": function( elem ) {
- // In CSS3, :checked should return both checked and selected elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- var nodeName = elem.nodeName.toLowerCase();
- return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
- },
-
- "selected": function( elem ) {
- // Accessing this property makes selected-by-default
- // options in Safari work properly
- if ( elem.parentNode ) {
- elem.parentNode.selectedIndex;
- }
-
- return elem.selected === true;
- },
-
- "parent": function( elem ) {
- return !Expr.pseudos["empty"]( elem );
- },
-
- "empty": function( elem ) {
- // http://www.w3.org/TR/selectors/#empty-pseudo
- // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
- // not comment, processing instructions, or others
- // Thanks to Diego Perini for the nodeName shortcut
- // Greater than "@" means alpha characters (specifically not starting with "#" or "?")
- var nodeType;
- elem = elem.firstChild;
- while ( elem ) {
- if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
- return false;
- }
- elem = elem.nextSibling;
- }
- return true;
- },
-
- "header": function( elem ) {
- return rheader.test( elem.nodeName );
- },
-
- "text": function( elem ) {
- var type, attr;
- // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
- // use getAttribute instead to test this case
- return elem.nodeName.toLowerCase() === "input" &&
- (type = elem.type) === "text" &&
- ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
- },
-
- // Input types
- "radio": createInputPseudo("radio"),
- "checkbox": createInputPseudo("checkbox"),
- "file": createInputPseudo("file"),
- "password": createInputPseudo("password"),
- "image": createInputPseudo("image"),
-
- "submit": createButtonPseudo("submit"),
- "reset": createButtonPseudo("reset"),
-
- "button": function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === "button" || name === "button";
- },
-
- "input": function( elem ) {
- return rinputs.test( elem.nodeName );
- },
-
- "focus": function( elem ) {
- var doc = elem.ownerDocument;
- return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
- },
-
- "active": function( elem ) {
- return elem === elem.ownerDocument.activeElement;
- },
-
- // Positional types
- "first": createPositionalPseudo(function() {
- return [ 0 ];
- }),
-
- "last": createPositionalPseudo(function( matchIndexes, length ) {
- return [ length - 1 ];
- }),
-
- "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
- return [ argument < 0 ? argument + length : argument ];
- }),
-
- "even": createPositionalPseudo(function( matchIndexes, length ) {
- for ( var i = 0; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "odd": createPositionalPseudo(function( matchIndexes, length ) {
- for ( var i = 1; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- })
- }
-};
-
-function siblingCheck( a, b ) {
-
- if ( a && b ) {
- var cur = a.nextSibling;
-
- while ( cur ) {
- if ( cur === b ) {
- return -1;
- }
-
- cur = cur.nextSibling;
- }
- }
-
- return a ? 1 : -1;
-}
-
-sortOrder = docElem.compareDocumentPosition ?
- function( a, b ) {
- var compare, parent;
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
- }
-
- if ( a.compareDocumentPosition && b.compareDocumentPosition ) {
- if ( (compare = a.compareDocumentPosition( b )) & 1 || (( parent = a.parentNode ) && parent.nodeType === 11) ) {
- if ( a === document || contains(document, a) ) {
- return -1;
- }
- if ( b === document || contains(document, b) ) {
- return 1;
- }
- return 0;
- }
- return compare & 4 ? -1 : 1;
- }
-
- return a.compareDocumentPosition ? -1 : 1;
- } :
- function( a, b ) {
- // The nodes are identical, we can exit early
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
-
- // Fallback to using sourceIndex (in IE) if it's available on both nodes
- } else if ( a.sourceIndex && b.sourceIndex ) {
- return ( ~b.sourceIndex || ( MAX_NEGATIVE ) ) - ( contains( document, a ) && ~a.sourceIndex || ( MAX_NEGATIVE ) );
- }
-
- var i = 0,
- ap = [ a ],
- bp = [ b ],
- aup = a.parentNode,
- bup = b.parentNode,
- cur = aup;
-
- // If no parents were found then the nodes are disconnected
- if ( a === document ) {
- return -1;
-
- } else if ( b === document ) {
- return 1;
-
- } else if ( !aup && !bup ) {
- return 0;
-
- } else if ( !bup ) {
- return -1;
-
- } else if ( !aup ) {
- return 1;
-
- // If the nodes are siblings (or identical) we can do a quick check
- } else if ( aup === bup ) {
- return siblingCheck( a, b );
- }
-
- // Otherwise they're somewhere else in the tree so we need
- // to build up a full list of the parentNodes for comparison
- while ( cur ) {
- ap.unshift( cur );
- cur = cur.parentNode;
- }
-
- cur = bup;
-
- while ( cur ) {
- bp.unshift( cur );
- cur = cur.parentNode;
- }
-
- // Walk down the tree looking for a discrepancy
- while ( ap[i] === bp[i] ) {
- i++;
- }
-
- // Prefer our document
- if ( i === 0 ) {
- if ( ap[0] === document || contains(document, ap[0]) ) {
- return -1;
- }
- if ( bp[0] === document || contains(document, bp[0]) ) {
- return 1;
- }
- return 0;
- }
-
- // We ended someplace up the tree so do a sibling check
- return siblingCheck( ap[i], bp[i] );
- };
-
-// Always assume the presence of duplicates if sort doesn't
-// pass them to our comparison function (as in Google Chrome).
-[0, 0].sort( sortOrder );
-baseHasDuplicate = !hasDuplicate;
-
-// Document sorting and removing duplicates
-Sizzle.uniqueSort = function( results ) {
- var elem,
- duplicates = [],
- i = 1,
- j = 0;
-
- hasDuplicate = baseHasDuplicate;
- results.sort( sortOrder );
-
- if ( hasDuplicate ) {
- for ( ; (elem = results[i]); i++ ) {
- if ( elem === results[ i - 1 ] ) {
- j = duplicates.push( i );
- }
- }
- while ( j-- ) {
- results.splice( duplicates[ j ], 1 );
- }
- }
-
- return results;
-};
-
-Sizzle.error = function( msg ) {
- throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-function tokenize( selector, parseOnly ) {
- var matched, match, tokens, type,
- soFar, groups, preFilters,
- cached = tokenCache[ expando ][ selector + " " ];
-
- if ( cached ) {
- return parseOnly ? 0 : cached.slice( 0 );
- }
-
- soFar = selector;
- groups = [];
- preFilters = Expr.preFilter;
-
- while ( soFar ) {
-
- // Comma and first run
- if ( !matched || (match = rcomma.exec( soFar )) ) {
- if ( match ) {
- // Don't consume trailing commas as valid
- soFar = soFar.slice( match[0].length ) || soFar;
- }
- groups.push( tokens = [] );
- }
-
- matched = false;
-
- // Combinators
- if ( (match = rcombinators.exec( soFar )) ) {
- tokens.push( matched = new Token( match.shift() ) );
- soFar = soFar.slice( matched.length );
-
- // Cast descendant combinators to space
- matched.type = match[0].replace( rtrim, " " );
- }
-
- // Filters
- for ( type in Expr.filter ) {
- if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
- (match = preFilters[ type ]( match ))) ) {
-
- tokens.push( matched = new Token( match.shift() ) );
- soFar = soFar.slice( matched.length );
- matched.type = type;
- matched.matches = match;
- }
- }
-
- if ( !matched ) {
- break;
- }
- }
-
- // Return the length of the invalid excess
- // if we're just parsing
- // Otherwise, throw an error or return tokens
- return parseOnly ?
- soFar.length :
- soFar ?
- Sizzle.error( selector ) :
- // Cache the tokens
- tokenCache( selector, groups ).slice( 0 );
-}
-
-function addCombinator( matcher, combinator, base ) {
- var dir = combinator.dir,
- checkNonElements = base && combinator.dir === "parentNode",
- doneName = done++;
-
- return combinator.first ?
- // Check against closest ancestor/preceding element
- function( elem, context, xml ) {
- while ( (elem = elem[ dir ]) ) {
- if ( checkNonElements || elem.nodeType === 1 ) {
- return matcher( elem, context, xml );
- }
- }
- } :
-
- // Check against all ancestor/preceding elements
- function( elem, context, xml ) {
- // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
- if ( !xml ) {
- var cache,
- dirkey = dirruns + " " + doneName + " ",
- cachedkey = dirkey + cachedruns;
- while ( (elem = elem[ dir ]) ) {
- if ( checkNonElements || elem.nodeType === 1 ) {
- if ( (cache = elem[ expando ]) === cachedkey ) {
- return elem.sizset;
- } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
- if ( elem.sizset ) {
- return elem;
- }
- } else {
- elem[ expando ] = cachedkey;
- if ( matcher( elem, context, xml ) ) {
- elem.sizset = true;
- return elem;
- }
- elem.sizset = false;
- }
- }
- }
- } else {
- while ( (elem = elem[ dir ]) ) {
- if ( checkNonElements || elem.nodeType === 1 ) {
- if ( matcher( elem, context, xml ) ) {
- return elem;
- }
- }
- }
- }
- };
-}
-
-function elementMatcher( matchers ) {
- return matchers.length > 1 ?
- function( elem, context, xml ) {
- var i = matchers.length;
- while ( i-- ) {
- if ( !matchers[i]( elem, context, xml ) ) {
- return false;
- }
- }
- return true;
- } :
- matchers[0];
-}
-
-function condense( unmatched, map, filter, context, xml ) {
- var elem,
- newUnmatched = [],
- i = 0,
- len = unmatched.length,
- mapped = map != null;
-
- for ( ; i < len; i++ ) {
- if ( (elem = unmatched[i]) ) {
- if ( !filter || filter( elem, context, xml ) ) {
- newUnmatched.push( elem );
- if ( mapped ) {
- map.push( i );
- }
- }
- }
- }
-
- return newUnmatched;
-}
-
-function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
- if ( postFilter && !postFilter[ expando ] ) {
- postFilter = setMatcher( postFilter );
- }
- if ( postFinder && !postFinder[ expando ] ) {
- postFinder = setMatcher( postFinder, postSelector );
- }
- return markFunction(function( seed, results, context, xml ) {
- var temp, i, elem,
- preMap = [],
- postMap = [],
- preexisting = results.length,
-
- // Get initial elements from seed or context
- elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
-
- // Prefilter to get matcher input, preserving a map for seed-results synchronization
- matcherIn = preFilter && ( seed || !selector ) ?
- condense( elems, preMap, preFilter, context, xml ) :
- elems,
-
- matcherOut = matcher ?
- // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
- postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
-
- // ...intermediate processing is necessary
- [] :
-
- // ...otherwise use results directly
- results :
- matcherIn;
-
- // Find primary matches
- if ( matcher ) {
- matcher( matcherIn, matcherOut, context, xml );
- }
-
- // Apply postFilter
- if ( postFilter ) {
- temp = condense( matcherOut, postMap );
- postFilter( temp, [], context, xml );
-
- // Un-match failing elements by moving them back to matcherIn
- i = temp.length;
- while ( i-- ) {
- if ( (elem = temp[i]) ) {
- matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
- }
- }
- }
-
- if ( seed ) {
- if ( postFinder || preFilter ) {
- if ( postFinder ) {
- // Get the final matcherOut by condensing this intermediate into postFinder contexts
- temp = [];
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) ) {
- // Restore matcherIn since elem is not yet a final match
- temp.push( (matcherIn[i] = elem) );
- }
- }
- postFinder( null, (matcherOut = []), temp, xml );
- }
-
- // Move matched elements from seed to results to keep them synchronized
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) &&
- (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
-
- seed[temp] = !(results[temp] = elem);
- }
- }
- }
-
- // Add elements to results, through postFinder if defined
- } else {
- matcherOut = condense(
- matcherOut === results ?
- matcherOut.splice( preexisting, matcherOut.length ) :
- matcherOut
- );
- if ( postFinder ) {
- postFinder( null, results, matcherOut, xml );
- } else {
- push.apply( results, matcherOut );
- }
- }
- });
-}
-
-function matcherFromTokens( tokens ) {
- var checkContext, matcher, j,
- len = tokens.length,
- leadingRelative = Expr.relative[ tokens[0].type ],
- implicitRelative = leadingRelative || Expr.relative[" "],
- i = leadingRelative ? 1 : 0,
-
- // The foundational matcher ensures that elements are reachable from top-level context(s)
- matchContext = addCombinator( function( elem ) {
- return elem === checkContext;
- }, implicitRelative, true ),
- matchAnyContext = addCombinator( function( elem ) {
- return indexOf.call( checkContext, elem ) > -1;
- }, implicitRelative, true ),
- matchers = [ function( elem, context, xml ) {
- return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
- (checkContext = context).nodeType ?
- matchContext( elem, context, xml ) :
- matchAnyContext( elem, context, xml ) );
- } ];
-
- for ( ; i < len; i++ ) {
- if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
- matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
- } else {
- matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
-
- // Return special upon seeing a positional matcher
- if ( matcher[ expando ] ) {
- // Find the next relative operator (if any) for proper handling
- j = ++i;
- for ( ; j < len; j++ ) {
- if ( Expr.relative[ tokens[j].type ] ) {
- break;
- }
- }
- return setMatcher(
- i > 1 && elementMatcher( matchers ),
- i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
- matcher,
- i < j && matcherFromTokens( tokens.slice( i, j ) ),
- j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
- j < len && tokens.join("")
- );
- }
- matchers.push( matcher );
- }
- }
-
- return elementMatcher( matchers );
-}
-
-function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
- // A counter to specify which element is currently being matched
- var matcherCachedRuns = 0,
- bySet = setMatchers.length > 0,
- byElement = elementMatchers.length > 0,
- superMatcher = function( seed, context, xml, results, expandContext ) {
- var elem, j, matcher,
- setMatched = [],
- matchedCount = 0,
- i = "0",
- unmatched = seed && [],
- outermost = expandContext != null,
- contextBackup = outermostContext,
- // We must always have either seed elements or context
- elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
- // Nested matchers should use non-integer dirruns
- dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
-
- if ( outermost ) {
- outermostContext = context !== document && context;
- cachedruns = matcherCachedRuns;
- }
-
- // Add elements passing elementMatchers directly to results
- for ( ; (elem = elems[i]) != null; i++ ) {
- if ( byElement && elem ) {
- for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
- if ( matcher( elem, context, xml ) ) {
- results.push( elem );
- break;
- }
- }
- if ( outermost ) {
- dirruns = dirrunsUnique;
- cachedruns = ++matcherCachedRuns;
- }
- }
-
- // Track unmatched elements for set filters
- if ( bySet ) {
- // They will have gone through all possible matchers
- if ( (elem = !matcher && elem) ) {
- matchedCount--;
- }
-
- // Lengthen the array for every element, matched or not
- if ( seed ) {
- unmatched.push( elem );
- }
- }
- }
-
- // Apply set filters to unmatched elements
- // `i` starts as a string, so matchedCount would equal "00" if there are no elements
- matchedCount += i;
- if ( bySet && i !== matchedCount ) {
- for ( j = 0; (matcher = setMatchers[j]); j++ ) {
- matcher( unmatched, setMatched, context, xml );
- }
-
- if ( seed ) {
- // Reintegrate element matches to eliminate the need for sorting
- if ( matchedCount > 0 ) {
- while ( i-- ) {
- if ( !(unmatched[i] || setMatched[i]) ) {
- setMatched[i] = pop.call( results );
- }
- }
- }
-
- // Discard index placeholder values to get only actual matches
- setMatched = condense( setMatched );
- }
-
- // Add matches to results
- push.apply( results, setMatched );
-
- // Seedless set matches succeeding multiple successful matchers stipulate sorting
- if ( outermost && !seed && setMatched.length > 0 &&
- ( matchedCount + setMatchers.length ) > 1 ) {
-
- Sizzle.uniqueSort( results );
- }
- }
-
- // Override manipulation of globals by nested matchers
- if ( outermost ) {
- dirruns = dirrunsUnique;
- outermostContext = contextBackup;
- }
-
- return unmatched;
- };
-
- return bySet ?
- markFunction( superMatcher ) :
- superMatcher;
-}
-
-compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
- var i,
- setMatchers = [],
- elementMatchers = [],
- cached = compilerCache[ expando ][ selector + " " ];
-
- if ( !cached ) {
- // Generate a function of recursive functions that can be used to check each element
- if ( !group ) {
- group = tokenize( selector );
- }
- i = group.length;
- while ( i-- ) {
- cached = matcherFromTokens( group[i] );
- if ( cached[ expando ] ) {
- setMatchers.push( cached );
- } else {
- elementMatchers.push( cached );
- }
- }
-
- // Cache the compiled function
- cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
- }
- return cached;
-};
-
-function multipleContexts( selector, contexts, results ) {
- var i = 0,
- len = contexts.length;
- for ( ; i < len; i++ ) {
- Sizzle( selector, contexts[i], results );
- }
- return results;
-}
-
-function select( selector, context, results, seed, xml ) {
- var i, tokens, token, type, find,
- match = tokenize( selector );
-
- if ( !seed ) {
- // Try to minimize operations if there is only one group
- if ( match.length === 1 ) {
-
- // Take a shortcut and set the context if the root selector is an ID
- tokens = match[0] = match[0].slice( 0 );
- if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
- context.nodeType === 9 && !xml &&
- Expr.relative[ tokens[1].type ] ) {
-
- context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
- if ( !context ) {
- return results;
- }
-
- selector = selector.slice( tokens.shift().length );
- }
-
- // Fetch a seed set for right-to-left matching
- for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
- token = tokens[i];
-
- // Abort if we hit a combinator
- if ( Expr.relative[ (type = token.type) ] ) {
- break;
- }
- if ( (find = Expr.find[ type ]) ) {
- // Search, expanding context for leading sibling combinators
- if ( (seed = find(
- token.matches[0].replace( rbackslash, "" ),
- rsibling.test( tokens[0].type ) && context.parentNode || context,
- xml
- )) ) {
-
- // If seed is empty or no tokens remain, we can return early
- tokens.splice( i, 1 );
- selector = seed.length && tokens.join("");
- if ( !selector ) {
- push.apply( results, slice.call( seed, 0 ) );
- return results;
- }
-
- break;
- }
- }
- }
- }
- }
-
- // Compile and execute a filtering function
- // Provide `match` to avoid retokenization if we modified the selector above
- compile( selector, match )(
- seed,
- context,
- xml,
- results,
- rsibling.test( selector )
- );
- return results;
-}
-
-if ( document.querySelectorAll ) {
- (function() {
- var disconnectedMatch,
- oldSelect = select,
- rescape = /'|\\/g,
- rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
-
- // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
- // A support test would require too much code (would include document ready)
- rbuggyQSA = [ ":focus" ],
-
- // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
- // A support test would require too much code (would include document ready)
- // just skip matchesSelector for :active
- rbuggyMatches = [ ":active" ],
- matches = docElem.matchesSelector ||
- docElem.mozMatchesSelector ||
- docElem.webkitMatchesSelector ||
- docElem.oMatchesSelector ||
- docElem.msMatchesSelector;
-
- // Build QSA regex
- // Regex strategy adopted from Diego Perini
- assert(function( div ) {
- // Select is set to empty string on purpose
- // This is to test IE's treatment of not explictly
- // setting a boolean content attribute,
- // since its presence should be enough
- // http://bugs.jquery.com/ticket/12359
- div.innerHTML = "<select><option selected=''></option></select>";
-
- // IE8 - Some boolean attributes are not treated correctly
- if ( !div.querySelectorAll("[selected]").length ) {
- rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
- }
-
- // Webkit/Opera - :checked should return selected option elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- // IE8 throws error here (do not put tests after this one)
- if ( !div.querySelectorAll(":checked").length ) {
- rbuggyQSA.push(":checked");
- }
- });
-
- assert(function( div ) {
-
- // Opera 10-12/IE9 - ^= $= *= and empty values
- // Should not select anything
- div.innerHTML = "<p test=''></p>";
- if ( div.querySelectorAll("[test^='']").length ) {
- rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
- }
-
- // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
- // IE8 throws error here (do not put tests after this one)
- div.innerHTML = "<input type='hidden'/>";
- if ( !div.querySelectorAll(":enabled").length ) {
- rbuggyQSA.push(":enabled", ":disabled");
- }
- });
-
- // rbuggyQSA always contains :focus, so no need for a length check
- rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
-
- select = function( selector, context, results, seed, xml ) {
- // Only use querySelectorAll when not filtering,
- // when this is not xml,
- // and when no QSA bugs apply
- if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
- var groups, i,
- old = true,
- nid = expando,
- newContext = context,
- newSelector = context.nodeType === 9 && selector;
-
- // qSA works strangely on Element-rooted queries
- // We can work around this by specifying an extra ID on the root
- // and working up from there (Thanks to Andrew Dupont for the technique)
- // IE 8 doesn't work on object elements
- if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
- groups = tokenize( selector );
-
- if ( (old = context.getAttribute("id")) ) {
- nid = old.replace( rescape, "\\$&" );
- } else {
- context.setAttribute( "id", nid );
- }
- nid = "[id='" + nid + "'] ";
-
- i = groups.length;
- while ( i-- ) {
- groups[i] = nid + groups[i].join("");
- }
- newContext = rsibling.test( selector ) && context.parentNode || context;
- newSelector = groups.join(",");
- }
-
- if ( newSelector ) {
- try {
- push.apply( results, slice.call( newContext.querySelectorAll(
- newSelector
- ), 0 ) );
- return results;
- } catch(qsaError) {
- } finally {
- if ( !old ) {
- context.removeAttribute("id");
- }
- }
- }
- }
-
- return oldSelect( selector, context, results, seed, xml );
- };
-
- if ( matches ) {
- assert(function( div ) {
- // Check to see if it's possible to do matchesSelector
- // on a disconnected node (IE 9)
- disconnectedMatch = matches.call( div, "div" );
-
- // This should fail with an exception
- // Gecko does not error, returns false instead
- try {
- matches.call( div, "[test!='']:sizzle" );
- rbuggyMatches.push( "!=", pseudos );
- } catch ( e ) {}
- });
-
- // rbuggyMatches always contains :active and :focus, so no need for a length check
- rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
-
- Sizzle.matchesSelector = function( elem, expr ) {
- // Make sure that attribute selectors are quoted
- expr = expr.replace( rattributeQuotes, "='$1']" );
-
- // rbuggyMatches always contains :active, so no need for an existence check
- if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
- try {
- var ret = matches.call( elem, expr );
-
- // IE 9's matchesSelector returns false on disconnected nodes
- if ( ret || disconnectedMatch ||
- // As well, disconnected nodes are said to be in a document
- // fragment in IE 9
- elem.document && elem.document.nodeType !== 11 ) {
- return ret;
- }
- } catch(e) {}
- }
-
- return Sizzle( expr, null, null, [ elem ] ).length > 0;
- };
- }
- })();
-}
-
-// Deprecated
-Expr.pseudos["nth"] = Expr.pseudos["eq"];
-
-// Easy API for creating new setFilters
-function setFilters() {}
-Expr.filters = setFilters.prototype = Expr.pseudos;
-Expr.setFilters = new setFilters();
-
-// EXPOSE
-if ( typeof define === "function" && define.amd ) {
- define(function() { return Sizzle; });
-} else {
- window.Sizzle = Sizzle;
-}
-// EXPOSE
-
-})( window );
|
0b3db7cbf5eada6176af266cc6bebfcd1332f115
|
restlet-framework-java
|
- Additional WADL refactorings.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java
index 0752ec6751..0ad154478f 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java
@@ -32,6 +32,7 @@
import java.util.Iterator;
import java.util.List;
+import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.util.XmlWriter;
@@ -47,39 +48,66 @@ public class FaultInfo extends RepresentationInfo {
/**
* Constructor.
+ *
+ * @param status
+ * The associated status code.
*/
- public FaultInfo() {
+ public FaultInfo(Status status) {
super();
+ getStatuses().add(status);
}
/**
* Constructor with a single documentation element.
*
+ * @param status
+ * The associated status code.
* @param documentation
* A single documentation element.
*/
- public FaultInfo(DocumentationInfo documentation) {
+ public FaultInfo(Status status, DocumentationInfo documentation) {
super(documentation);
+ getStatuses().add(status);
}
/**
* Constructor with a list of documentation elements.
*
+ * @param status
+ * The associated status code.
* @param documentations
* The list of documentation elements.
*/
- public FaultInfo(List<DocumentationInfo> documentations) {
+ public FaultInfo(Status status, List<DocumentationInfo> documentations) {
super(documentations);
+ getStatuses().add(status);
}
/**
* Constructor with a single documentation element.
*
+ * @param status
+ * The associated status code.
* @param documentation
* A single documentation element.
*/
- public FaultInfo(String documentation) {
- super(documentation);
+ public FaultInfo(Status status, String documentation) {
+ this(status, new DocumentationInfo(documentation));
+ }
+
+ /**
+ * Constructor with a single documentation element.
+ *
+ * @param status
+ * The associated status code.
+ * @param mediaType
+ * The fault representation's media type.
+ * @param documentation
+ * A single documentation element.
+ */
+ public FaultInfo(Status status, MediaType mediaType, String documentation) {
+ this(status, new DocumentationInfo(documentation));
+ setMediaType(mediaType);
}
/**
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
index 5ac681ffc5..0aac5ee5ab 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java
@@ -32,8 +32,10 @@
import java.util.List;
import java.util.Map;
+import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
+import org.restlet.data.Status;
import org.restlet.resource.Variant;
import org.restlet.util.XmlWriter;
import org.xml.sax.SAXException;
@@ -98,6 +100,24 @@ public MethodInfo(String documentation) {
super(documentation);
}
+ /**
+ * Adds a new fault to the response.
+ *
+ * @param status
+ * The associated status code.
+ * @param mediaType
+ * The fault representation's media type.
+ * @param documentation
+ * A single documentation element.
+ * @return The created fault description.
+ */
+ public FaultInfo addFault(Status status, MediaType mediaType,
+ String documentation) {
+ FaultInfo result = new FaultInfo(status, mediaType, documentation);
+ getResponse().getFaults().add(result);
+ return result;
+ }
+
/**
* Adds a new request parameter.
*
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java
index 9eadc8c8c6..d6af850a75 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java
@@ -530,7 +530,8 @@ public void startElement(String uri, String localName, String qName,
}
pushState(State.DOCUMENTATION);
} else if (localName.equals("fault")) {
- this.currentFault = new FaultInfo();
+ this.currentFault = new FaultInfo(null);
+
if (attrs.getIndex("id") != -1) {
this.currentFault.setIdentifier(attrs.getValue("id"));
}
|
855142e35dc21c03b1c9bb0a33992e283a0b8791
|
kotlin
|
move test output to one level down--for ReadClassDataTest and CompileJavaAgainstKotlinTest-
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/tests/org/jetbrains/jet/CompileJavaAgainstKotlinTest.java b/compiler/tests/org/jetbrains/jet/CompileJavaAgainstKotlinTest.java
index 8bb9e576bc676..b856970872da2 100644
--- a/compiler/tests/org/jetbrains/jet/CompileJavaAgainstKotlinTest.java
+++ b/compiler/tests/org/jetbrains/jet/CompileJavaAgainstKotlinTest.java
@@ -53,7 +53,7 @@ public String getName() {
@Override
protected void setUp() throws Exception {
super.setUp();
- tmpdir = new File("tmp/" + this.getClass().getSimpleName() + "." + this.getName());
+ tmpdir = JetTestUtils.tmpDirForTest(this);
JetTestUtils.recreateDirectory(tmpdir);
}
diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java
index dc777e336faaf..468862c185255 100644
--- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java
+++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java
@@ -2,6 +2,7 @@
import com.google.common.collect.Lists;
import com.intellij.openapi.Disposable;
+import junit.framework.TestCase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory;
import org.jetbrains.jet.lang.diagnostics.Diagnostic;
@@ -166,6 +167,10 @@ public static void rmrf(File file) {
file.delete();
}
}
+
+ public static File tmpDirForTest(TestCase test) {
+ return new File("tmp/" + test.getClass().getSimpleName() + "/" + test.getName());
+ }
public static void recreateDirectory(File file) throws IOException {
rmrf(file);
diff --git a/compiler/tests/org/jetbrains/jet/ReadClassDataTest.java b/compiler/tests/org/jetbrains/jet/ReadClassDataTest.java
index d7e988b905295..abc9bab89f850 100644
--- a/compiler/tests/org/jetbrains/jet/ReadClassDataTest.java
+++ b/compiler/tests/org/jetbrains/jet/ReadClassDataTest.java
@@ -62,7 +62,7 @@ public ReadClassDataTest(@NotNull File testFile) {
@Override
protected void setUp() throws Exception {
super.setUp();
- tmpdir = new File("tmp/" + this.getClass().getSimpleName() + "." + this.getName());
+ tmpdir = JetTestUtils.tmpDirForTest(this);
JetTestUtils.recreateDirectory(tmpdir);
}
|
250ac825075785eef0c544670133eb590aaf1168
|
orientdb
|
Fixed problem with LET and context variables--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/src/main/java/com/orientechnologies/orient/etl/OAbstractETLComponent.java b/src/main/java/com/orientechnologies/orient/etl/OAbstractETLComponent.java
index 3479d210f96..35bb3a519ff 100644
--- a/src/main/java/com/orientechnologies/orient/etl/OAbstractETLComponent.java
+++ b/src/main/java/com/orientechnologies/orient/etl/OAbstractETLComponent.java
@@ -103,7 +103,7 @@ protected Object resolve(final Object iContent) {
Object value = null;
if (iContent instanceof String) {
- if (((String) iContent).startsWith("$"))
+ if (((String) iContent).startsWith("$") && !((String) iContent).startsWith(OSystemVariableResolver.VAR_BEGIN))
value = context.getVariable(iContent.toString());
else
value = OVariableParser.resolveVariables((String) iContent, OSystemVariableResolver.VAR_BEGIN,
diff --git a/src/main/java/com/orientechnologies/orient/etl/block/OLetBlock.java b/src/main/java/com/orientechnologies/orient/etl/block/OLetBlock.java
index 37bb615cf11..e81888aba56 100644
--- a/src/main/java/com/orientechnologies/orient/etl/block/OLetBlock.java
+++ b/src/main/java/com/orientechnologies/orient/etl/block/OLetBlock.java
@@ -26,18 +26,27 @@
public class OLetBlock extends OAbstractBlock {
protected String name;
protected OSQLFilter expression;
+ protected Object value;
@Override
public ODocument getConfiguration() {
return new ODocument().fromJSON("{parameters:[{name:{optional:false,description:'Variable name'}},"
- + "{value:{optional:false,description:'Variable value'}}]}");
+ + "{value:{optional:true,description:'Variable value'}}"
+ + "{expression:{optional:true,description:'Expression to evaluate'}}" + "]}");
}
@Override
- public void configure(OETLProcessor iProcessor, final ODocument iConfiguration, OBasicCommandContext iContext) {
+ public void configure(OETLProcessor iProcessor, final ODocument iConfiguration, final OBasicCommandContext iContext) {
super.configure(iProcessor, iConfiguration, iContext);
+
name = iConfiguration.field("name");
- expression = new OSQLFilter((String) iConfiguration.field("value"), iContext, null);
+ if (iConfiguration.containsField("value")) {
+ value = iConfiguration.field("value");
+ } else
+ expression = new OSQLFilter((String) iConfiguration.field("expression"), iContext, null);
+
+ if (value == null && expression == null)
+ throw new IllegalArgumentException("'value' or 'expression' parameter are mandatory in Let Transformer");
}
@Override
@@ -47,6 +56,9 @@ public String getName() {
@Override
public void executeBlock() {
- context.setVariable(name, expression.evaluate(null, null, context));
+ if (expression != null)
+ context.setVariable(name, expression.evaluate(null, null, context));
+ else
+ context.setVariable(name, resolve(value));
}
}
diff --git a/src/main/resources/config-dbpedia.json b/src/main/resources/config-dbpedia.json
index c122848a1f5..217d8f313cb 100644
--- a/src/main/resources/config-dbpedia.json
+++ b/src/main/resources/config-dbpedia.json
@@ -6,8 +6,8 @@
parallel: true
},
begin: [
- { let: { name: "$filePath", value: "$fileDirectory.append( $fileName )"} },
- { let: { name: "$className", value: "$fileName.substring( 0, $fileName.indexOf('.') )"} }
+ { let: { name: "$filePath", expression: "$fileDirectory.append( $fileName )"} },
+ { let: { name: "$className", expression: "$fileName.substring( 0, $fileName.indexOf('.') )"} }
],
source : {
file: { path: "$filePath", lock : true }
|
135f05e6728a3a0eb02c8974dafca434557080c0
|
drools
|
JBRULES-1736 Dynamically generated Types -Must get- classloader from the rulebase root classloader now--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@21573 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-clips/.classpath b/drools-clips/.classpath
index d078808cf23..e330ced3ca6 100644
--- a/drools-clips/.classpath
+++ b/drools-clips/.classpath
@@ -9,7 +9,21 @@
<classpathentry kind="src" path="/drools-compiler"/>
<classpathentry kind="src" path="/drools-core"/>
<classpathentry kind="var" path="M2_REPO/org/mvel/mvel/2.0-dp4/mvel-2.0-dp4.jar"/>
- <classpathentry kind="var" path="M2_REPO/org/antlr/antlr-runtime/3.0/antlr-runtime-3.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/antlr/antlr-runtime/3.0.1/antlr-runtime-3.0.1.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/antlr/stringtemplate/3.1-b1/stringtemplate-3.1-b1.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/antlr/gunit/1.0.1/gunit-1.0.1.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/apache/maven/maven-project/2.0/maven-project-2.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/apache/maven/maven-profile/2.0/maven-profile-2.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/apache/maven/maven-model/2.0/maven-model-2.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/codehaus/plexus/plexus-utils/1.0.4/plexus-utils-1.0.4.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/codehaus/plexus/plexus-container-default/1.0-alpha-8/plexus-container-default-1.0-alpha-8.jar"/>
+ <classpathentry kind="var" path="M2_REPO/classworlds/classworlds/1.1-alpha-2/classworlds-1.1-alpha-2.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/apache/maven/maven-artifact-manager/2.0/maven-artifact-manager-2.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/apache/maven/maven-repository-metadata/2.0/maven-repository-metadata-2.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/apache/maven/maven-artifact/2.0/maven-artifact-2.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/apache/maven/wagon/wagon-provider-api/1.0-alpha-5/wagon-provider-api-1.0-alpha-5.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/antlr/antlr/3.0.1/antlr-3.0.1.jar"/>
+ <classpathentry kind="var" path="M2_REPO/antlr/antlr/2.7.7/antlr-2.7.7.jar"/>
<classpathentry kind="var" path="M2_REPO/org/eclipse/jdt/core/3.2.3.v_686_R32x/core-3.2.3.v_686_R32x.jar"/>
<classpathentry kind="var" path="M2_REPO/janino/janino/2.5.10/janino-2.5.10.jar"/>
</classpath>
\ No newline at end of file
diff --git a/drools-clips/src/main/java/org/drools/clips/ClipsShell.java b/drools-clips/src/main/java/org/drools/clips/ClipsShell.java
index b9406261086..c3fd0da41c2 100644
--- a/drools-clips/src/main/java/org/drools/clips/ClipsShell.java
+++ b/drools-clips/src/main/java/org/drools/clips/ClipsShell.java
@@ -403,7 +403,8 @@ public void lispFormHandler(LispForm lispForm) {
context.addPackageImport( importName.substring( 0,
importName.length() - 2 ) );
} else {
- Class cls = pkg.getDialectRuntimeRegistry().getClassLoader().loadClass( importName );
+
+ Class cls = ((InternalRuleBase)ruleBase).getRootClassLoader().loadClass( importName );
context.addImport( cls.getSimpleName(),
(Class) cls );
}
@@ -418,7 +419,7 @@ public void lispFormHandler(LispForm lispForm) {
}
ClassLoader tempClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader( pkg.getPackageScopeClassLoader() );
+ Thread.currentThread().setContextClassLoader( ((InternalRuleBase)ruleBase).getRootClassLoader() );
ExpressionCompiler expr = new ExpressionCompiler( appendable.toString() );
Serializable executable = expr.compile( context );
diff --git a/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java b/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java
index 251ba45fdf0..6d8994bccc1 100644
--- a/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java
+++ b/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java
@@ -31,6 +31,7 @@
import org.drools.clips.functions.RunFunction;
import org.drools.clips.functions.SetFunction;
import org.drools.clips.functions.SwitchFunction;
+import org.drools.common.InternalRuleBase;
import org.drools.rule.Package;
import org.drools.rule.Rule;
@@ -251,7 +252,7 @@ public void FIXME_testTemplateCreation2() throws Exception {
this.shell.eval( "(defrule xxx (PersonTemplate (name ?name&bob) (age 30) ) (PersonTemplate (name ?name) (age 35)) => (printout t xx \" \" (eq 1 1) ) )" );
this.shell.eval( "(assert (PersonTemplate (name 'mike') (age 34)))" );
- Class personClass = this.shell.getStatefulSession().getRuleBase().getPackage( "MAIN" ).getPackageScopeClassLoader().loadClass( "MAIN.PersonTemplate" );
+ Class personClass = ((InternalRuleBase)this.shell.getStatefulSession().getRuleBase()).getRootClassLoader().loadClass( "MAIN.PersonTemplate" );
assertNotNull( personClass );
}
@@ -287,7 +288,7 @@ public void testTemplateCreationWithJava() throws Exception {
pkg.getRules().length );
WorkingMemory wm = shell.getStatefulSession();
- Class personClass = this.shell.getStatefulSession().getRuleBase().getPackage( "MAIN" ).getPackageScopeClassLoader().loadClass( "MAIN.Person" );
+ Class personClass = ((InternalRuleBase)this.shell.getStatefulSession().getRuleBase()).getRootClassLoader().loadClass( "MAIN.Person" );
Method nameMethod = personClass.getMethod( "setName",
new Class[]{String.class} );
|
ac61b13a7c8284dea58ca4d2a046a44d317ced00
|
spring-framework
|
AnnotatedElementUtils wraps unexpected exceptions- with descriptive IllegalStateException--Issue: SPR-10441-
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java
index 8494c0f51d25..78fc584adb46 100644
--- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java
+++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java
@@ -42,7 +42,6 @@ public class AnnotatedElementUtils {
public static Set<String> getMetaAnnotationTypes(AnnotatedElement element, String annotationType) {
final Set<String> types = new LinkedHashSet<String>();
process(element, annotationType, true, new Processor<Object>() {
-
@Override
public Object process(Annotation annotation, int metaDepth) {
if (metaDepth > 0) {
@@ -50,7 +49,6 @@ public Object process(Annotation annotation, int metaDepth) {
}
return null;
}
-
@Override
public void postProcess(Annotation annotation, Object result) {
}
@@ -60,7 +58,6 @@ public void postProcess(Annotation annotation, Object result) {
public static boolean hasMetaAnnotationTypes(AnnotatedElement element, String annotationType) {
return Boolean.TRUE.equals(process(element, annotationType, true, new Processor<Boolean>() {
-
@Override
public Boolean process(Annotation annotation, int metaDepth) {
if (metaDepth > 0) {
@@ -68,7 +65,6 @@ public Boolean process(Annotation annotation, int metaDepth) {
}
return null;
}
-
@Override
public void postProcess(Annotation annotation, Boolean result) {
}
@@ -77,12 +73,10 @@ public void postProcess(Annotation annotation, Boolean result) {
public static boolean isAnnotated(AnnotatedElement element, String annotationType) {
return Boolean.TRUE.equals(process(element, annotationType, true, new Processor<Boolean>() {
-
@Override
public Boolean process(Annotation annotation, int metaDepth) {
return Boolean.TRUE;
}
-
@Override
public void postProcess(Annotation annotation, Boolean result) {
}
@@ -97,12 +91,10 @@ public static AnnotationAttributes getAnnotationAttributes(AnnotatedElement elem
final boolean classValuesAsString, final boolean nestedAnnotationsAsMap) {
return process(element, annotationType, true, new Processor<AnnotationAttributes>() {
-
@Override
public AnnotationAttributes process(Annotation annotation, int metaDepth) {
return AnnotationUtils.getAnnotationAttributes(annotation, classValuesAsString, nestedAnnotationsAsMap);
}
-
@Override
public void postProcess(Annotation annotation, AnnotationAttributes result) {
for (String key : result.keySet()) {
@@ -117,8 +109,7 @@ public void postProcess(Annotation annotation, AnnotationAttributes result) {
});
}
- public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element,
- final String annotationType) {
+ public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element, String annotationType) {
return getAllAnnotationAttributes(element, annotationType, false, false);
}
@@ -127,7 +118,6 @@ public static MultiValueMap<String, Object> getAllAnnotationAttributes(Annotated
final MultiValueMap<String, Object> attributes = new LinkedMultiValueMap<String, Object>();
process(element, annotationType, false, new Processor<Void>() {
-
@Override
public Void process(Annotation annotation, int metaDepth) {
if (annotation.annotationType().getName().equals(annotationType)) {
@@ -138,7 +128,6 @@ public Void process(Annotation annotation, int metaDepth) {
}
return null;
}
-
@Override
public void postProcess(Annotation annotation, Void result) {
for (String key : attributes.keySet()) {
@@ -157,12 +146,10 @@ public void postProcess(Annotation annotation, Void result) {
/**
* Process all annotations of the specified {@code annotationType} and
* recursively all meta-annotations on the specified {@code element}.
- *
* <p>If the {@code traverseClassHierarchy} flag is {@code true} and the sought
* annotation is neither <em>directly present</em> on the given element nor
* present on the given element as a meta-annotation, then the algorithm will
* recursively search through the class hierarchy of the given element.
- *
* @param element the annotated element
* @param annotationType the annotation type to find
* @param traverseClassHierarchy whether or not to traverse up the class
@@ -172,19 +159,23 @@ public void postProcess(Annotation annotation, Void result) {
*/
private static <T> T process(AnnotatedElement element, String annotationType, boolean traverseClassHierarchy,
Processor<T> processor) {
- return doProcess(element, annotationType, traverseClassHierarchy, processor, new HashSet<AnnotatedElement>(), 0);
+
+ try {
+ return doProcess(element, annotationType, traverseClassHierarchy, processor, new HashSet<AnnotatedElement>(), 0);
+ }
+ catch (Throwable ex) {
+ throw new IllegalStateException("Failed to introspect annotations: " + element, ex);
+ }
}
/**
* Perform the search algorithm for the {@link #process} method, avoiding
* endless recursion by tracking which annotated elements have already been
* <em>visited</em>.
- *
* <p>The {@code metaDepth} parameter represents the depth of the annotation
* relative to the initial element. For example, an annotation that is
* <em>present</em> on the element will have a depth of 0; a meta-annotation
* will have a depth of 1; and a meta-meta-annotation will have a depth of 2.
- *
* @param element the annotated element
* @param annotationType the annotation type to find
* @param traverseClassHierarchy whether or not to traverse up the class
@@ -198,10 +189,8 @@ private static <T> T doProcess(AnnotatedElement element, String annotationType,
Processor<T> processor, Set<AnnotatedElement> visited, int metaDepth) {
if (visited.add(element)) {
-
- Annotation[] annotations = traverseClassHierarchy ? element.getDeclaredAnnotations()
- : element.getAnnotations();
-
+ Annotation[] annotations =
+ (traverseClassHierarchy ? element.getDeclaredAnnotations() : element.getAnnotations());
for (Annotation annotation : annotations) {
if (annotation.annotationType().getName().equals(annotationType) || metaDepth > 0) {
T result = processor.process(annotation, metaDepth);
@@ -216,7 +205,6 @@ private static <T> T doProcess(AnnotatedElement element, String annotationType,
}
}
}
-
for (Annotation annotation : annotations) {
if (!isInJavaLangAnnotationPackage(annotation)) {
T result = doProcess(annotation.annotationType(), annotationType, traverseClassHierarchy,
@@ -227,7 +215,6 @@ private static <T> T doProcess(AnnotatedElement element, String annotationType,
}
}
}
-
if (traverseClassHierarchy && element instanceof Class) {
Class<?> superclass = ((Class<?>) element).getSuperclass();
if (superclass != null && !superclass.equals(Object.class)) {
@@ -239,7 +226,6 @@ private static <T> T doProcess(AnnotatedElement element, String annotationType,
}
}
}
-
return null;
}
@@ -252,13 +238,11 @@ private static interface Processor<T> {
/**
* Called to process the annotation.
- *
* <p>The {@code metaDepth} parameter represents the depth of the
* annotation relative to the initial element. For example, an annotation
* that is <em>present</em> on the element will have a depth of 0; a
* meta-annotation will have a depth of 1; and a meta-meta-annotation
* will have a depth of 2.
- *
* @param annotation the annotation to process
* @param metaDepth the depth of the annotation relative to the initial element
* @return the result of the processing or {@code null} to continue
|
6945d04785d7322df45b5c71053ba18431f606cd
|
orientdb
|
Further work or traverse: - supported new- OSQLPredicate to specify a predicate using SQL language--
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/build.number b/build.number
index 19e55caca3e..1c3c6d61de5 100644
--- a/build.number
+++ b/build.number
@@ -1,3 +1,3 @@
#Build Number for ANT. Do not edit!
-#Sat Apr 28 19:00:06 CEST 2012
-build.number=11815
+#Sat Apr 28 20:56:54 CEST 2012
+build.number=11818
diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverse.java b/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverse.java
index 2416ee1d4c8..358eedfa27b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverse.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverse.java
@@ -45,7 +45,7 @@ public class OTraverse implements OCommand, Iterable<OIdentifiable>, Iterator<OI
*
* @see com.orientechnologies.orient.core.command.OCommand#execute()
*/
- public Object execute() {
+ public List<OIdentifiable> execute() {
final List<OIdentifiable> result = new ArrayList<OIdentifiable>();
while (hasNext())
result.add(next());
@@ -114,6 +114,17 @@ public OTraverseContext getContext() {
return context;
}
+ public OTraverse target(final Iterable<? extends OIdentifiable> iTarget) {
+ return target(iTarget.iterator());
+ }
+
+ public OTraverse target(final OIdentifiable... iRecords) {
+ final List<OIdentifiable> list = new ArrayList<OIdentifiable>();
+ for (OIdentifiable id : iRecords)
+ list.add(id);
+ return target(list.iterator());
+ }
+
@SuppressWarnings("unchecked")
public OTraverse target(final Iterator<? extends OIdentifiable> iTarget) {
target = iTarget;
@@ -147,6 +158,12 @@ public OTraverse fields(final Collection<String> iFields) {
return this;
}
+ public OTraverse fields(final String... iFields) {
+ for (String f : iFields)
+ field(f);
+ return this;
+ }
+
public List<String> getFields() {
return fields;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java b/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java
index 297e8846907..47f06163454 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java
@@ -28,9 +28,9 @@
public class OTraverseContext implements OCommandContext {
private OCommandContext nestedStack;
- private Set<ORID> allTraversed = new HashSet<ORID>();
- private List<OTraverseAbstractProcess<?>> stack = new ArrayList<OTraverseAbstractProcess<?>>();
- private int depth = -1;
+ private Set<ORID> history = new HashSet<ORID>();
+ private List<OTraverseAbstractProcess<?>> stack = new ArrayList<OTraverseAbstractProcess<?>>();
+ private int depth = -1;
public void push(final OTraverseAbstractProcess<?> iProcess) {
stack.add(iProcess);
@@ -55,11 +55,11 @@ public void reset() {
}
public boolean isAlreadyTraversed(final OIdentifiable identity) {
- return allTraversed.contains(identity.getIdentity());
+ return history.contains(identity.getIdentity());
}
public void addTraversed(final OIdentifiable identity) {
- allTraversed.add(identity.getIdentity());
+ history.add(identity.getIdentity());
}
public int incrementDepth() {
@@ -77,6 +77,8 @@ else if ("path".equalsIgnoreCase(iName))
return getPath();
else if ("stack".equalsIgnoreCase(iName))
return stack;
+ else if ("history".equalsIgnoreCase(iName))
+ return history;
else if (nestedStack != null)
// DELEGATE
nestedStack.getVariable(iName);
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLHelper.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLHelper.java
index 11f34176254..e1668449d26 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLHelper.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLHelper.java
@@ -39,6 +39,7 @@
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemParameter;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemVariable;
+import com.orientechnologies.orient.core.sql.filter.OSQLPredicate;
import com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime;
/**
@@ -182,7 +183,7 @@ else if (t == OType.DATE || t == OType.DATETIME)
return null;
}
- public static Object parseValue(final OSQLFilter iSQLFilter, final OCommandToParse iCommand, final String iWord,
+ public static Object parseValue(final OSQLPredicate iSQLFilter, final OCommandToParse iCommand, final String iWord,
final OCommandContext iContext) {
if (iWord.charAt(0) == OStringSerializerHelper.PARAMETER_POSITIONAL
|| iWord.charAt(0) == OStringSerializerHelper.PARAMETER_NAMED) {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilter.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilter.java
index 4c15ece5ec2..7a23f87dcc7 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilter.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilter.java
@@ -17,27 +17,20 @@
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
-import java.util.Locale;
import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
import com.orientechnologies.common.parser.OStringParser;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
import com.orientechnologies.orient.core.command.OCommandPredicate;
-import com.orientechnologies.orient.core.command.OCommandToParse;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
-import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.exception.OQueryParsingException;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OClass;
-import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
@@ -46,11 +39,7 @@
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.OCommandSQLParsingException;
import com.orientechnologies.orient.core.sql.OCommandSQLResultset;
-import com.orientechnologies.orient.core.sql.OSQLEngine;
import com.orientechnologies.orient.core.sql.OSQLHelper;
-import com.orientechnologies.orient.core.sql.operator.OQueryOperator;
-import com.orientechnologies.orient.core.sql.operator.OQueryOperatorNot;
-import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
/**
* Parsed query. It's built once a query is parsed.
@@ -58,26 +47,19 @@
* @author Luca Garulli
*
*/
-public class OSQLFilter extends OCommandToParse implements OCommandPredicate {
- protected ODatabaseRecord database;
+public class OSQLFilter extends OSQLPredicate implements OCommandPredicate {
protected Iterable<? extends OIdentifiable> targetRecords;
protected Map<String, String> targetClusters;
protected Map<OClass, String> targetClasses;
protected String targetIndex;
- protected Set<OProperty> properties = new HashSet<OProperty>();
- protected OSQLFilterCondition rootCondition;
- protected List<String> recordTransformed;
- protected List<OSQLFilterItemParameter> parameterItems;
- protected int braces;
- private OCommandContext context;
public OSQLFilter(final String iText, final OCommandContext iContext) {
+ super();
context = iContext;
- try {
- database = ODatabaseRecordThreadLocal.INSTANCE.get();
- text = iText;
- textUpperCase = text.toUpperCase(Locale.ENGLISH);
+ text = iText;
+ textUpperCase = iText.toUpperCase();
+ try {
if (extractTargets()) {
// IF WHERE EXISTS EXTRACT CONDITIONS
@@ -85,8 +67,17 @@ public OSQLFilter(final String iText, final OCommandContext iContext) {
int newPos = OSQLHelper.nextWord(text, textUpperCase, currentPos, word, true);
if (newPos > -1) {
if (word.toString().equals(OCommandExecutorSQLAbstract.KEYWORD_WHERE)) {
- currentPos = newPos;
- rootCondition = (OSQLFilterCondition) extractConditions(null);
+ final int lastPos = newPos;
+ final String lastText = text;
+ final String lastTextUpperCase = textUpperCase;
+
+ text(text.substring(newPos));
+
+ if (currentPos > -1)
+ currentPos += lastPos;
+ text = lastText;
+ textUpperCase = lastTextUpperCase;
+
} else if (word.toString().equals(OCommandExecutorSQLAbstract.KEYWORD_LIMIT)
|| word.toString().equals(OCommandExecutorSQLSelect.KEYWORD_ORDER)
|| word.toString().equals(OCommandExecutorSQLSelect.KEYWORD_SKIP))
@@ -115,7 +106,7 @@ public boolean evaluate(final ORecord<?> iRecord, final OCommandContext iContext
@SuppressWarnings("unchecked")
private boolean extractTargets() {
- jumpWhiteSpaces();
+ currentPos = OStringParser.jumpWhiteSpaces(text, currentPos);
if (currentPos == -1)
throw new OQueryParsingException("No query target found", text, 0);
@@ -210,7 +201,7 @@ private boolean extractTargets() {
if (targetClasses == null)
targetClasses = new HashMap<OClass, String>();
- OClass cls = database.getMetadata().getSchema().getClass(subjectName);
+ final OClass cls = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSchema().getClass(subjectName);
if (cls == null)
throw new OCommandExecutionException("Class '" + subjectName + "' was not found in current database");
@@ -222,213 +213,6 @@ private boolean extractTargets() {
return currentPos > -1;
}
- private Object extractConditions(final OSQLFilterCondition iParentCondition) {
- final int oldPosition = currentPos;
- final String[] words = nextValue(true);
-
- if (words != null && words.length > 0 && (words[0].equalsIgnoreCase("SELECT") || words[0].equalsIgnoreCase("TRAVERSE"))) {
- // SUB QUERY
- final StringBuilder embedded = new StringBuilder();
- OStringSerializerHelper.getEmbedded(text, oldPosition - 1, -1, embedded);
- currentPos += embedded.length() + 1;
- return new OSQLSynchQuery<Object>(embedded.toString());
- }
-
- currentPos = oldPosition;
- final OSQLFilterCondition currentCondition = extractCondition();
-
- // CHECK IF THERE IS ANOTHER CONDITION ON RIGHT
- if (!jumpWhiteSpaces())
- // END OF TEXT
- return currentCondition;
-
- if (currentPos > -1 && text.charAt(currentPos) == ')')
- return currentCondition;
-
- final OQueryOperator nextOperator = extractConditionOperator();
- if (nextOperator == null)
- return currentCondition;
-
- if (nextOperator.precedence > currentCondition.getOperator().precedence) {
- // SWAP ITEMS
- final OSQLFilterCondition subCondition = new OSQLFilterCondition(currentCondition.right, nextOperator);
- currentCondition.right = subCondition;
- subCondition.right = extractConditions(subCondition);
- return currentCondition;
- } else {
- final OSQLFilterCondition parentCondition = new OSQLFilterCondition(currentCondition, nextOperator);
- parentCondition.right = extractConditions(parentCondition);
- return parentCondition;
- }
- }
-
- protected OSQLFilterCondition extractCondition() {
- if (!jumpWhiteSpaces())
- // END OF TEXT
- return null;
-
- // EXTRACT ITEMS
- Object left = extractConditionItem(true, 1);
-
- if (checkForEnd(left.toString()))
- return null;
-
- final OQueryOperator oper;
- final Object right;
-
- if (left instanceof OQueryOperator && ((OQueryOperator) left).isUnary()) {
- oper = (OQueryOperator) left;
- left = extractConditionItem(false, 1);
- right = null;
- } else {
- oper = extractConditionOperator();
- right = oper != null ? extractConditionItem(false, oper.expectedRightWords) : null;
- }
-
- // CREATE THE CONDITION OBJECT
- return new OSQLFilterCondition(left, oper, right);
- }
-
- protected boolean checkForEnd(final String iWord) {
- if (iWord != null
- && (iWord.equals(OCommandExecutorSQLSelect.KEYWORD_ORDER) || iWord.equals(OCommandExecutorSQLSelect.KEYWORD_LIMIT) || iWord
- .equals(OCommandExecutorSQLSelect.KEYWORD_SKIP))) {
- currentPos -= iWord.length();
- return true;
- }
- return false;
- }
-
- private OQueryOperator extractConditionOperator() {
- if (!jumpWhiteSpaces())
- // END OF PARSING: JUST RETURN
- return null;
-
- if (text.charAt(currentPos) == ')')
- // FOUND ')': JUST RETURN
- return null;
-
- String word;
- word = nextWord(true, " 0123456789'\"");
-
- if (checkForEnd(word))
- return null;
-
- for (OQueryOperator op : OSQLEngine.getInstance().getRecordOperators()) {
- if (word.startsWith(op.keyword)) {
- final List<String> params = new ArrayList<String>();
- // CHECK FOR PARAMETERS
- if (word.length() > op.keyword.length() && word.charAt(op.keyword.length()) == OStringSerializerHelper.EMBEDDED_BEGIN) {
- int paramBeginPos = currentPos - (word.length() - op.keyword.length());
- currentPos = OStringSerializerHelper.getParameters(text, paramBeginPos, -1, params);
- } else if (!word.equals(op.keyword))
- throw new OQueryParsingException("Malformed usage of operator '" + op.toString() + "'. Parsed operator is: " + word);
-
- try {
- return op.configure(params);
- } catch (Exception e) {
- throw new OQueryParsingException("Syntax error using the operator '" + op.toString() + "'. Syntax is: " + op.getSyntax());
- }
- }
- }
-
- throw new OQueryParsingException("Unknown operator " + word, text, currentPos);
- }
-
- private Object extractConditionItem(final boolean iAllowOperator, final int iExpectedWords) {
- final Object[] result = new Object[iExpectedWords];
-
- for (int i = 0; i < iExpectedWords; ++i) {
- final String[] words = nextValue(true);
- if (words == null)
- break;
-
- if (words[0].length() > 0 && words[0].charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) {
- braces++;
-
- // SUB-CONDITION
- currentPos = currentPos - words[0].length() + 1;
-
- final Object subCondition = extractConditions(null);
-
- if (!jumpWhiteSpaces() || text.charAt(currentPos) == ')')
- braces--;
-
- if (currentPos > -1)
- currentPos++;
-
- result[i] = subCondition;
- } else if (words[0].charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN) {
- // COLLECTION OF ELEMENTS
- currentPos = currentPos - words[0].length();
-
- final List<String> stringItems = new ArrayList<String>();
- currentPos = OStringSerializerHelper.getCollection(text, currentPos, stringItems);
-
- if (stringItems.get(0).charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN) {
-
- final List<List<Object>> coll = new ArrayList<List<Object>>();
- for (String stringItem : stringItems) {
- final List<String> stringSubItems = new ArrayList<String>();
- OStringSerializerHelper.getCollection(stringItem, 0, stringSubItems);
-
- coll.add(convertCollectionItems(stringSubItems));
- }
-
- result[i] = coll;
-
- } else {
- result[i] = convertCollectionItems(stringItems);
- }
-
- currentPos++;
-
- } else if (words[0].startsWith(OSQLFilterItemFieldAll.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) {
-
- result[i] = new OSQLFilterItemFieldAll(this, words[1]);
-
- } else if (words[0].startsWith(OSQLFilterItemFieldAny.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) {
-
- result[i] = new OSQLFilterItemFieldAny(this, words[1]);
-
- } else {
-
- if (words[0].equals("NOT")) {
- if (iAllowOperator)
- return new OQueryOperatorNot();
- else {
- // GET THE NEXT VALUE
- final String[] nextWord = nextValue(true);
- if (nextWord != null && nextWord.length == 2) {
- words[1] = words[1] + " " + nextWord[1];
-
- if (words[1].endsWith(")"))
- words[1] = words[1].substring(0, words[1].length() - 1);
- }
- }
- }
-
- if (words[1].endsWith(")")) {
- final int openParenthesis = words[1].indexOf('(');
- if (openParenthesis == -1)
- words[1] = words[1].substring(0, words[1].length() - 1);
- }
-
- result[i] = OSQLHelper.parseValue(this, this, words[1], context);
- }
- }
-
- return iExpectedWords == 1 ? result[0] : result;
- }
-
- private List<Object> convertCollectionItems(List<String> stringItems) {
- List<Object> coll = new ArrayList<Object>();
- for (String s : stringItems) {
- coll.add(OSQLHelper.parseValue(this, this, s, context));
- }
- return coll;
- }
-
public Map<String, String> getTargetClusters() {
return targetClusters;
}
@@ -449,85 +233,6 @@ public OSQLFilterCondition getRootCondition() {
return rootCondition;
}
- private String[] nextValue(final boolean iAdvanceWhenNotFound) {
- if (!jumpWhiteSpaces())
- return null;
-
- int begin = currentPos;
- char c;
- char stringBeginCharacter = ' ';
- int openBraces = 0;
- int openBraket = 0;
- boolean escaped = false;
- boolean escapingOn = false;
-
- for (; currentPos < text.length(); ++currentPos) {
- c = text.charAt(currentPos);
-
- if (stringBeginCharacter == ' ' && (c == '"' || c == '\'')) {
- // QUOTED STRING: GET UNTIL THE END OF QUOTING
- stringBeginCharacter = c;
- } else if (stringBeginCharacter != ' ') {
- // INSIDE TEXT
- if (c == '\\') {
- escapingOn = true;
- escaped = true;
- } else {
- if (c == stringBeginCharacter && !escapingOn) {
- stringBeginCharacter = ' ';
-
- if (openBraket == 0 && openBraces == 0) {
- if (iAdvanceWhenNotFound)
- currentPos++;
- break;
- }
- }
-
- if (escapingOn)
- escapingOn = false;
- }
- } else if (c == '#' && currentPos == begin) {
- // BEGIN OF RID
- } else if (c == '(') {
- openBraces++;
- } else if (c == ')' && openBraces > 0) {
- openBraces--;
- } else if (c == OStringSerializerHelper.COLLECTION_BEGIN) {
- openBraket++;
- } else if (c == OStringSerializerHelper.COLLECTION_END) {
- openBraket--;
- if (openBraket == 0 && openBraces == 0) {
- // currentPos++;
- // break;
- }
- } else if (c == ' ' && openBraces == 0) {
- break;
- } else if (!Character.isLetter(c) && !Character.isDigit(c) && c != '.' && c != '$' && c != ':' && c != '-' && c != '_'
- && c != '+' && c != '@' && openBraces == 0 && openBraket == 0) {
- if (iAdvanceWhenNotFound)
- currentPos++;
- break;
- }
- }
-
- if (escaped)
- return new String[] { OStringSerializerHelper.decode(textUpperCase.substring(begin, currentPos)),
- OStringSerializerHelper.decode(text.substring(begin, currentPos)) };
- else
- return new String[] { textUpperCase.substring(begin, currentPos), text.substring(begin, currentPos) };
- }
-
- private String nextWord(final boolean iForceUpperCase, final String iSeparators) {
- StringBuilder word = new StringBuilder();
- currentPos = OSQLHelper.nextWord(text, textUpperCase, currentPos, word, iForceUpperCase, iSeparators);
- return word.toString();
- }
-
- private boolean jumpWhiteSpaces() {
- currentPos = OStringParser.jumpWhiteSpaces(text, currentPos);
- return currentPos > -1;
- }
-
@Override
public String toString() {
if (rootCondition != null)
@@ -535,52 +240,4 @@ public String toString() {
return "Unparsed: " + text;
}
- /**
- * Binds parameters.
- *
- * @param iArgs
- */
- public void bindParameters(final Map<Object, Object> iArgs) {
- if (parameterItems == null || iArgs == null || iArgs.size() == 0)
- return;
-
- for (Entry<Object, Object> entry : iArgs.entrySet()) {
- if (entry.getKey() instanceof Integer)
- parameterItems.get(((Integer) entry.getKey())).setValue(entry.setValue(entry.getValue()));
- else {
- String paramName = entry.getKey().toString();
- for (OSQLFilterItemParameter value : parameterItems) {
- if (value.getName().equalsIgnoreCase(paramName)) {
- value.setValue(entry.getValue());
- break;
- }
- }
- }
- }
- }
-
- public OSQLFilterItemParameter addParameter(final String iName) {
- final String name;
- if (iName.charAt(0) == OStringSerializerHelper.PARAMETER_NAMED) {
- name = iName.substring(1);
-
- // CHECK THE PARAMETER NAME IS CORRECT
- if (!OStringSerializerHelper.isAlphanumeric(name)) {
- throw new OQueryParsingException("Parameter name '" + name + "' is invalid, only alphanumeric characters are allowed");
- }
- } else
- name = iName;
-
- final OSQLFilterItemParameter param = new OSQLFilterItemParameter(name);
-
- if (parameterItems == null)
- parameterItems = new ArrayList<OSQLFilterItemParameter>();
-
- parameterItems.add(param);
- return param;
- }
-
- public void setRootCondition(final OSQLFilterCondition iCondition) {
- rootCondition = iCondition;
- }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java
index 46262c81b26..2c8d701397e 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java
@@ -47,271 +47,271 @@
*
*/
public class OSQLFilterCondition {
- private static final String NULL_VALUE = "null";
- protected Object left;
- protected OQueryOperator operator;
- protected Object right;
-
- public OSQLFilterCondition(final Object iLeft, final OQueryOperator iOperator) {
- this.left = iLeft;
- this.operator = iOperator;
- }
-
- public OSQLFilterCondition(final Object iLeft, final OQueryOperator iOperator, final Object iRight) {
- this.left = iLeft;
- this.operator = iOperator;
- this.right = iRight;
- }
-
- public Object evaluate(final OIdentifiable o, final OCommandContext iContext) {
- // EXECUTE SUB QUERIES ONCE
- if (left instanceof OSQLQuery<?>)
- left = ((OSQLQuery<?>) left).setContext(iContext).execute();
-
- if (right instanceof OSQLQuery<?>)
- right = ((OSQLQuery<?>) right).setContext(iContext).execute();
-
- Object l = evaluate(o, left, iContext);
- Object r = evaluate(o, right, iContext);
-
- final Object[] convertedValues = checkForConversion(o, l, r);
- if (convertedValues != null) {
- l = convertedValues[0];
- r = convertedValues[1];
- }
-
- if (operator == null) {
- if (l == null)
- // THE LEFT RETURNED NULL
- return Boolean.FALSE;
-
- // UNITARY OPERATOR: JUST RETURN LEFT RESULT
- return l;
- }
-
- return operator.evaluateRecord(o, this, l, r, iContext);
- }
-
- public ORID getBeginRidRange() {
- if (operator == null)
- if (left instanceof OSQLFilterCondition)
- return ((OSQLFilterCondition) left).getBeginRidRange();
- else
- return null;
-
- return operator.getBeginRidRange(left, right);
- }
-
- public ORID getEndRidRange() {
- if (operator == null)
- if (left instanceof OSQLFilterCondition)
- return ((OSQLFilterCondition) left).getEndRidRange();
- else
- return null;
-
- return operator.getEndRidRange(left, right);
- }
-
- private Object[] checkForConversion(final OIdentifiable o, final Object l, final Object r) {
- Object[] result = null;
-
- // DEFINED OPERATOR
- if ((r instanceof String && r.equals(OSQLHelper.DEFINED)) || (l instanceof String && l.equals(OSQLHelper.DEFINED))) {
- result = new Object[] { ((OSQLFilterItemAbstract) this.left).getRoot(), r };
- }
-
- // NOT_NULL OPERATOR
- else if ((r instanceof String && r.equals(OSQLHelper.NOT_NULL)) || (l instanceof String && l.equals(OSQLHelper.NOT_NULL))) {
- result = null;
- }
-
- else if (l != null && r != null && !l.getClass().isAssignableFrom(r.getClass()) && !r.getClass().isAssignableFrom(l.getClass()))
- // INTEGERS
- if (r instanceof Integer && !(l instanceof Number)) {
- if (l instanceof String && ((String) l).indexOf('.') > -1)
- result = new Object[] { new Float((String) l).intValue(), r };
- else if (l instanceof Date)
- result = new Object[] { ((Date) l).getTime(), r };
- else if (!(l instanceof OQueryRuntimeValueMulti) && !(l instanceof Collection<?>) && !l.getClass().isArray()
- && !(l instanceof Map))
- result = new Object[] { getInteger(l), r };
- } else if (l instanceof Integer && !(r instanceof Number)) {
- if (r instanceof String && ((String) r).indexOf('.') > -1)
- result = new Object[] { l, new Float((String) r).intValue() };
- else if (r instanceof Date)
- result = new Object[] { l, ((Date) r).getTime() };
- else if (!(r instanceof OQueryRuntimeValueMulti) && !(r instanceof Collection<?>) && !r.getClass().isArray()
- && !(r instanceof Map))
- result = new Object[] { l, getInteger(r) };
- }
-
- // FLOATS
- else if (r instanceof Float && !(l instanceof Float))
- result = new Object[] { getFloat(l), r };
- else if (l instanceof Float && !(r instanceof Float))
- result = new Object[] { l, getFloat(r) };
-
- // DATES
- else if (r instanceof Date && !(l instanceof Collection || l instanceof Date)) {
- result = new Object[] { getDate(l), r };
- } else if (l instanceof Date && !(r instanceof Collection || r instanceof Date)) {
- result = new Object[] { l, getDate(r) };
- }
-
- // RIDS
- else if (r instanceof ORID && l instanceof String && !l.equals(OSQLHelper.NOT_NULL)) {
- result = new Object[] { new ORecordId((String) l), r };
- } else if (l instanceof ORID && r instanceof String && !r.equals(OSQLHelper.NOT_NULL)) {
- result = new Object[] { l, new ORecordId((String) r) };
- }
-
- return result;
- }
-
- protected Integer getInteger(Object iValue) {
- if (iValue == null)
- return null;
-
- final String stringValue = iValue.toString();
-
- if (NULL_VALUE.equals(stringValue))
- return null;
- if (OSQLHelper.DEFINED.equals(stringValue))
- return null;
-
- if (OStringSerializerHelper.contains(stringValue, '.') || OStringSerializerHelper.contains(stringValue, ','))
- return (int) Float.parseFloat(stringValue);
- else
- return stringValue.length() > 0 ? new Integer(stringValue) : new Integer(0);
- }
-
- protected Float getFloat(final Object iValue) {
- if (iValue == null)
- return null;
-
- final String stringValue = iValue.toString();
-
- if (NULL_VALUE.equals(stringValue))
- return null;
-
- return stringValue.length() > 0 ? new Float(stringValue) : new Float(0);
- }
-
- protected Date getDate(final Object iValue) {
- if (iValue == null)
- return null;
-
- if (iValue instanceof Long)
- return new Date(((Long) iValue).longValue());
-
- String stringValue = iValue.toString();
-
- if (NULL_VALUE.equals(stringValue))
- return null;
-
- if (stringValue.length() <= 0)
- return null;
-
- if (Pattern.matches("^\\d+$", stringValue)) {
- return new Date(Long.valueOf(stringValue).longValue());
- }
-
- final OStorageConfiguration config = ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getConfiguration();
-
- SimpleDateFormat formatter = config.getDateFormatInstance();
-
- if (stringValue.length() > config.dateFormat.length()) {
- // ASSUMES YOU'RE USING THE DATE-TIME FORMATTE
- formatter = config.getDateTimeFormatInstance();
- }
-
- try {
- return formatter.parse(stringValue);
- } catch (ParseException pe) {
- throw new OQueryParsingException("Error on conversion of date '" + stringValue + "' using the format: "
- + formatter.toPattern());
- }
- }
-
- protected Object evaluate(OIdentifiable o, final Object iValue, final OCommandContext iContext) {
- if (o.getRecord().getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) {
- try {
- o = o.getRecord().load();
- } catch (ORecordNotFoundException e) {
- return null;
- }
- }
-
- if (iValue instanceof OSQLFilterItem)
- return ((OSQLFilterItem) iValue).getValue(o, iContext);
-
- if (iValue instanceof OSQLFilterCondition)
- // NESTED CONDITION: EVALUATE IT RECURSIVELY
- return ((OSQLFilterCondition) iValue).evaluate(o, iContext);
-
- if (iValue instanceof OSQLFunctionRuntime) {
- // STATELESS FUNCTION: EXECUTE IT
- final OSQLFunctionRuntime f = (OSQLFunctionRuntime) iValue;
- return f.execute(o, null);
- }
-
- final Iterable<?> multiValue = OMultiValue.getMultiValueIterable(iValue);
-
- if (multiValue != null) {
- // MULTI VALUE: RETURN A COPY
- final ArrayList<Object> result = new ArrayList<Object>(OMultiValue.getSize(iValue));
-
- for (final Object value : multiValue) {
- if (value instanceof OSQLFilterItem)
- result.add(((OSQLFilterItem) value).getValue(o, null));
- else
- result.add(value);
- }
- return result;
- }
-
- // SIMPLE VALUE: JUST RETURN IT
- return iValue;
- }
-
- @Override
- public String toString() {
- StringBuilder buffer = new StringBuilder();
-
- buffer.append('(');
- buffer.append(left);
- if (operator != null) {
- buffer.append(' ');
- buffer.append(operator);
- buffer.append(' ');
- if (right instanceof String)
- buffer.append('\'');
- buffer.append(right);
- if (right instanceof String)
- buffer.append('\'');
- buffer.append(')');
- }
-
- return buffer.toString();
- }
-
- public Object getLeft() {
- return left;
- }
-
- public Object getRight() {
- return right;
- }
-
- public OQueryOperator getOperator() {
- return operator;
- }
-
- public void setLeft(final Object iValue) {
- left = iValue;
- }
-
- public void setRight(final Object iValue) {
- right = iValue;
- }
+ private static final String NULL_VALUE = "null";
+ protected Object left;
+ protected OQueryOperator operator;
+ protected Object right;
+
+ public OSQLFilterCondition(final Object iLeft, final OQueryOperator iOperator) {
+ this.left = iLeft;
+ this.operator = iOperator;
+ }
+
+ public OSQLFilterCondition(final Object iLeft, final OQueryOperator iOperator, final Object iRight) {
+ this.left = iLeft;
+ this.operator = iOperator;
+ this.right = iRight;
+ }
+
+ public Object evaluate(final OIdentifiable o, final OCommandContext iContext) {
+ // EXECUTE SUB QUERIES ONCE
+ if (left instanceof OSQLQuery<?>)
+ left = ((OSQLQuery<?>) left).setContext(iContext).execute();
+
+ if (right instanceof OSQLQuery<?>)
+ right = ((OSQLQuery<?>) right).setContext(iContext).execute();
+
+ Object l = evaluate(o, left, iContext);
+ Object r = evaluate(o, right, iContext);
+
+ final Object[] convertedValues = checkForConversion(o, l, r);
+ if (convertedValues != null) {
+ l = convertedValues[0];
+ r = convertedValues[1];
+ }
+
+ if (operator == null) {
+ if (l == null)
+ // THE LEFT RETURNED NULL
+ return Boolean.FALSE;
+
+ // UNITARY OPERATOR: JUST RETURN LEFT RESULT
+ return l;
+ }
+
+ return operator.evaluateRecord(o, this, l, r, iContext);
+ }
+
+ public ORID getBeginRidRange() {
+ if (operator == null)
+ if (left instanceof OSQLFilterCondition)
+ return ((OSQLFilterCondition) left).getBeginRidRange();
+ else
+ return null;
+
+ return operator.getBeginRidRange(left, right);
+ }
+
+ public ORID getEndRidRange() {
+ if (operator == null)
+ if (left instanceof OSQLFilterCondition)
+ return ((OSQLFilterCondition) left).getEndRidRange();
+ else
+ return null;
+
+ return operator.getEndRidRange(left, right);
+ }
+
+ private Object[] checkForConversion(final OIdentifiable o, final Object l, final Object r) {
+ Object[] result = null;
+
+ // DEFINED OPERATOR
+ if ((r instanceof String && r.equals(OSQLHelper.DEFINED)) || (l instanceof String && l.equals(OSQLHelper.DEFINED))) {
+ result = new Object[] { ((OSQLFilterItemAbstract) this.left).getRoot(), r };
+ }
+
+ // NOT_NULL OPERATOR
+ else if ((r instanceof String && r.equals(OSQLHelper.NOT_NULL)) || (l instanceof String && l.equals(OSQLHelper.NOT_NULL))) {
+ result = null;
+ }
+
+ else if (l != null && r != null && !l.getClass().isAssignableFrom(r.getClass()) && !r.getClass().isAssignableFrom(l.getClass()))
+ // INTEGERS
+ if (r instanceof Integer && !(l instanceof Number)) {
+ if (l instanceof String && ((String) l).indexOf('.') > -1)
+ result = new Object[] { new Float((String) l).intValue(), r };
+ else if (l instanceof Date)
+ result = new Object[] { ((Date) l).getTime(), r };
+ else if (!(l instanceof OQueryRuntimeValueMulti) && !(l instanceof Collection<?>) && !l.getClass().isArray()
+ && !(l instanceof Map))
+ result = new Object[] { getInteger(l), r };
+ } else if (l instanceof Integer && !(r instanceof Number)) {
+ if (r instanceof String && ((String) r).indexOf('.') > -1)
+ result = new Object[] { l, new Float((String) r).intValue() };
+ else if (r instanceof Date)
+ result = new Object[] { l, ((Date) r).getTime() };
+ else if (!(r instanceof OQueryRuntimeValueMulti) && !(r instanceof Collection<?>) && !r.getClass().isArray()
+ && !(r instanceof Map))
+ result = new Object[] { l, getInteger(r) };
+ }
+
+ // FLOATS
+ else if (r instanceof Float && !(l instanceof Float))
+ result = new Object[] { getFloat(l), r };
+ else if (l instanceof Float && !(r instanceof Float))
+ result = new Object[] { l, getFloat(r) };
+
+ // DATES
+ else if (r instanceof Date && !(l instanceof Collection || l instanceof Date)) {
+ result = new Object[] { getDate(l), r };
+ } else if (l instanceof Date && !(r instanceof Collection || r instanceof Date)) {
+ result = new Object[] { l, getDate(r) };
+ }
+
+ // RIDS
+ else if (r instanceof ORID && l instanceof String && !l.equals(OSQLHelper.NOT_NULL)) {
+ result = new Object[] { new ORecordId((String) l), r };
+ } else if (l instanceof ORID && r instanceof String && !r.equals(OSQLHelper.NOT_NULL)) {
+ result = new Object[] { l, new ORecordId((String) r) };
+ }
+
+ return result;
+ }
+
+ protected Integer getInteger(Object iValue) {
+ if (iValue == null)
+ return null;
+
+ final String stringValue = iValue.toString();
+
+ if (NULL_VALUE.equals(stringValue))
+ return null;
+ if (OSQLHelper.DEFINED.equals(stringValue))
+ return null;
+
+ if (OStringSerializerHelper.contains(stringValue, '.') || OStringSerializerHelper.contains(stringValue, ','))
+ return (int) Float.parseFloat(stringValue);
+ else
+ return stringValue.length() > 0 ? new Integer(stringValue) : new Integer(0);
+ }
+
+ protected Float getFloat(final Object iValue) {
+ if (iValue == null)
+ return null;
+
+ final String stringValue = iValue.toString();
+
+ if (NULL_VALUE.equals(stringValue))
+ return null;
+
+ return stringValue.length() > 0 ? new Float(stringValue) : new Float(0);
+ }
+
+ protected Date getDate(final Object iValue) {
+ if (iValue == null)
+ return null;
+
+ if (iValue instanceof Long)
+ return new Date(((Long) iValue).longValue());
+
+ String stringValue = iValue.toString();
+
+ if (NULL_VALUE.equals(stringValue))
+ return null;
+
+ if (stringValue.length() <= 0)
+ return null;
+
+ if (Pattern.matches("^\\d+$", stringValue)) {
+ return new Date(Long.valueOf(stringValue).longValue());
+ }
+
+ final OStorageConfiguration config = ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getConfiguration();
+
+ SimpleDateFormat formatter = config.getDateFormatInstance();
+
+ if (stringValue.length() > config.dateFormat.length()) {
+ // ASSUMES YOU'RE USING THE DATE-TIME FORMATTE
+ formatter = config.getDateTimeFormatInstance();
+ }
+
+ try {
+ return formatter.parse(stringValue);
+ } catch (ParseException pe) {
+ throw new OQueryParsingException("Error on conversion of date '" + stringValue + "' using the format: "
+ + formatter.toPattern());
+ }
+ }
+
+ protected Object evaluate(OIdentifiable o, final Object iValue, final OCommandContext iContext) {
+ if (o.getRecord().getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) {
+ try {
+ o = o.getRecord().load();
+ } catch (ORecordNotFoundException e) {
+ return null;
+ }
+ }
+
+ if (iValue instanceof OSQLFilterItem)
+ return ((OSQLFilterItem) iValue).getValue(o, iContext);
+
+ if (iValue instanceof OSQLFilterCondition)
+ // NESTED CONDITION: EVALUATE IT RECURSIVELY
+ return ((OSQLFilterCondition) iValue).evaluate(o, iContext);
+
+ if (iValue instanceof OSQLFunctionRuntime) {
+ // STATELESS FUNCTION: EXECUTE IT
+ final OSQLFunctionRuntime f = (OSQLFunctionRuntime) iValue;
+ return f.execute(o, null);
+ }
+
+ final Iterable<?> multiValue = OMultiValue.getMultiValueIterable(iValue);
+
+ if (multiValue != null) {
+ // MULTI VALUE: RETURN A COPY
+ final ArrayList<Object> result = new ArrayList<Object>(OMultiValue.getSize(iValue));
+
+ for (final Object value : multiValue) {
+ if (value instanceof OSQLFilterItem)
+ result.add(((OSQLFilterItem) value).getValue(o, null));
+ else
+ result.add(value);
+ }
+ return result;
+ }
+
+ // SIMPLE VALUE: JUST RETURN IT
+ return iValue;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+
+ buffer.append('(');
+ buffer.append(left);
+ if (operator != null) {
+ buffer.append(' ');
+ buffer.append(operator);
+ buffer.append(' ');
+ if (right instanceof String)
+ buffer.append('\'');
+ buffer.append(right);
+ if (right instanceof String)
+ buffer.append('\'');
+ buffer.append(')');
+ }
+
+ return buffer.toString();
+ }
+
+ public Object getLeft() {
+ return left;
+ }
+
+ public Object getRight() {
+ return right;
+ }
+
+ public OQueryOperator getOperator() {
+ return operator;
+ }
+
+ public void setLeft(final Object iValue) {
+ left = iValue;
+ }
+
+ public void setRight(final Object iValue) {
+ right = iValue;
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAll.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAll.java
index 31de0848b1a..67bff01bb6d 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAll.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAll.java
@@ -28,7 +28,7 @@ public class OSQLFilterItemFieldAll extends OSQLFilterItemFieldMultiAbstract {
public static final String NAME = "ALL";
public static final String FULL_NAME = "ALL()";
- public OSQLFilterItemFieldAll(final OSQLFilter iQueryCompiled, final String iName) {
+ public OSQLFilterItemFieldAll(final OSQLPredicate iQueryCompiled, final String iName) {
super(iQueryCompiled, iName, OStringSerializerHelper.getParameters(iName));
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAny.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAny.java
index fad3f6aac1c..145347f9e86 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAny.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAny.java
@@ -25,19 +25,19 @@
*
*/
public class OSQLFilterItemFieldAny extends OSQLFilterItemFieldMultiAbstract {
- public static final String NAME = "ANY";
- public static final String FULL_NAME = "ANY()";
+ public static final String NAME = "ANY";
+ public static final String FULL_NAME = "ANY()";
- public OSQLFilterItemFieldAny(final OSQLFilter iQueryCompiled, final String iName) {
- super(iQueryCompiled, iName, OStringSerializerHelper.getParameters(iName));
- }
+ public OSQLFilterItemFieldAny(final OSQLPredicate iQueryCompiled, final String iName) {
+ super(iQueryCompiled, iName, OStringSerializerHelper.getParameters(iName));
+ }
- @Override
- public String getRoot() {
- return FULL_NAME;
- }
+ @Override
+ public String getRoot() {
+ return FULL_NAME;
+ }
- @Override
- protected void setRoot(final OCommandToParse iQueryToParse, final String iRoot) {
- }
+ @Override
+ protected void setRoot(final OCommandToParse iQueryToParse, final String iRoot) {
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldMultiAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldMultiAbstract.java
index 6181f1a7180..9002a582da5 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldMultiAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldMultiAbstract.java
@@ -30,25 +30,25 @@
*
*/
public abstract class OSQLFilterItemFieldMultiAbstract extends OSQLFilterItemAbstract {
- private List<String> names;
+ private List<String> names;
- public OSQLFilterItemFieldMultiAbstract(final OSQLFilter iQueryCompiled, final String iName, final List<String> iNames) {
- super(iQueryCompiled, iName);
- names = iNames;
- }
+ public OSQLFilterItemFieldMultiAbstract(final OSQLPredicate iQueryCompiled, final String iName, final List<String> iNames) {
+ super(iQueryCompiled, iName);
+ names = iNames;
+ }
- public Object getValue(final OIdentifiable iRecord, OCommandContext iContetx) {
- if (names.size() == 1)
- return transformValue(iRecord, ODocumentHelper.getIdentifiableValue(iRecord, names.get(0)));
+ public Object getValue(final OIdentifiable iRecord, OCommandContext iContetx) {
+ if (names.size() == 1)
+ return transformValue(iRecord, ODocumentHelper.getIdentifiableValue(iRecord, names.get(0)));
- final Object[] values = ((ODocument) iRecord).fieldValues();
+ final Object[] values = ((ODocument) iRecord).fieldValues();
- if (hasChainOperators()) {
- // TRANSFORM ALL THE VALUES
- for (int i = 0; i < values.length; ++i)
- values[i] = transformValue(iRecord, values[i]);
- }
+ if (hasChainOperators()) {
+ // TRANSFORM ALL THE VALUES
+ for (int i = 0; i < values.length; ++i)
+ values[i] = transformValue(iRecord, values[i]);
+ }
- return new OQueryRuntimeValueMulti(this, values);
- }
+ return new OQueryRuntimeValueMulti(this, values);
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLPredicate.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLPredicate.java
new file mode 100644
index 00000000000..54eca8c0392
--- /dev/null
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLPredicate.java
@@ -0,0 +1,435 @@
+/*
+ * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.orientechnologies.orient.core.sql.filter;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import com.orientechnologies.common.parser.OStringParser;
+import com.orientechnologies.orient.core.command.OCommandContext;
+import com.orientechnologies.orient.core.command.OCommandPredicate;
+import com.orientechnologies.orient.core.command.OCommandToParse;
+import com.orientechnologies.orient.core.exception.OQueryParsingException;
+import com.orientechnologies.orient.core.metadata.schema.OProperty;
+import com.orientechnologies.orient.core.record.ORecord;
+import com.orientechnologies.orient.core.record.ORecordSchemaAware;
+import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
+import com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect;
+import com.orientechnologies.orient.core.sql.OSQLEngine;
+import com.orientechnologies.orient.core.sql.OSQLHelper;
+import com.orientechnologies.orient.core.sql.operator.OQueryOperator;
+import com.orientechnologies.orient.core.sql.operator.OQueryOperatorNot;
+import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
+
+/**
+ * Parses text in SQL format and build a tree of conditions.
+ *
+ * @author Luca Garulli
+ *
+ */
+public class OSQLPredicate extends OCommandToParse implements OCommandPredicate {
+ protected Set<OProperty> properties = new HashSet<OProperty>();
+ protected OSQLFilterCondition rootCondition;
+ protected List<String> recordTransformed;
+ protected List<OSQLFilterItemParameter> parameterItems;
+ protected int braces;
+ protected OCommandContext context;
+
+ public OSQLPredicate() {
+ }
+
+ public OSQLPredicate(final String iText) {
+ text(iText);
+ }
+
+ public OSQLPredicate text(final String iText) {
+ try {
+ text = iText;
+ textUpperCase = text.toUpperCase(Locale.ENGLISH);
+ currentPos = 0;
+ jumpWhiteSpaces();
+
+ rootCondition = (OSQLFilterCondition) extractConditions(null);
+ } catch (OQueryParsingException e) {
+ if (e.getText() == null)
+ // QUERY EXCEPTION BUT WITHOUT TEXT: NEST IT
+ throw new OQueryParsingException("Error on parsing query", text, currentPos, e);
+
+ throw e;
+ } catch (Throwable t) {
+ throw new OQueryParsingException("Error on parsing query", text, currentPos, t);
+ }
+ return this;
+ }
+
+ public boolean evaluate(final ORecord<?> iRecord, final OCommandContext iContext) {
+ if (rootCondition == null)
+ return true;
+
+ return (Boolean) rootCondition.evaluate((ORecordSchemaAware<?>) iRecord, iContext);
+ }
+
+ private Object extractConditions(final OSQLFilterCondition iParentCondition) {
+ final int oldPosition = currentPos;
+ final String[] words = nextValue(true);
+
+ if (words != null && words.length > 0 && (words[0].equalsIgnoreCase("SELECT") || words[0].equalsIgnoreCase("TRAVERSE"))) {
+ // SUB QUERY
+ final StringBuilder embedded = new StringBuilder();
+ OStringSerializerHelper.getEmbedded(text, oldPosition - 1, -1, embedded);
+ currentPos += embedded.length() + 1;
+ return new OSQLSynchQuery<Object>(embedded.toString());
+ }
+
+ currentPos = oldPosition;
+ final OSQLFilterCondition currentCondition = extractCondition();
+
+ // CHECK IF THERE IS ANOTHER CONDITION ON RIGHT
+ if (!jumpWhiteSpaces())
+ // END OF TEXT
+ return currentCondition;
+
+ if (currentPos > -1 && text.charAt(currentPos) == ')')
+ return currentCondition;
+
+ final OQueryOperator nextOperator = extractConditionOperator();
+ if (nextOperator == null)
+ return currentCondition;
+
+ if (nextOperator.precedence > currentCondition.getOperator().precedence) {
+ // SWAP ITEMS
+ final OSQLFilterCondition subCondition = new OSQLFilterCondition(currentCondition.right, nextOperator);
+ currentCondition.right = subCondition;
+ subCondition.right = extractConditions(subCondition);
+ return currentCondition;
+ } else {
+ final OSQLFilterCondition parentCondition = new OSQLFilterCondition(currentCondition, nextOperator);
+ parentCondition.right = extractConditions(parentCondition);
+ return parentCondition;
+ }
+ }
+
+ protected OSQLFilterCondition extractCondition() {
+ if (!jumpWhiteSpaces())
+ // END OF TEXT
+ return null;
+
+ // EXTRACT ITEMS
+ Object left = extractConditionItem(true, 1);
+
+ if (checkForEnd(left.toString()))
+ return null;
+
+ final OQueryOperator oper;
+ final Object right;
+
+ if (left instanceof OQueryOperator && ((OQueryOperator) left).isUnary()) {
+ oper = (OQueryOperator) left;
+ left = extractConditionItem(false, 1);
+ right = null;
+ } else {
+ oper = extractConditionOperator();
+ right = oper != null ? extractConditionItem(false, oper.expectedRightWords) : null;
+ }
+
+ // CREATE THE CONDITION OBJECT
+ return new OSQLFilterCondition(left, oper, right);
+ }
+
+ protected boolean checkForEnd(final String iWord) {
+ if (iWord != null
+ && (iWord.equals(OCommandExecutorSQLSelect.KEYWORD_ORDER) || iWord.equals(OCommandExecutorSQLSelect.KEYWORD_LIMIT) || iWord
+ .equals(OCommandExecutorSQLSelect.KEYWORD_SKIP))) {
+ currentPos -= iWord.length();
+ return true;
+ }
+ return false;
+ }
+
+ private OQueryOperator extractConditionOperator() {
+ if (!jumpWhiteSpaces())
+ // END OF PARSING: JUST RETURN
+ return null;
+
+ if (text.charAt(currentPos) == ')')
+ // FOUND ')': JUST RETURN
+ return null;
+
+ String word;
+ word = nextWord(true, " 0123456789'\"");
+
+ if (checkForEnd(word))
+ return null;
+
+ for (OQueryOperator op : OSQLEngine.getInstance().getRecordOperators()) {
+ if (word.startsWith(op.keyword)) {
+ final List<String> params = new ArrayList<String>();
+ // CHECK FOR PARAMETERS
+ if (word.length() > op.keyword.length() && word.charAt(op.keyword.length()) == OStringSerializerHelper.EMBEDDED_BEGIN) {
+ int paramBeginPos = currentPos - (word.length() - op.keyword.length());
+ currentPos = OStringSerializerHelper.getParameters(text, paramBeginPos, -1, params);
+ } else if (!word.equals(op.keyword))
+ throw new OQueryParsingException("Malformed usage of operator '" + op.toString() + "'. Parsed operator is: " + word);
+
+ try {
+ return op.configure(params);
+ } catch (Exception e) {
+ throw new OQueryParsingException("Syntax error using the operator '" + op.toString() + "'. Syntax is: " + op.getSyntax());
+ }
+ }
+ }
+
+ throw new OQueryParsingException("Unknown operator " + word, text, currentPos);
+ }
+
+ private Object extractConditionItem(final boolean iAllowOperator, final int iExpectedWords) {
+ final Object[] result = new Object[iExpectedWords];
+
+ for (int i = 0; i < iExpectedWords; ++i) {
+ final String[] words = nextValue(true);
+ if (words == null)
+ break;
+
+ if (words[0].length() > 0 && words[0].charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) {
+ braces++;
+
+ // SUB-CONDITION
+ currentPos = currentPos - words[0].length() + 1;
+
+ final Object subCondition = extractConditions(null);
+
+ if (!jumpWhiteSpaces() || text.charAt(currentPos) == ')')
+ braces--;
+
+ if (currentPos > -1)
+ currentPos++;
+
+ result[i] = subCondition;
+ } else if (words[0].charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN) {
+ // COLLECTION OF ELEMENTS
+ currentPos = currentPos - words[0].length();
+
+ final List<String> stringItems = new ArrayList<String>();
+ currentPos = OStringSerializerHelper.getCollection(text, currentPos, stringItems);
+
+ if (stringItems.get(0).charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN) {
+
+ final List<List<Object>> coll = new ArrayList<List<Object>>();
+ for (String stringItem : stringItems) {
+ final List<String> stringSubItems = new ArrayList<String>();
+ OStringSerializerHelper.getCollection(stringItem, 0, stringSubItems);
+
+ coll.add(convertCollectionItems(stringSubItems));
+ }
+
+ result[i] = coll;
+
+ } else {
+ result[i] = convertCollectionItems(stringItems);
+ }
+
+ currentPos++;
+
+ } else if (words[0].startsWith(OSQLFilterItemFieldAll.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) {
+
+ result[i] = new OSQLFilterItemFieldAll(this, words[1]);
+
+ } else if (words[0].startsWith(OSQLFilterItemFieldAny.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) {
+
+ result[i] = new OSQLFilterItemFieldAny(this, words[1]);
+
+ } else {
+
+ if (words[0].equals("NOT")) {
+ if (iAllowOperator)
+ return new OQueryOperatorNot();
+ else {
+ // GET THE NEXT VALUE
+ final String[] nextWord = nextValue(true);
+ if (nextWord != null && nextWord.length == 2) {
+ words[1] = words[1] + " " + nextWord[1];
+
+ if (words[1].endsWith(")"))
+ words[1] = words[1].substring(0, words[1].length() - 1);
+ }
+ }
+ }
+
+ if (words[1].endsWith(")")) {
+ final int openParenthesis = words[1].indexOf('(');
+ if (openParenthesis == -1)
+ words[1] = words[1].substring(0, words[1].length() - 1);
+ }
+
+ result[i] = OSQLHelper.parseValue(this, this, words[1], context);
+ }
+ }
+
+ return iExpectedWords == 1 ? result[0] : result;
+ }
+
+ private List<Object> convertCollectionItems(List<String> stringItems) {
+ List<Object> coll = new ArrayList<Object>();
+ for (String s : stringItems) {
+ coll.add(OSQLHelper.parseValue(this, this, s, context));
+ }
+ return coll;
+ }
+
+ public OSQLFilterCondition getRootCondition() {
+ return rootCondition;
+ }
+
+ private String[] nextValue(final boolean iAdvanceWhenNotFound) {
+ if (!jumpWhiteSpaces())
+ return null;
+
+ int begin = currentPos;
+ char c;
+ char stringBeginCharacter = ' ';
+ int openBraces = 0;
+ int openBraket = 0;
+ boolean escaped = false;
+ boolean escapingOn = false;
+
+ for (; currentPos < text.length(); ++currentPos) {
+ c = text.charAt(currentPos);
+
+ if (stringBeginCharacter == ' ' && (c == '"' || c == '\'')) {
+ // QUOTED STRING: GET UNTIL THE END OF QUOTING
+ stringBeginCharacter = c;
+ } else if (stringBeginCharacter != ' ') {
+ // INSIDE TEXT
+ if (c == '\\') {
+ escapingOn = true;
+ escaped = true;
+ } else {
+ if (c == stringBeginCharacter && !escapingOn) {
+ stringBeginCharacter = ' ';
+
+ if (openBraket == 0 && openBraces == 0) {
+ if (iAdvanceWhenNotFound)
+ currentPos++;
+ break;
+ }
+ }
+
+ if (escapingOn)
+ escapingOn = false;
+ }
+ } else if (c == '#' && currentPos == begin) {
+ // BEGIN OF RID
+ } else if (c == '(') {
+ openBraces++;
+ } else if (c == ')' && openBraces > 0) {
+ openBraces--;
+ } else if (c == OStringSerializerHelper.COLLECTION_BEGIN) {
+ openBraket++;
+ } else if (c == OStringSerializerHelper.COLLECTION_END) {
+ openBraket--;
+ if (openBraket == 0 && openBraces == 0) {
+ // currentPos++;
+ // break;
+ }
+ } else if (c == ' ' && openBraces == 0) {
+ break;
+ } else if (!Character.isLetter(c) && !Character.isDigit(c) && c != '.' && c != '$' && c != ':' && c != '-' && c != '_'
+ && c != '+' && c != '@' && openBraces == 0 && openBraket == 0) {
+ if (iAdvanceWhenNotFound)
+ currentPos++;
+ break;
+ }
+ }
+
+ if (escaped)
+ return new String[] { OStringSerializerHelper.decode(textUpperCase.substring(begin, currentPos)),
+ OStringSerializerHelper.decode(text.substring(begin, currentPos)) };
+ else
+ return new String[] { textUpperCase.substring(begin, currentPos), text.substring(begin, currentPos) };
+ }
+
+ private String nextWord(final boolean iForceUpperCase, final String iSeparators) {
+ StringBuilder word = new StringBuilder();
+ currentPos = OSQLHelper.nextWord(text, textUpperCase, currentPos, word, iForceUpperCase, iSeparators);
+ return word.toString();
+ }
+
+ private boolean jumpWhiteSpaces() {
+ currentPos = OStringParser.jumpWhiteSpaces(text, currentPos);
+ return currentPos > -1;
+ }
+
+ @Override
+ public String toString() {
+ if (rootCondition != null)
+ return "Parsed: " + rootCondition.toString();
+ return "Unparsed: " + text;
+ }
+
+ /**
+ * Binds parameters.
+ *
+ * @param iArgs
+ */
+ public void bindParameters(final Map<Object, Object> iArgs) {
+ if (parameterItems == null || iArgs == null || iArgs.size() == 0)
+ return;
+
+ for (Entry<Object, Object> entry : iArgs.entrySet()) {
+ if (entry.getKey() instanceof Integer)
+ parameterItems.get(((Integer) entry.getKey())).setValue(entry.setValue(entry.getValue()));
+ else {
+ String paramName = entry.getKey().toString();
+ for (OSQLFilterItemParameter value : parameterItems) {
+ if (value.getName().equalsIgnoreCase(paramName)) {
+ value.setValue(entry.getValue());
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ public OSQLFilterItemParameter addParameter(final String iName) {
+ final String name;
+ if (iName.charAt(0) == OStringSerializerHelper.PARAMETER_NAMED) {
+ name = iName.substring(1);
+
+ // CHECK THE PARAMETER NAME IS CORRECT
+ if (!OStringSerializerHelper.isAlphanumeric(name)) {
+ throw new OQueryParsingException("Parameter name '" + name + "' is invalid, only alphanumeric characters are allowed");
+ }
+ } else
+ name = iName;
+
+ final OSQLFilterItemParameter param = new OSQLFilterItemParameter(name);
+
+ if (parameterItems == null)
+ parameterItems = new ArrayList<OSQLFilterItemParameter>();
+
+ parameterItems.add(param);
+ return param;
+ }
+
+ public void setRootCondition(final OSQLFilterCondition iCondition) {
+ rootCondition = iCondition;
+ }
+}
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TraverseTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TraverseTest.java
index f26315aace1..bdd1bd0f66d 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TraverseTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TraverseTest.java
@@ -24,9 +24,14 @@
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
+import com.orientechnologies.orient.core.command.OCommandContext;
+import com.orientechnologies.orient.core.command.OCommandPredicate;
+import com.orientechnologies.orient.core.command.traverse.OTraverse;
import com.orientechnologies.orient.core.db.graph.OGraphDatabase;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
+import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
+import com.orientechnologies.orient.core.sql.filter.OSQLPredicate;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
@Test
@@ -89,18 +94,27 @@ public void deinit() {
database.close();
}
- public void traverseAllFromActorNoWhere() {
+ public void traverseSQLAllFromActorNoWhere() {
List<ODocument> result1 = database.command(new OSQLSynchQuery<ODocument>("traverse * from " + tomCruise.getIdentity()))
.execute();
Assert.assertEquals(result1.size(), totalElements);
}
- public void traverseOutFromOneActorNoWhere() {
+ public void traverseAPIAllFromActorNoWhere() {
+ List<OIdentifiable> result1 = new OTraverse().fields("*").target(tomCruise.getIdentity()).execute();
+ Assert.assertEquals(result1.size(), totalElements);
+ }
+
+ public void traverseSQLOutFromOneActorNoWhere() {
database.command(new OSQLSynchQuery<ODocument>("traverse out from " + tomCruise.getIdentity())).execute();
}
+ public void traverseAPIOutFromOneActorNoWhere() {
+ new OTraverse().field("out").target(tomCruise.getIdentity()).execute();
+ }
+
@Test
- public void traverseOutFromActor1Depth() {
+ public void traverseSQLOutFromActor1Depth() {
List<ODocument> result1 = database.command(
new OSQLSynchQuery<ODocument>("traverse out from " + tomCruise.getIdentity() + " where $depth <= 1")).execute();
@@ -111,14 +125,14 @@ public void traverseOutFromActor1Depth() {
}
@Test
- public void traverseDept02() {
+ public void traverseSQLDept02() {
List<ODocument> result1 = database.command(new OSQLSynchQuery<ODocument>("traverse any() from Movie where $depth < 2"))
.execute();
}
@Test
- public void traverseMoviesOnly() {
+ public void traverseSQLMoviesOnly() {
List<ODocument> result1 = database.command(
new OSQLSynchQuery<ODocument>("select from ( traverse any() from Movie ) where @class = 'Movie'")).execute();
Assert.assertTrue(result1.size() > 0);
@@ -128,7 +142,7 @@ public void traverseMoviesOnly() {
}
@Test
- public void traversePerClassFields() {
+ public void traverseSQLPerClassFields() {
List<ODocument> result1 = database.command(
new OSQLSynchQuery<ODocument>("select from ( traverse V.out, E.in from " + tomCruise.getIdentity()
+ ") where @class = 'Movie'")).execute();
@@ -139,7 +153,7 @@ public void traversePerClassFields() {
}
@Test
- public void traverseMoviesOnlyDepth() {
+ public void traverseSQLMoviesOnlyDepth() {
List<ODocument> result1 = database.command(
new OSQLSynchQuery<ODocument>("select from ( traverse * from " + tomCruise.getIdentity()
+ " where $depth <= 1 ) where @class = 'Movie'")).execute();
@@ -170,7 +184,7 @@ public void traverseSelect() {
}
@Test
- public void traverseSelectAndTraverseNested() {
+ public void traverseSQLSelectAndTraverseNested() {
List<ODocument> result1 = database.command(
new OSQLSynchQuery<ODocument>("traverse * from ( select from ( traverse * from " + tomCruise.getIdentity()
+ " where $depth <= 2 ) where @class = 'Movie' )")).execute();
@@ -178,7 +192,15 @@ public void traverseSelectAndTraverseNested() {
}
@Test
- public void traverseIterating() {
+ public void traverseAPISelectAndTraverseNested() {
+ List<ODocument> result1 = database.command(
+ new OSQLSynchQuery<ODocument>("traverse * from ( select from ( traverse * from " + tomCruise.getIdentity()
+ + " where $depth <= 2 ) where @class = 'Movie' )")).execute();
+ Assert.assertEquals(result1.size(), totalElements);
+ }
+
+ @Test
+ public void traverseSQLIterating() {
int cycles = 0;
for (OIdentifiable id : new OSQLSynchQuery<ODocument>("traverse * from Movie where $depth < 2")) {
cycles++;
@@ -186,6 +208,29 @@ public void traverseIterating() {
Assert.assertTrue(cycles > 0);
}
+ @Test
+ public void traverseAPIIterating() {
+ int cycles = 0;
+ for (OIdentifiable id : new OTraverse().target(database.browseClass("Movie").iterator()).predicate(new OCommandPredicate() {
+ public boolean evaluate(ORecord<?> iRecord, OCommandContext iContext) {
+ return ((Integer) iContext.getVariable("depth")) <= 2;
+ }
+ })) {
+ cycles++;
+ }
+ Assert.assertTrue(cycles > 0);
+ }
+
+ @Test
+ public void traverseAPIandSQLIterating() {
+ int cycles = 0;
+ for (OIdentifiable id : new OTraverse().target(database.browseClass("Movie").iterator()).predicate(
+ new OSQLPredicate("$depth <= 2"))) {
+ cycles++;
+ }
+ Assert.assertTrue(cycles > 0);
+ }
+
@Test
public void traverseSelectIterable() {
int cycles = 0;
|
d9ed3ad870a70bbda3183148223ee519e45bde43
|
orientdb
|
Issue 762 was fixed.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OClassIndexManager.java b/core/src/main/java/com/orientechnologies/orient/core/index/OClassIndexManager.java
index e860fcefb6b..2699f835912 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OClassIndexManager.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OClassIndexManager.java
@@ -29,6 +29,7 @@
import java.util.SortedSet;
import java.util.TreeSet;
+import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.OMultiValueChangeEvent;
import com.orientechnologies.orient.core.db.record.OMultiValueChangeTimeLine;
@@ -182,12 +183,7 @@ public void onRecordAfterDelete(final ODocument iRecord) {
// REMOVE INDEX OF ENTRIES FOR THE NON CHANGED ONLY VALUES
for (final OIndex<?> index : indexes) {
final Object key = index.getDefinition().getDocumentValueToIndex(iRecord);
- if (key instanceof Collection) {
- for (final Object keyItem : (Collection<?>) key)
- if (keyItem != null)
- index.remove(keyItem, iRecord);
- } else if (key != null)
- index.remove(key, iRecord);
+ deleteIndexKey(index, iRecord, key);
}
}
@@ -204,37 +200,80 @@ public void onRecordDeleteFailed(ODocument iDocument) {
releaseModificationLock(iDocument);
}
- private void processCompositeIndexUpdate(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
- final OIndexDefinition indexDefinition = index.getDefinition();
+ private static void processCompositeIndexUpdate(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
+ final OCompositeIndexDefinition indexDefinition = (OCompositeIndexDefinition) index.getDefinition();
+
final List<String> indexFields = indexDefinition.getFields();
+ final String multiValueField = indexDefinition.getMultiValueField();
+
for (final String indexField : indexFields) {
if (dirtyFields.contains(indexField)) {
final List<Object> origValues = new ArrayList<Object>(indexFields.size());
for (final String field : indexFields) {
- if (dirtyFields.contains(field)) {
- origValues.add(iRecord.getOriginalValue(field));
- } else {
- origValues.add(iRecord.<Object> field(field));
- }
+ if (!field.equals(multiValueField))
+ if (dirtyFields.contains(field)) {
+ origValues.add(iRecord.getOriginalValue(field));
+ } else {
+ origValues.add(iRecord.<Object> field(field));
+ }
}
- final Object origValue = indexDefinition.createValue(origValues);
- final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
+ if (multiValueField == null) {
+ final Object origValue = indexDefinition.createValue(origValues);
+ final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
- if (origValue != null) {
- index.remove(origValue, iRecord);
- }
+ if (origValue != null)
+ index.remove(origValue, iRecord);
- if (newValue != null) {
- index.put(newValue, iRecord.placeholder());
+ if (newValue != null)
+ index.put(newValue, iRecord.placeholder());
+ } else {
+ final OMultiValueChangeTimeLine<?, ?> multiValueChangeTimeLine = iRecord.getCollectionTimeLine(multiValueField);
+ if (multiValueChangeTimeLine == null) {
+ if (dirtyFields.contains(multiValueField))
+ origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.getOriginalValue(multiValueField));
+ else
+ origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.field(multiValueField));
+
+ final Object origValue = indexDefinition.createValue(origValues);
+ final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
+
+ processIndexUpdateFieldAssignment(index, iRecord, origValue, newValue);
+ } else {
+ if (dirtyFields.size() == 1) {
+ final Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
+ final Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();
+
+ for (OMultiValueChangeEvent<?, ?> changeEvent : multiValueChangeTimeLine.getMultiValueChangeEvents()) {
+ indexDefinition.processChangeEvent(changeEvent, keysToAdd, keysToRemove, origValues.toArray());
+ }
+
+ for (final Object keyToRemove : keysToRemove.keySet())
+ index.remove(keyToRemove, iRecord);
+
+ for (final Object keyToAdd : keysToAdd.keySet())
+ index.put(keyToAdd, iRecord.placeholder());
+ } else {
+ final OTrackedMultiValue fieldValue = iRecord.field(multiValueField);
+ final Object restoredMultiValue = fieldValue
+ .returnOriginalState(multiValueChangeTimeLine.getMultiValueChangeEvents());
+
+ origValues.add(indexDefinition.getMultiValueDefinitionIndex(), restoredMultiValue);
+
+ final Object origValue = indexDefinition.createValue(origValues);
+ final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
+
+ processIndexUpdateFieldAssignment(index, iRecord, origValue, newValue);
+ }
+ }
}
return;
}
}
}
- private void processSingleIndexUpdate(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
+ private static void processSingleIndexUpdate(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
final OIndexDefinition indexDefinition = index.getDefinition();
final List<String> indexFields = indexDefinition.getFields();
@@ -265,48 +304,47 @@ private void processSingleIndexUpdate(final OIndex<?> index, final Set<String> d
final Object origValue = indexDefinition.createValue(iRecord.getOriginalValue(indexField));
final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);
- if ((origValue instanceof Collection) && (newValue instanceof Collection)) {
- final Set<Object> valuesToRemove = new HashSet<Object>((Collection<?>) origValue);
- final Set<Object> valuesToAdd = new HashSet<Object>((Collection<?>) newValue);
+ processIndexUpdateFieldAssignment(index, iRecord, origValue, newValue);
+ }
+ }
- valuesToRemove.removeAll((Collection<?>) newValue);
- valuesToAdd.removeAll((Collection<?>) origValue);
+ private static void processIndexUpdateFieldAssignment(OIndex<?> index, ODocument iRecord, final Object origValue,
+ final Object newValue) {
+ if ((origValue instanceof Collection) && (newValue instanceof Collection)) {
+ final Set<Object> valuesToRemove = new HashSet<Object>((Collection<?>) origValue);
+ final Set<Object> valuesToAdd = new HashSet<Object>((Collection<?>) newValue);
- for (final Object valueToRemove : valuesToRemove) {
- if (valueToRemove != null) {
- index.remove(valueToRemove, iRecord);
- }
- }
+ valuesToRemove.removeAll((Collection<?>) newValue);
+ valuesToAdd.removeAll((Collection<?>) origValue);
- for (final Object valueToAdd : valuesToAdd) {
- if (valueToAdd != null) {
- index.put(valueToAdd, iRecord);
- }
+ for (final Object valueToRemove : valuesToRemove) {
+ if (valueToRemove != null) {
+ index.remove(valueToRemove, iRecord);
}
- } else {
- if (origValue instanceof Collection) {
- for (final Object origValueItem : (Collection<?>) origValue) {
- if (origValueItem != null) {
- index.remove(origValueItem, iRecord);
- }
- }
- } else if (origValue != null) {
- index.remove(origValue, iRecord);
+ }
+
+ for (final Object valueToAdd : valuesToAdd) {
+ if (valueToAdd != null) {
+ index.put(valueToAdd, iRecord);
}
+ }
+ } else {
+ deleteIndexKey(index, iRecord, origValue);
- if (newValue instanceof Collection) {
- for (final Object newValueItem : (Collection<?>) newValue) {
- index.put(newValueItem, iRecord.placeholder());
- }
- } else if (newValue != null) {
- index.put(newValue, iRecord.placeholder());
+ if (newValue instanceof Collection) {
+ for (final Object newValueItem : (Collection<?>) newValue) {
+ index.put(newValueItem, iRecord.placeholder());
}
+ } else if (newValue != null) {
+ index.put(newValue, iRecord.placeholder());
}
}
}
- private boolean processCompositeIndexDelete(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
- final OIndexDefinition indexDefinition = index.getDefinition();
+ private static boolean processCompositeIndexDelete(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
+ final OCompositeIndexDefinition indexDefinition = (OCompositeIndexDefinition) index.getDefinition();
+
+ final String multiValueField = indexDefinition.getMultiValueField();
final List<String> indexFields = indexDefinition.getFields();
for (final String indexField : indexFields) {
@@ -315,15 +353,27 @@ private boolean processCompositeIndexDelete(final OIndex<?> index, final Set<Str
final List<Object> origValues = new ArrayList<Object>(indexFields.size());
for (final String field : indexFields) {
- if (dirtyFields.contains(field))
- origValues.add(iRecord.getOriginalValue(field));
+ if (!field.equals(multiValueField))
+ if (dirtyFields.contains(field))
+ origValues.add(iRecord.getOriginalValue(field));
+ else
+ origValues.add(iRecord.<Object> field(field));
+ }
+
+ if (multiValueField != null) {
+ final OMultiValueChangeTimeLine<?, ?> multiValueChangeTimeLine = iRecord.getCollectionTimeLine(multiValueField);
+ if (multiValueChangeTimeLine != null) {
+ final OTrackedMultiValue fieldValue = iRecord.field(multiValueField);
+ final Object restoredMultiValue = fieldValue.returnOriginalState(multiValueChangeTimeLine.getMultiValueChangeEvents());
+ origValues.add(indexDefinition.getMultiValueDefinitionIndex(), restoredMultiValue);
+ } else if (dirtyFields.contains(multiValueField))
+ origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.getOriginalValue(multiValueField));
else
- origValues.add(iRecord.<Object> field(field));
+ origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.field(multiValueField));
}
final Object origValue = indexDefinition.createValue(origValues);
- if (origValue != null)
- index.remove(origValue, iRecord);
+ deleteIndexKey(index, iRecord, origValue);
return true;
}
@@ -331,8 +381,19 @@ private boolean processCompositeIndexDelete(final OIndex<?> index, final Set<Str
return false;
}
+ private static void deleteIndexKey(OIndex<?> index, ODocument iRecord, Object origValue) {
+ if (origValue instanceof Collection) {
+ for (final Object valueItem : (Collection<?>) origValue) {
+ if (valueItem != null)
+ index.remove(valueItem, iRecord);
+ }
+ } else if (origValue != null) {
+ index.remove(origValue, iRecord);
+ }
+ }
+
@SuppressWarnings({ "rawtypes", "unchecked" })
- private boolean processSingleIndexDelete(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
+ private static boolean processSingleIndexDelete(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
final OIndexDefinition indexDefinition = index.getDefinition();
final List<String> indexFields = indexDefinition.getFields();
@@ -352,21 +413,13 @@ private boolean processSingleIndexDelete(final OIndex<?> index, final Set<String
} else
origValue = indexDefinition.createValue(iRecord.getOriginalValue(indexField));
- if (origValue instanceof Collection) {
- for (final Object valueItem : (Collection<?>) origValue) {
- if (valueItem != null) {
- index.remove(valueItem, iRecord);
- }
- }
- } else if (origValue != null) {
- index.remove(origValue, iRecord);
- }
+ deleteIndexKey(index, iRecord, origValue);
return true;
}
return false;
}
- private void checkIndexedPropertiesOnCreation(final ODocument iRecord) {
+ private static void checkIndexedPropertiesOnCreation(final ODocument iRecord) {
final OClass cls = iRecord.getSchemaClass();
if (cls == null)
return;
@@ -386,7 +439,7 @@ private void checkIndexedPropertiesOnCreation(final ODocument iRecord) {
}
}
- private void acquireModificationLock(final ODocument iRecord) {
+ private static void acquireModificationLock(final ODocument iRecord) {
final OClass cls = iRecord.getSchemaClass();
if (cls == null)
return;
@@ -406,7 +459,7 @@ public int compare(OIndex<?> indexOne, OIndex<?> indexTwo) {
}
}
- private void releaseModificationLock(final ODocument iRecord) {
+ private static void releaseModificationLock(final ODocument iRecord) {
final OClass cls = iRecord.getSchemaClass();
if (cls == null)
return;
@@ -417,7 +470,7 @@ private void releaseModificationLock(final ODocument iRecord) {
}
}
- private void checkIndexedPropertiesOnUpdate(final ODocument iRecord) {
+ private static void checkIndexedPropertiesOnUpdate(final ODocument iRecord) {
final OClass cls = iRecord.getSchemaClass();
if (cls == null)
return;
@@ -448,7 +501,7 @@ private void checkIndexedPropertiesOnUpdate(final ODocument iRecord) {
}
}
- private ODocument checkForLoading(final ODocument iRecord) {
+ private static ODocument checkForLoading(final ODocument iRecord) {
if (iRecord.getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) {
try {
return (ODocument) iRecord.load();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OCompositeIndexDefinition.java b/core/src/main/java/com/orientechnologies/orient/core/index/OCompositeIndexDefinition.java
index b70418b6802..8bb1d48c224 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OCompositeIndexDefinition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OCompositeIndexDefinition.java
@@ -18,12 +18,16 @@
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
+import java.util.Set;
import com.orientechnologies.common.collection.OCompositeKey;
+import com.orientechnologies.orient.core.db.record.OMultiValueChangeEvent;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
@@ -36,9 +40,10 @@
public class OCompositeIndexDefinition extends ODocumentWrapperNoClass implements OIndexDefinition {
private final List<OIndexDefinition> indexDefinitions;
private String className;
+ private int multiValueDefinitionIndex = -1;
public OCompositeIndexDefinition() {
- indexDefinitions = new LinkedList<OIndexDefinition>();
+ indexDefinitions = new ArrayList<OIndexDefinition>(5);
}
/**
@@ -50,7 +55,7 @@ public OCompositeIndexDefinition() {
public OCompositeIndexDefinition(final String iClassName) {
super(new ODocument());
- indexDefinitions = new LinkedList<OIndexDefinition>();
+ indexDefinitions = new ArrayList<OIndexDefinition>(5);
className = iClassName;
}
@@ -64,8 +69,18 @@ public OCompositeIndexDefinition(final String iClassName) {
*/
public OCompositeIndexDefinition(final String iClassName, final List<? extends OIndexDefinition> iIndexes) {
super(new ODocument());
- indexDefinitions = new LinkedList<OIndexDefinition>();
- indexDefinitions.addAll(iIndexes);
+
+ indexDefinitions = new ArrayList<OIndexDefinition>(5);
+ for (OIndexDefinition indexDefinition : iIndexes) {
+ indexDefinitions.add(indexDefinition);
+
+ if (indexDefinition instanceof OIndexDefinitionMultiValue)
+ if (multiValueDefinitionIndex == -1)
+ multiValueDefinitionIndex = indexDefinitions.size() - 1;
+ else
+ throw new OIndexException("Composite key can not contain more than one collection item");
+ }
+
className = iClassName;
}
@@ -84,6 +99,13 @@ public String getClassName() {
*/
public void addIndex(final OIndexDefinition indexDefinition) {
indexDefinitions.add(indexDefinition);
+ if (indexDefinition instanceof OIndexDefinitionMultiValue) {
+ if (multiValueDefinitionIndex == -1)
+ multiValueDefinitionIndex = indexDefinitions.size() - 1;
+ else
+ throw new OIndexException("Composite key can not contain more than one collection item");
+ }
+
}
/**
@@ -97,11 +119,26 @@ public List<String> getFields() {
return Collections.unmodifiableList(fields);
}
+ /**
+ * {@inheritDoc}
+ */
+ public List<String> getFieldsToIndex() {
+ final List<String> fields = new LinkedList<String>();
+ for (final OIndexDefinition indexDefinition : indexDefinitions) {
+ fields.addAll(indexDefinition.getFieldsToIndex());
+ }
+ return Collections.unmodifiableList(fields);
+ }
+
/**
* {@inheritDoc}
*/
public Object getDocumentValueToIndex(final ODocument iDocument) {
- final OCompositeKey compositeKey = new OCompositeKey();
+ final List<OCompositeKey> compositeKeys = new ArrayList<OCompositeKey>(10);
+ final OCompositeKey firstKey = new OCompositeKey();
+ boolean containsCollection = false;
+
+ compositeKeys.add(firstKey);
for (final OIndexDefinition indexDefinition : indexDefinitions) {
final Object result = indexDefinition.getDocumentValueToIndex(iDocument);
@@ -109,18 +146,37 @@ public Object getDocumentValueToIndex(final ODocument iDocument) {
if (result == null)
return null;
- compositeKey.addKey(result);
+ containsCollection = addKey(firstKey, compositeKeys, containsCollection, result);
}
- return compositeKey;
+ if (!containsCollection)
+ return firstKey;
+
+ return compositeKeys;
+ }
+
+ public int getMultiValueDefinitionIndex() {
+ return multiValueDefinitionIndex;
+ }
+
+ public String getMultiValueField() {
+ if (multiValueDefinitionIndex >= 0)
+ return indexDefinitions.get(multiValueDefinitionIndex).getFields().get(0);
+
+ return null;
}
/**
* {@inheritDoc}
*/
- public Comparable<?> createValue(final List<?> params) {
+ public Object createValue(final List<?> params) {
int currentParamIndex = 0;
- final OCompositeKey compositeKey = new OCompositeKey();
+ final OCompositeKey firstKey = new OCompositeKey();
+
+ final List<OCompositeKey> compositeKeys = new ArrayList<OCompositeKey>(10);
+ compositeKeys.add(firstKey);
+
+ boolean containsCollection = false;
for (final OIndexDefinition indexDefinition : indexDefinitions) {
if (currentParamIndex + 1 > params.size())
@@ -137,6 +193,49 @@ public Comparable<?> createValue(final List<?> params) {
final Object keyValue = indexDefinition.createValue(indexParams);
+ if (keyValue == null)
+ return null;
+
+ containsCollection = addKey(firstKey, compositeKeys, containsCollection, keyValue);
+ }
+
+ if (!containsCollection)
+ return firstKey;
+
+ return compositeKeys;
+ }
+
+ public OIndexDefinitionMultiValue getMultiValueDefinition() {
+ if (multiValueDefinitionIndex > -1)
+ return (OIndexDefinitionMultiValue) indexDefinitions.get(multiValueDefinitionIndex);
+
+ return null;
+ }
+
+ public OCompositeKey createSingleValue(final List<?> params) {
+ final OCompositeKey compositeKey = new OCompositeKey();
+ int currentParamIndex = 0;
+
+ for (final OIndexDefinition indexDefinition : indexDefinitions) {
+ if (currentParamIndex + 1 > params.size())
+ break;
+
+ final int endIndex;
+ if (currentParamIndex + indexDefinition.getParamCount() > params.size())
+ endIndex = params.size();
+ else
+ endIndex = currentParamIndex + indexDefinition.getParamCount();
+
+ final List<?> indexParams = params.subList(currentParamIndex, endIndex);
+ currentParamIndex += indexDefinition.getParamCount();
+
+ final Object keyValue;
+
+ if (indexDefinition instanceof OIndexDefinitionMultiValue)
+ keyValue = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(indexParams.toArray());
+ else
+ keyValue = indexDefinition.createValue(indexParams);
+
if (keyValue == null)
return null;
@@ -146,13 +245,58 @@ public Comparable<?> createValue(final List<?> params) {
return compositeKey;
}
+ private static boolean addKey(OCompositeKey firstKey, List<OCompositeKey> compositeKeys, boolean containsCollection,
+ Object keyValue) {
+ if (keyValue instanceof Collection) {
+ final Collection<?> collectionKey = (Collection<?>) keyValue;
+ if (!containsCollection)
+ for (int i = 1; i < collectionKey.size(); i++) {
+ final OCompositeKey compositeKey = new OCompositeKey(firstKey.getKeys());
+ compositeKeys.add(compositeKey);
+ }
+ else
+ throw new OIndexException("Composite key can not contain more than one collection item");
+
+ int compositeIndex = 0;
+ for (final Object keyItem : collectionKey) {
+ final OCompositeKey compositeKey = compositeKeys.get(compositeIndex);
+ compositeKey.addKey(keyItem);
+
+ compositeIndex++;
+ }
+
+ containsCollection = true;
+ } else if (containsCollection)
+ for (final OCompositeKey compositeKey : compositeKeys)
+ compositeKey.addKey(keyValue);
+ else
+ firstKey.addKey(keyValue);
+
+ return containsCollection;
+ }
+
/**
* {@inheritDoc}
*/
- public Comparable<?> createValue(final Object... params) {
+ public Object createValue(final Object... params) {
return createValue(Arrays.asList(params));
}
+ public void processChangeEvent(OMultiValueChangeEvent<?, ?> changeEvent, Map<OCompositeKey, Integer> keysToAdd,
+ Map<OCompositeKey, Integer> keysToRemove, Object... params) {
+
+ final OIndexDefinitionMultiValue indexDefinitionMultiValue = (OIndexDefinitionMultiValue) indexDefinitions
+ .get(multiValueDefinitionIndex);
+
+ final CompositeWrapperMap compositeWrapperKeysToAdd = new CompositeWrapperMap(keysToAdd, indexDefinitions, params,
+ multiValueDefinitionIndex);
+
+ final CompositeWrapperMap compositeWrapperKeysToRemove = new CompositeWrapperMap(keysToRemove, indexDefinitions, params,
+ multiValueDefinitionIndex);
+
+ indexDefinitionMultiValue.processChangeEvent(changeEvent, compositeWrapperKeysToAdd, compositeWrapperKeysToRemove);
+ }
+
/**
* {@inheritDoc}
*/
@@ -235,7 +379,7 @@ public String toCreateIndexDDL(final String indexName, final String indexType) {
final StringBuilder ddl = new StringBuilder("create index ");
ddl.append(indexName).append(" on ").append(className).append(" ( ");
- final Iterator<String> fieldIterator = getFields().iterator();
+ final Iterator<String> fieldIterator = getFieldsToIndex().iterator();
if (fieldIterator.hasNext()) {
ddl.append(fieldIterator.next());
while (fieldIterator.hasNext()) {
@@ -244,14 +388,16 @@ public String toCreateIndexDDL(final String indexName, final String indexType) {
}
ddl.append(" ) ").append(indexType).append(' ');
- boolean first = true;
- for (OType oType : getTypes()) {
- if (first)
- first = false;
- else
- ddl.append(", ");
+ if (multiValueDefinitionIndex == -1) {
+ boolean first = true;
+ for (OType oType : getTypes()) {
+ if (first)
+ first = false;
+ else
+ ddl.append(", ");
- ddl.append(oType.name());
+ ddl.append(oType.name());
+ }
}
return ddl.toString();
@@ -277,6 +423,9 @@ protected void fromStream() {
indexDefinition.fromStream(indDoc);
indexDefinitions.add(indexDefinition);
+
+ if (indexDefinition instanceof OIndexDefinitionMultiValue)
+ multiValueDefinitionIndex = indexDefinitions.size() - 1;
}
} catch (final ClassNotFoundException e) {
@@ -291,4 +440,85 @@ protected void fromStream() {
throw new OIndexException("Error during composite index deserialization", e);
}
}
+
+ private static final class CompositeWrapperMap implements Map<Object, Integer> {
+ private final Map<OCompositeKey, Integer> underlying;
+ private final Object[] params;
+ private final List<OIndexDefinition> indexDefinitions;
+ private final int multiValueIndex;
+
+ private CompositeWrapperMap(Map<OCompositeKey, Integer> underlying, List<OIndexDefinition> indexDefinitions, Object[] params,
+ int multiValueIndex) {
+ this.underlying = underlying;
+ this.params = params;
+ this.multiValueIndex = multiValueIndex;
+ this.indexDefinitions = indexDefinitions;
+ }
+
+ public int size() {
+ return underlying.size();
+ }
+
+ public boolean isEmpty() {
+ return underlying.isEmpty();
+ }
+
+ public boolean containsKey(Object key) {
+ final OCompositeKey compositeKey = convertToCompositeKey(key);
+
+ return underlying.containsKey(compositeKey);
+ }
+
+ public boolean containsValue(Object value) {
+ return underlying.containsValue(value);
+ }
+
+ public Integer get(Object key) {
+ return underlying.get(convertToCompositeKey(key));
+ }
+
+ public Integer put(Object key, Integer value) {
+ final OCompositeKey compositeKey = convertToCompositeKey(key);
+ return underlying.put(compositeKey, value);
+ }
+
+ public Integer remove(Object key) {
+ return underlying.remove(convertToCompositeKey(key));
+ }
+
+ public void putAll(Map<? extends Object, ? extends Integer> m) {
+ throw new UnsupportedOperationException("Unsupported because of performance reasons");
+ }
+
+ public void clear() {
+ underlying.clear();
+ }
+
+ public Set<Object> keySet() {
+ throw new UnsupportedOperationException("Unsupported because of performance reasons");
+ }
+
+ public Collection<Integer> values() {
+ return underlying.values();
+ }
+
+ public Set<Entry<Object, Integer>> entrySet() {
+ throw new UnsupportedOperationException();
+ }
+
+ private OCompositeKey convertToCompositeKey(Object key) {
+ final OCompositeKey compositeKey = new OCompositeKey();
+
+ int paramsIndex = 0;
+ for (int i = 0; i < indexDefinitions.size(); i++) {
+ final OIndexDefinition indexDefinition = indexDefinitions.get(i);
+ if (i != multiValueIndex) {
+ compositeKey.addKey(indexDefinition.createValue(params[paramsIndex]));
+ paramsIndex++;
+ } else
+ compositeKey.addKey(((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(key));
+ }
+ return compositeKey;
+ }
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinition.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinition.java
index cfdfcbf1c03..79f183b550b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinition.java
@@ -30,86 +30,92 @@
* @author Andrey Lomakin, Artem Orobets
*/
public interface OIndexDefinition extends OIndexCallback {
- /**
- * @return Names of fields which given index is used to calculate key value. Order of fields is important.
- */
- public List<String> getFields();
+ /**
+ * @return Names of fields which given index is used to calculate key value. Order of fields is important.
+ */
+ public List<String> getFields();
- /**
- * @return Name of the class which this index belongs to.
- */
- public String getClassName();
+ /**
+ * @return Names of fields and their index modifiers (like "by value" for fields that hold <code>Map</code> values) which given
+ * index is used to calculate key value. Order of fields is important.
+ */
+ public List<String> getFieldsToIndex();
- /**
- * {@inheritDoc}
- */
- public boolean equals(Object index);
+ /**
+ * @return Name of the class which this index belongs to.
+ */
+ public String getClassName();
- /**
- * {@inheritDoc}
- */
- public int hashCode();
+ /**
+ * {@inheritDoc}
+ */
+ public boolean equals(Object index);
- /**
- * {@inheritDoc}
- */
- public String toString();
+ /**
+ * {@inheritDoc}
+ */
+ public int hashCode();
- /**
- * Calculates key value by passed in parameters.
- *
- * If it is impossible to calculate key value by given parameters <code>null</code> will be returned.
- *
- * @param params
- * Parameters from which index key will be calculated.
- *
- * @return Key value or null if calculation is impossible.
- */
- public Object createValue(List<?> params);
+ /**
+ * {@inheritDoc}
+ */
+ public String toString();
- /**
- * Calculates key value by passed in parameters.
- *
- * If it is impossible to calculate key value by given parameters <code>null</code> will be returned.
- *
- *
- * @param params
- * Parameters from which index key will be calculated.
- *
- * @return Key value or null if calculation is impossible.
- */
- public Object createValue(Object... params);
+ /**
+ * Calculates key value by passed in parameters.
+ *
+ * If it is impossible to calculate key value by given parameters <code>null</code> will be returned.
+ *
+ * @param params
+ * Parameters from which index key will be calculated.
+ *
+ * @return Key value or null if calculation is impossible.
+ */
+ public Object createValue(List<?> params);
- /**
- * Returns amount of parameters that are used to calculate key value. It does not mean that all parameters should be supplied. It
- * only means that if you provide more parameters they will be ignored and will not participate in index key calculation.
- *
- * @return Amount of that are used to calculate key value. Call result should be equals to {@code getTypes().length}.
- */
- public int getParamCount();
+ /**
+ * Calculates key value by passed in parameters.
+ *
+ * If it is impossible to calculate key value by given parameters <code>null</code> will be returned.
+ *
+ *
+ * @param params
+ * Parameters from which index key will be calculated.
+ *
+ * @return Key value or null if calculation is impossible.
+ */
+ public Object createValue(Object... params);
- /**
- * Return types of values from which index key consist. In case of index that is built on single document property value single
- * array that contains property type will be returned. In case of composite indexes result will contain several key types.
- *
- * @return Types of values from which index key consist.
- */
- public OType[] getTypes();
+ /**
+ * Returns amount of parameters that are used to calculate key value. It does not mean that all parameters should be supplied. It
+ * only means that if you provide more parameters they will be ignored and will not participate in index key calculation.
+ *
+ * @return Amount of that are used to calculate key value. Call result should be equals to {@code getTypes().length}.
+ */
+ public int getParamCount();
- /**
- * Serializes internal index state to document.
- *
- * @return Document that contains internal index state.
- */
- public ODocument toStream();
+ /**
+ * Return types of values from which index key consist. In case of index that is built on single document property value single
+ * array that contains property type will be returned. In case of composite indexes result will contain several key types.
+ *
+ * @return Types of values from which index key consist.
+ */
+ public OType[] getTypes();
- /**
- * Deserialize internal index state from document.
- *
- * @param document
- * Serialized index presentation.
- */
- public void fromStream(ODocument document);
+ /**
+ * Serializes internal index state to document.
+ *
+ * @return Document that contains internal index state.
+ */
+ public ODocument toStream();
- public String toCreateIndexDDL(String indexName, String indexType);
+ /**
+ * Deserialize internal index state from document.
+ *
+ * @param document
+ * Serialized index presentation.
+ */
+ public void fromStream(ODocument document);
+
+ public String toCreateIndexDDL(String indexName, String indexType);
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionFactory.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionFactory.java
index becbcbe6e29..854b9bb083e 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionFactory.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionFactory.java
@@ -1,6 +1,7 @@
package com.orientechnologies.orient.core.index;
import java.util.List;
+import java.util.regex.Pattern;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
@@ -14,6 +15,8 @@
* @author Artem Orobets
*/
public class OIndexDefinitionFactory {
+ private static final Pattern FILED_NAME_PATTERN = Pattern.compile("\\s+");
+
/**
* Creates an instance of {@link OIndexDefinition} for automatic index.
*
@@ -43,35 +46,26 @@ public static OIndexDefinition createIndexDefinition(final OClass oClass, final
* @return extracted property name
*/
public static String extractFieldName(final String fieldDefinition) {
- String[] fieldNameParts = fieldDefinition.split("\\s+");
+ String[] fieldNameParts = FILED_NAME_PATTERN.split(fieldDefinition);
if (fieldNameParts.length == 1)
return fieldDefinition;
if (fieldNameParts.length == 3 && "by".equalsIgnoreCase(fieldNameParts[1]))
return fieldNameParts[0];
throw new IllegalArgumentException("Illegal field name format, should be '<property> [by key|value]' but was '"
- + fieldDefinition + "'");
+ + fieldDefinition + '\'');
}
private static OIndexDefinition createMultipleFieldIndexDefinition(final OClass oClass, final List<String> fieldsToIndex,
final List<OType> types) {
- final OIndexDefinition indexDefinition;
final String className = oClass.getName();
final OCompositeIndexDefinition compositeIndex = new OCompositeIndexDefinition(className);
for (int i = 0, fieldsToIndexSize = fieldsToIndex.size(); i < fieldsToIndexSize; i++) {
- String fieldName = adjustFieldName(oClass, fieldsToIndex.get(i));
- final OType propertyType = types.get(i);
- if (propertyType.equals(OType.EMBEDDEDLIST) || propertyType.equals(OType.EMBEDDEDSET) || propertyType.equals(OType.LINKSET)
- || propertyType.equals(OType.LINKLIST) || propertyType.equals(OType.EMBEDDEDMAP) || propertyType.equals(OType.LINKMAP))
- throw new OIndexException("Collections are not supported in composite indexes");
-
- final OPropertyIndexDefinition propertyIndex = new OPropertyIndexDefinition(className, fieldName, propertyType);
- compositeIndex.addIndex(propertyIndex);
+ compositeIndex.addIndex(createSingleFieldIndexDefinition(oClass, fieldsToIndex.get(i), types.get(i)));
}
- indexDefinition = compositeIndex;
- return indexDefinition;
+ return compositeIndex;
}
private static void checkTypes(OClass oClass, List<String> fieldNames, List<OType> types) {
@@ -135,7 +129,7 @@ else if (type.equals(OType.LINKLIST)) {
}
private static OPropertyMapIndexDefinition.INDEX_BY extractMapIndexSpecifier(final String fieldName) {
- String[] fieldNameParts = fieldName.split("\\s+");
+ String[] fieldNameParts = FILED_NAME_PATTERN.split(fieldName);
if (fieldNameParts.length == 1)
return OPropertyMapIndexDefinition.INDEX_BY.KEY;
@@ -145,12 +139,12 @@ private static OPropertyMapIndexDefinition.INDEX_BY extractMapIndexSpecifier(fin
return OPropertyMapIndexDefinition.INDEX_BY.valueOf(fieldNameParts[2].toUpperCase());
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException("Illegal field name format, should be '<property> [by key|value]' but was '"
- + fieldName + "'");
+ + fieldName + '\'');
}
}
throw new IllegalArgumentException("Illegal field name format, should be '<property> [by key|value]' but was '" + fieldName
- + "'");
+ + '\'');
}
private static String adjustFieldName(final OClass clazz, final String fieldName) {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionMultiValue.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionMultiValue.java
index 6e93bc81818..b54c650516b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionMultiValue.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexDefinitionMultiValue.java
@@ -19,30 +19,34 @@
import com.orientechnologies.orient.core.db.record.OMultiValueChangeEvent;
- /**
- * Interface that indicates that index definition is based on collection of values but not on single value.
- *
- * @author <a href="mailto:[email protected]">Andrey Lomakin</a>
- * @since 20.12.11
- */
- public interface OIndexDefinitionMultiValue extends OIndexDefinition {
+/**
+ * Interface that indicates that index definition is based on collection of values but not on single value.
+ *
+ * @author <a href="mailto:[email protected]">Andrey Lomakin</a>
+ * @since 20.12.11
+ */
+public interface OIndexDefinitionMultiValue extends OIndexDefinition {
- /**
- * Converts passed in value in the key of single index entry.
- *
- * @param param Value to convert.
- * @return Index key.
- */
- public Object createSingleValue(final Object param);
+ /**
+ * Converts passed in value in the key of single index entry.
+ *
+ * @param param
+ * Value to convert.
+ * @return Index key.
+ */
+ public Object createSingleValue(final Object... param);
- /**
- * Process event that contains operation on collection and extract values that should be added removed from index
- * to reflect collection changes in the given index.
- *
- * @param changeEvent Event that describes operation that was performed on collection.
- * @param keysToAdd Values that should be added to related index.
- * @param keysToRemove Values that should be removed to related index.
- */
- public void processChangeEvent(final OMultiValueChangeEvent<?,?> changeEvent, final Map<Object, Integer> keysToAdd,
- final Map<Object, Integer> keysToRemove);
+ /**
+ * Process event that contains operation on collection and extract values that should be added removed from index to reflect
+ * collection changes in the given index.
+ *
+ * @param changeEvent
+ * Event that describes operation that was performed on collection.
+ * @param keysToAdd
+ * Values that should be added to related index.
+ * @param keysToRemove
+ * Values that should be removed to related index.
+ */
+ public void processChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
+ final Map<Object, Integer> keysToRemove);
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexDefinition.java b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexDefinition.java
index 2ceba637455..be35084b3bb 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexDefinition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyIndexDefinition.java
@@ -55,6 +55,10 @@ public List<String> getFields() {
return Collections.singletonList(field);
}
+ public List<String> getFieldsToIndex() {
+ return Collections.singletonList(field);
+ }
+
public Object getDocumentValueToIndex(final ODocument iDocument) {
if (OType.LINK.equals(keyType)) {
final OIdentifiable identifiable = iDocument.field(field, OType.LINK);
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyListIndexDefinition.java b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyListIndexDefinition.java
index 83d4d5a9558..23cdf4db719 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyListIndexDefinition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyListIndexDefinition.java
@@ -33,69 +33,69 @@
*/
public class OPropertyListIndexDefinition extends OAbstractIndexDefinitionMultiValue implements OIndexDefinitionMultiValue {
- public OPropertyListIndexDefinition(final String iClassName, final String iField, final OType iType) {
- super(iClassName, iField, iType);
- }
+ public OPropertyListIndexDefinition(final String iClassName, final String iField, final OType iType) {
+ super(iClassName, iField, iType);
+ }
- public OPropertyListIndexDefinition() {
- }
+ public OPropertyListIndexDefinition() {
+ }
- @Override
- public Object getDocumentValueToIndex(ODocument iDocument) {
- return createValue(iDocument.field(field));
- }
+ @Override
+ public Object getDocumentValueToIndex(ODocument iDocument) {
+ return createValue(iDocument.field(field));
+ }
- @Override
- public Object createValue(final List<?> params) {
- if (!(params.get(0) instanceof Collection))
- return null;
+ @Override
+ public Object createValue(final List<?> params) {
+ if (!(params.get(0) instanceof Collection))
+ return null;
- final Collection<?> multiValueCollection = (Collection<?>) params.get(0);
- final List<Object> values = new ArrayList<Object>(multiValueCollection.size());
- for (final Object item : multiValueCollection) {
- values.add(createSingleValue(item));
- }
- return values;
- }
+ final Collection<?> multiValueCollection = (Collection<?>) params.get(0);
+ final List<Object> values = new ArrayList<Object>(multiValueCollection.size());
+ for (final Object item : multiValueCollection) {
+ values.add(createSingleValue(item));
+ }
+ return values;
+ }
- @Override
- public Object createValue(final Object... params) {
- if (!(params[0] instanceof Collection)) {
- return null;
- }
+ @Override
+ public Object createValue(final Object... params) {
+ if (!(params[0] instanceof Collection)) {
+ return null;
+ }
- final Collection<?> multiValueCollection = (Collection<?>) params[0];
- final List<Object> values = new ArrayList<Object>(multiValueCollection.size());
- for (final Object item : multiValueCollection) {
- values.add(createSingleValue(item));
- }
- return values;
- }
+ final Collection<?> multiValueCollection = (Collection<?>) params[0];
+ final List<Object> values = new ArrayList<Object>(multiValueCollection.size());
+ for (final Object item : multiValueCollection) {
+ values.add(createSingleValue(item));
+ }
+ return values;
+ }
- public Object createSingleValue(final Object param) {
- return OType.convert(param, keyType.getDefaultJavaType());
- }
+ public Object createSingleValue(final Object... param) {
+ return OType.convert(param[0], keyType.getDefaultJavaType());
+ }
- public void processChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
- final Map<Object, Integer> keysToRemove) {
- switch (changeEvent.getChangeType()) {
- case ADD: {
- processAdd(createSingleValue(changeEvent.getValue()), keysToAdd, keysToRemove);
- break;
- }
- case REMOVE: {
- processRemoval(createSingleValue(changeEvent.getOldValue()), keysToAdd, keysToRemove);
- break;
- }
- case UPDATE: {
- processRemoval(createSingleValue(changeEvent.getOldValue()), keysToAdd, keysToRemove);
- processAdd(createSingleValue(changeEvent.getValue()), keysToAdd, keysToRemove);
- break;
- }
- default:
- throw new IllegalArgumentException("Invalid change type : " + changeEvent.getChangeType());
- }
- }
+ public void processChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
+ final Map<Object, Integer> keysToRemove) {
+ switch (changeEvent.getChangeType()) {
+ case ADD: {
+ processAdd(createSingleValue(changeEvent.getValue()), keysToAdd, keysToRemove);
+ break;
+ }
+ case REMOVE: {
+ processRemoval(createSingleValue(changeEvent.getOldValue()), keysToAdd, keysToRemove);
+ break;
+ }
+ case UPDATE: {
+ processRemoval(createSingleValue(changeEvent.getOldValue()), keysToAdd, keysToRemove);
+ processAdd(createSingleValue(changeEvent.getValue()), keysToAdd, keysToRemove);
+ break;
+ }
+ default:
+ throw new IllegalArgumentException("Invalid change type : " + changeEvent.getChangeType());
+ }
+ }
@Override
public String toCreateIndexDDL(String indexName, String indexType) {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyMapIndexDefinition.java b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyMapIndexDefinition.java
index 023b0fe2b5e..976c87a21e9 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyMapIndexDefinition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OPropertyMapIndexDefinition.java
@@ -17,6 +17,7 @@
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -32,176 +33,183 @@
*/
public class OPropertyMapIndexDefinition extends OAbstractIndexDefinitionMultiValue implements OIndexDefinitionMultiValue {
- /**
- * Indicates whether Map will be indexed using its keys or values.
- */
- public static enum INDEX_BY {
- KEY, VALUE
- }
-
- private INDEX_BY indexBy = INDEX_BY.KEY;
-
- public OPropertyMapIndexDefinition() {
- }
-
- public OPropertyMapIndexDefinition(final String iClassName, final String iField, final OType iType, final INDEX_BY indexBy) {
- super(iClassName, iField, iType);
-
- if (indexBy == null)
- throw new NullPointerException("You have to provide way by which map entries should be mapped");
-
- this.indexBy = indexBy;
- }
-
- @Override
- public Object getDocumentValueToIndex(ODocument iDocument) {
- return createValue(iDocument.field(field));
- }
-
- @Override
- public Object createValue(List<?> params) {
- if (!(params.get(0) instanceof Map))
- return null;
-
- final Collection<?> mapParams = extractMapParams((Map<?, ?>) params.get(0));
- final List<Object> result = new ArrayList<Object>(mapParams.size());
- for (final Object mapParam : mapParams) {
- result.add(createSingleValue(mapParam));
- }
-
- return result;
- }
-
- @Override
- public Object createValue(Object... params) {
- if (!(params[0] instanceof Map))
- return null;
-
- final Collection<?> mapParams = extractMapParams((Map<?, ?>) params[0]);
-
- final List<Object> result = new ArrayList<Object>(mapParams.size());
- for (final Object mapParam : mapParams) {
- result.add(createSingleValue(mapParam));
- }
-
- return result;
- }
-
- public INDEX_BY getIndexBy() {
- return indexBy;
- }
-
- @Override
- protected void serializeToStream() {
- super.serializeToStream();
- document.field("mapIndexBy", indexBy.toString());
- }
-
- @Override
- protected void serializeFromStream() {
- super.serializeFromStream();
- indexBy = INDEX_BY.valueOf(document.<String> field("mapIndexBy"));
- }
-
- private Collection<?> extractMapParams(Map<?, ?> map) {
- if (indexBy == INDEX_BY.KEY)
- return map.keySet();
-
- return map.values();
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null || getClass() != o.getClass())
- return false;
- if (!super.equals(o))
- return false;
-
- OPropertyMapIndexDefinition that = (OPropertyMapIndexDefinition) o;
-
- if (indexBy != that.indexBy)
- return false;
-
- return true;
- }
-
- public Object createSingleValue(final Object param) {
- return OType.convert(param, keyType.getDefaultJavaType());
- }
-
- public void processChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
- final Map<Object, Integer> keysToRemove) {
- final boolean result;
- if (indexBy.equals(INDEX_BY.KEY))
- result = processKeyChangeEvent(changeEvent, keysToAdd, keysToRemove);
- else
- result = processValueChangeEvent(changeEvent, keysToAdd, keysToRemove);
-
- if (!result)
- throw new IllegalArgumentException("Invalid change type :" + changeEvent.getChangeType());
- }
-
- private boolean processKeyChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
- final Map<Object, Integer> keysToRemove) {
- switch (changeEvent.getChangeType()) {
- case ADD:
- processAdd(createSingleValue(changeEvent.getKey()), keysToAdd, keysToRemove);
- return true;
- case REMOVE:
- processRemoval(createSingleValue(changeEvent.getKey()), keysToAdd, keysToRemove);
- return true;
- case UPDATE:
- return true;
- }
- return false;
- }
-
- private boolean processValueChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
- final Map<Object, Integer> keysToRemove) {
- switch (changeEvent.getChangeType()) {
- case ADD:
- processAdd(createSingleValue(changeEvent.getValue()), keysToAdd, keysToRemove);
- return true;
- case REMOVE:
- processRemoval(createSingleValue(changeEvent.getOldValue()), keysToAdd, keysToRemove);
- return true;
- case UPDATE:
- processRemoval(createSingleValue(changeEvent.getOldValue()), keysToAdd, keysToRemove);
- processAdd(createSingleValue(changeEvent.getValue()), keysToAdd, keysToRemove);
- return true;
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- int result = super.hashCode();
- result = 31 * result + indexBy.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- return "OPropertyMapIndexDefinition{" + "indexBy=" + indexBy + "} " + super.toString();
- }
-
- @Override
- public String toCreateIndexDDL(String indexName, String indexType) {
- final StringBuilder ddl = new StringBuilder("create index ");
-
- ddl.append(indexName).append(" on ");
- ddl.append(className).append(" ( ").append(field);
-
- if (indexBy == INDEX_BY.KEY)
- ddl.append(" by key");
- else
- ddl.append(" by value");
-
- ddl.append(" ) ");
- ddl.append(indexType);
-
- return ddl.toString();
- }
+ /**
+ * Indicates whether Map will be indexed using its keys or values.
+ */
+ public static enum INDEX_BY {
+ KEY, VALUE
+ }
+
+ private INDEX_BY indexBy = INDEX_BY.KEY;
+
+ public OPropertyMapIndexDefinition() {
+ }
+
+ public OPropertyMapIndexDefinition(final String iClassName, final String iField, final OType iType, final INDEX_BY indexBy) {
+ super(iClassName, iField, iType);
+
+ if (indexBy == null)
+ throw new NullPointerException("You have to provide way by which map entries should be mapped");
+
+ this.indexBy = indexBy;
+ }
+
+ @Override
+ public Object getDocumentValueToIndex(ODocument iDocument) {
+ return createValue(iDocument.field(field));
+ }
+
+ @Override
+ public Object createValue(List<?> params) {
+ if (!(params.get(0) instanceof Map))
+ return null;
+
+ final Collection<?> mapParams = extractMapParams((Map<?, ?>) params.get(0));
+ final List<Object> result = new ArrayList<Object>(mapParams.size());
+ for (final Object mapParam : mapParams) {
+ result.add(createSingleValue(mapParam));
+ }
+
+ return result;
+ }
+
+ @Override
+ public Object createValue(Object... params) {
+ if (!(params[0] instanceof Map))
+ return null;
+
+ final Collection<?> mapParams = extractMapParams((Map<?, ?>) params[0]);
+
+ final List<Object> result = new ArrayList<Object>(mapParams.size());
+ for (final Object mapParam : mapParams) {
+ result.add(createSingleValue(mapParam));
+ }
+
+ return result;
+ }
+
+ public INDEX_BY getIndexBy() {
+ return indexBy;
+ }
+
+ @Override
+ protected void serializeToStream() {
+ super.serializeToStream();
+ document.field("mapIndexBy", indexBy.toString());
+ }
+
+ @Override
+ protected void serializeFromStream() {
+ super.serializeFromStream();
+ indexBy = INDEX_BY.valueOf(document.<String> field("mapIndexBy"));
+ }
+
+ private Collection<?> extractMapParams(Map<?, ?> map) {
+ if (indexBy == INDEX_BY.KEY)
+ return map.keySet();
+
+ return map.values();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+ if (!super.equals(o))
+ return false;
+
+ OPropertyMapIndexDefinition that = (OPropertyMapIndexDefinition) o;
+
+ if (indexBy != that.indexBy)
+ return false;
+
+ return true;
+ }
+
+ public Object createSingleValue(final Object... param) {
+ return OType.convert(param[0], keyType.getDefaultJavaType());
+ }
+
+ public void processChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
+ final Map<Object, Integer> keysToRemove) {
+ final boolean result;
+ if (indexBy.equals(INDEX_BY.KEY))
+ result = processKeyChangeEvent(changeEvent, keysToAdd, keysToRemove);
+ else
+ result = processValueChangeEvent(changeEvent, keysToAdd, keysToRemove);
+
+ if (!result)
+ throw new IllegalArgumentException("Invalid change type :" + changeEvent.getChangeType());
+ }
+
+ private boolean processKeyChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
+ final Map<Object, Integer> keysToRemove) {
+ switch (changeEvent.getChangeType()) {
+ case ADD:
+ processAdd(createSingleValue(changeEvent.getKey()), keysToAdd, keysToRemove);
+ return true;
+ case REMOVE:
+ processRemoval(createSingleValue(changeEvent.getKey()), keysToAdd, keysToRemove);
+ return true;
+ case UPDATE:
+ return true;
+ }
+ return false;
+ }
+
+ private boolean processValueChangeEvent(final OMultiValueChangeEvent<?, ?> changeEvent, final Map<Object, Integer> keysToAdd,
+ final Map<Object, Integer> keysToRemove) {
+ switch (changeEvent.getChangeType()) {
+ case ADD:
+ processAdd(createSingleValue(changeEvent.getValue()), keysToAdd, keysToRemove);
+ return true;
+ case REMOVE:
+ processRemoval(createSingleValue(changeEvent.getOldValue()), keysToAdd, keysToRemove);
+ return true;
+ case UPDATE:
+ processRemoval(createSingleValue(changeEvent.getOldValue()), keysToAdd, keysToRemove);
+ processAdd(createSingleValue(changeEvent.getValue()), keysToAdd, keysToRemove);
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public List<String> getFieldsToIndex() {
+ if (indexBy == INDEX_BY.KEY)
+ return Collections.singletonList(field + " by key");
+ return Collections.singletonList(field + " by value");
+ }
+
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ result = 31 * result + indexBy.hashCode();
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "OPropertyMapIndexDefinition{" + "indexBy=" + indexBy + "} " + super.toString();
+ }
+
+ @Override
+ public String toCreateIndexDDL(String indexName, String indexType) {
+ final StringBuilder ddl = new StringBuilder("create index ");
+
+ ddl.append(indexName).append(" on ");
+ ddl.append(className).append(" ( ").append(field);
+
+ if (indexBy == INDEX_BY.KEY)
+ ddl.append(" by key");
+ else
+ ddl.append(" by value");
+
+ ddl.append(" ) ");
+ ddl.append(indexType);
+
+ return ddl.toString();
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/ORuntimeKeyIndexDefinition.java b/core/src/main/java/com/orientechnologies/orient/core/index/ORuntimeKeyIndexDefinition.java
index 270af80d814..ae6509a47f4 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/ORuntimeKeyIndexDefinition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/ORuntimeKeyIndexDefinition.java
@@ -53,6 +53,10 @@ public List<String> getFields() {
return Collections.emptyList();
}
+ public List<String> getFieldsToIndex() {
+ return Collections.emptyList();
+ }
+
public String getClassName() {
return null;
}
@@ -129,7 +133,7 @@ public String toString() {
*/
public String toCreateIndexDDL(final String indexName, final String indexType) {
final StringBuilder ddl = new StringBuilder("create index ");
- ddl.append(indexName).append(" ").append(indexType).append(" ");
+ ddl.append(indexName).append(' ').append(indexType).append(' ');
ddl.append("runtime ").append(serializer.getId());
return ddl.toString();
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinition.java b/core/src/main/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinition.java
index 3f17667999f..d4452d6edb7 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinition.java
@@ -12,131 +12,135 @@
import com.orientechnologies.orient.core.type.ODocumentWrapperNoClass;
public class OSimpleKeyIndexDefinition extends ODocumentWrapperNoClass implements OIndexDefinition {
- private OType[] keyTypes;
-
- public OSimpleKeyIndexDefinition(final OType... keyTypes) {
- super(new ODocument());
- this.keyTypes = keyTypes;
- }
-
- public OSimpleKeyIndexDefinition() {
- }
-
- public List<String> getFields() {
- return Collections.emptyList();
- }
-
- public String getClassName() {
- return null;
- }
-
- public Comparable<?> createValue(final List<?> params) {
- return createValue(params != null ? params.toArray() : null);
- }
-
- public Comparable<?> createValue(final Object... params) {
- if (params == null || params.length == 0)
- return null;
-
- if (keyTypes.length == 1)
- return (Comparable<?>) OType.convert(params[0], keyTypes[0].getDefaultJavaType());
-
- final OCompositeKey compositeKey = new OCompositeKey();
-
- for (int i = 0; i < params.length; ++i) {
- final Comparable<?> paramValue = (Comparable<?>) OType.convert(params[i], keyTypes[i].getDefaultJavaType());
-
- if (paramValue == null)
- return null;
- compositeKey.addKey(paramValue);
- }
-
- return compositeKey;
- }
-
- public int getParamCount() {
- return keyTypes.length;
- }
-
- public OType[] getTypes() {
- return keyTypes;
- }
-
- @Override
- public ODocument toStream() {
- document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
- try {
-
- final List<String> keyTypeNames = new ArrayList<String>(keyTypes.length);
-
- for (final OType keyType : keyTypes)
- keyTypeNames.add(keyType.toString());
-
- document.field("keyTypes", keyTypeNames, OType.EMBEDDEDLIST);
- return document;
- } finally {
- document.setInternalStatus(ORecordElement.STATUS.LOADED);
- }
- }
-
- @Override
- protected void fromStream() {
- final List<String> keyTypeNames = document.field("keyTypes");
- keyTypes = new OType[keyTypeNames.size()];
-
- int i = 0;
- for (final String keyTypeName : keyTypeNames) {
- keyTypes[i] = OType.valueOf(keyTypeName);
- i++;
- }
- }
-
- public Object getDocumentValueToIndex(final ODocument iDocument) {
- throw new OIndexException("This method is not supported in given index definition.");
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o)
- return true;
- if (o == null || getClass() != o.getClass())
- return false;
-
- final OSimpleKeyIndexDefinition that = (OSimpleKeyIndexDefinition) o;
- if (!Arrays.equals(keyTypes, that.keyTypes))
- return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = super.hashCode();
- result = 31 * result + (keyTypes != null ? Arrays.hashCode(keyTypes) : 0);
- return result;
- }
-
- @Override
- public String toString() {
- return "OSimpleKeyIndexDefinition{" + "keyTypes=" + (keyTypes == null ? null : Arrays.asList(keyTypes)) + '}';
- }
-
- /**
- * {@inheritDoc}
- *
- * @param indexName
- * @param indexType
- */
- public String toCreateIndexDDL(final String indexName, final String indexType) {
- final StringBuilder ddl = new StringBuilder("create index ");
- ddl.append(indexName).append(" ").append(indexType).append(" ");
-
- if (keyTypes != null && keyTypes.length > 0) {
- ddl.append(keyTypes[0].toString());
- for (int i = 1; i < keyTypes.length; i++) {
- ddl.append(", ").append(keyTypes[i].toString());
- }
- }
- return ddl.toString();
- }
+ private OType[] keyTypes;
+
+ public OSimpleKeyIndexDefinition(final OType... keyTypes) {
+ super(new ODocument());
+ this.keyTypes = keyTypes;
+ }
+
+ public OSimpleKeyIndexDefinition() {
+ }
+
+ public List<String> getFields() {
+ return Collections.emptyList();
+ }
+
+ public List<String> getFieldsToIndex() {
+ return Collections.emptyList();
+ }
+
+ public String getClassName() {
+ return null;
+ }
+
+ public Comparable<?> createValue(final List<?> params) {
+ return createValue(params != null ? params.toArray() : null);
+ }
+
+ public Comparable<?> createValue(final Object... params) {
+ if (params == null || params.length == 0)
+ return null;
+
+ if (keyTypes.length == 1)
+ return (Comparable<?>) OType.convert(params[0], keyTypes[0].getDefaultJavaType());
+
+ final OCompositeKey compositeKey = new OCompositeKey();
+
+ for (int i = 0; i < params.length; ++i) {
+ final Comparable<?> paramValue = (Comparable<?>) OType.convert(params[i], keyTypes[i].getDefaultJavaType());
+
+ if (paramValue == null)
+ return null;
+ compositeKey.addKey(paramValue);
+ }
+
+ return compositeKey;
+ }
+
+ public int getParamCount() {
+ return keyTypes.length;
+ }
+
+ public OType[] getTypes() {
+ return keyTypes;
+ }
+
+ @Override
+ public ODocument toStream() {
+ document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
+ try {
+
+ final List<String> keyTypeNames = new ArrayList<String>(keyTypes.length);
+
+ for (final OType keyType : keyTypes)
+ keyTypeNames.add(keyType.toString());
+
+ document.field("keyTypes", keyTypeNames, OType.EMBEDDEDLIST);
+ return document;
+ } finally {
+ document.setInternalStatus(ORecordElement.STATUS.LOADED);
+ }
+ }
+
+ @Override
+ protected void fromStream() {
+ final List<String> keyTypeNames = document.field("keyTypes");
+ keyTypes = new OType[keyTypeNames.size()];
+
+ int i = 0;
+ for (final String keyTypeName : keyTypeNames) {
+ keyTypes[i] = OType.valueOf(keyTypeName);
+ i++;
+ }
+ }
+
+ public Object getDocumentValueToIndex(final ODocument iDocument) {
+ throw new OIndexException("This method is not supported in given index definition.");
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+
+ final OSimpleKeyIndexDefinition that = (OSimpleKeyIndexDefinition) o;
+ if (!Arrays.equals(keyTypes, that.keyTypes))
+ return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ result = 31 * result + (keyTypes != null ? Arrays.hashCode(keyTypes) : 0);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "OSimpleKeyIndexDefinition{" + "keyTypes=" + (keyTypes == null ? null : Arrays.asList(keyTypes)) + '}';
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @param indexName
+ * @param indexType
+ */
+ public String toCreateIndexDDL(final String indexName, final String indexType) {
+ final StringBuilder ddl = new StringBuilder("create index ");
+ ddl.append(indexName).append(' ').append(indexType).append(' ');
+
+ if (keyTypes != null && keyTypes.length > 0) {
+ ddl.append(keyTypes[0].toString());
+ for (int i = 1; i < keyTypes.length; i++) {
+ ddl.append(", ").append(keyTypes[i].toString());
+ }
+ }
+ return ddl.toString();
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
index 5b0b4b95d08..3377f29751b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
@@ -60,7 +60,6 @@
import com.orientechnologies.orient.core.sql.operator.OIndexReuseType;
import com.orientechnologies.orient.core.sql.operator.OQueryOperator;
import com.orientechnologies.orient.core.sql.operator.OQueryOperatorBetween;
-import com.orientechnologies.orient.core.sql.operator.OQueryOperatorEquals;
import com.orientechnologies.orient.core.sql.operator.OQueryOperatorIn;
import com.orientechnologies.orient.core.sql.operator.OQueryOperatorMajor;
import com.orientechnologies.orient.core.sql.operator.OQueryOperatorMajorEquals;
@@ -382,11 +381,7 @@ public int compare(final OIndexSearchResult searchResultOne, final OIndexSearchR
final int searchResultFieldsCount = searchResult.fields().size();
final List<OIndex<?>> involvedIndexes = getInvolvedIndexes(iSchemaClass, searchResult);
- Collections.sort(involvedIndexes, new Comparator<OIndex>() {
- public int compare(final OIndex indexOne, final OIndex indexTwo) {
- return indexOne.getDefinition().getParamCount() - indexTwo.getDefinition().getParamCount();
- }
- });
+ Collections.sort(involvedIndexes, IndexComparator.INSTANCE);
// go through all possible index for given set of fields.
for (final OIndex index : involvedIndexes) {
@@ -395,7 +390,7 @@ public int compare(final OIndex indexOne, final OIndex indexTwo) {
// we need to test that last field in query subset and field in index that has the same position
// are equals.
- if (!(operator instanceof OQueryOperatorEquals)) {
+ if (!OIndexSearchResult.isIndexEqualityOperator(operator)) {
final String lastFiled = searchResult.lastField.getItemName(searchResult.lastField.getItemCount() - 1);
final String relatedIndexField = indexDefinition.getFields().get(searchResult.fieldValuePairs.size());
if (!lastFiled.equals(relatedIndexField))
@@ -423,7 +418,7 @@ public int compare(final OIndex indexOne, final OIndex indexTwo) {
return false;
}
- private List<OIndex<?>> getInvolvedIndexes(OClass iSchemaClass, OIndexSearchResult searchResultFields) {
+ private static List<OIndex<?>> getInvolvedIndexes(OClass iSchemaClass, OIndexSearchResult searchResultFields) {
final Set<OIndex<?>> involvedIndexes = iSchemaClass.getInvolvedIndexes(searchResultFields.fields());
final List<OIndex<?>> result = new ArrayList<OIndex<?>>(involvedIndexes.size());
@@ -438,18 +433,21 @@ private List<OIndex<?>> getInvolvedIndexes(OClass iSchemaClass, OIndexSearchResu
return result;
}
- private OIndexSearchResult analyzeQueryBranch(final OClass iSchemaClass, final OSQLFilterCondition iCondition,
+ private static OIndexSearchResult analyzeQueryBranch(final OClass iSchemaClass, OSQLFilterCondition iCondition,
final List<OIndexSearchResult> iIndexSearchResults) {
if (iCondition == null)
return null;
- final OQueryOperator operator = iCondition.getOperator();
- if (operator == null)
+ OQueryOperator operator = iCondition.getOperator();
+
+ while (operator == null) {
if (iCondition.getRight() == null && iCondition.getLeft() instanceof OSQLFilterCondition) {
- return analyzeQueryBranch(iSchemaClass, (OSQLFilterCondition) iCondition.getLeft(), iIndexSearchResults);
+ iCondition = (OSQLFilterCondition) iCondition.getLeft();
+ operator = iCondition.getOperator();
} else {
return null;
}
+ }
final OIndexReuseType indexReuseType = operator.getIndexReuseType(iCondition.getLeft(), iCondition.getRight());
if (indexReuseType.equals(OIndexReuseType.INDEX_INTERSECTION)) {
@@ -494,7 +492,7 @@ private OIndexSearchResult analyzeQueryBranch(final OClass iSchemaClass, final O
* Value to search
* @return true if the property was indexed and found, otherwise false
*/
- private OIndexSearchResult createIndexedProperty(final OSQLFilterCondition iCondition, final Object iItem) {
+ private static OIndexSearchResult createIndexedProperty(final OSQLFilterCondition iCondition, final Object iItem) {
if (iItem == null || !(iItem instanceof OSQLFilterItemField))
return null;
@@ -908,7 +906,7 @@ private boolean isIndexKeySizeQuery() {
return true;
}
- private Object getIndexKey(final OIndexDefinition indexDefinition, Object value) {
+ private static Object getIndexKey(final OIndexDefinition indexDefinition, Object value) {
if (indexDefinition instanceof OCompositeIndexDefinition) {
if (value instanceof List) {
final List<?> values = (List<?>) value;
@@ -939,7 +937,7 @@ protected void parseIndexSearchResult(final Collection<ODocument> entries) {
}
}
- private ODocument createIndexEntryAsDocument(final Object iKey, final OIdentifiable iValue) {
+ private static ODocument createIndexEntryAsDocument(final Object iKey, final OIdentifiable iValue) {
final ODocument doc = new ODocument().setOrdered(true);
doc.field("key", iKey);
doc.field("rid", iValue);
@@ -968,7 +966,7 @@ else if (projection.getValue() instanceof OSQLFunctionRuntime) {
}
}
- private boolean checkIndexExistence(OClass iSchemaClass, OIndexSearchResult result) {
+ private static boolean checkIndexExistence(OClass iSchemaClass, OIndexSearchResult result) {
if (!iSchemaClass.areIndexed(result.fields())) {
return false;
}
@@ -1024,4 +1022,12 @@ protected boolean optimizeExecution() {
return false;
}
+
+ private static class IndexComparator implements Comparator<OIndex> {
+ private static final IndexComparator INSTANCE = new IndexComparator();
+
+ public int compare(final OIndex indexOne, final OIndex indexTwo) {
+ return indexOne.getDefinition().getParamCount() - indexTwo.getDefinition().getParamCount();
+ }
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OIndexSearchResult.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OIndexSearchResult.java
index e16a0807051..30cbefc7129 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OIndexSearchResult.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OIndexSearchResult.java
@@ -7,6 +7,9 @@
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField;
import com.orientechnologies.orient.core.sql.operator.OQueryOperator;
+import com.orientechnologies.orient.core.sql.operator.OQueryOperatorContains;
+import com.orientechnologies.orient.core.sql.operator.OQueryOperatorContainsKey;
+import com.orientechnologies.orient.core.sql.operator.OQueryOperatorContainsValue;
import com.orientechnologies.orient.core.sql.operator.OQueryOperatorEquals;
/**
@@ -21,64 +24,69 @@
* index search and filed - value pair that uses this index should always be placed at last position.
*/
public class OIndexSearchResult {
- final Map<String, Object> fieldValuePairs = new HashMap<String, Object>();
- final OQueryOperator lastOperator;
- final OSQLFilterItemField.FieldChain lastField;
- final Object lastValue;
+ final Map<String, Object> fieldValuePairs = new HashMap<String, Object>(8);
+ final OQueryOperator lastOperator;
+ final OSQLFilterItemField.FieldChain lastField;
+ final Object lastValue;
- OIndexSearchResult(final OQueryOperator lastOperator, final OSQLFilterItemField.FieldChain field, final Object value) {
- this.lastOperator = lastOperator;
- lastField = field;
- lastValue = value;
- }
+ OIndexSearchResult(final OQueryOperator lastOperator, final OSQLFilterItemField.FieldChain field, final Object value) {
+ this.lastOperator = lastOperator;
+ lastField = field;
+ lastValue = value;
+ }
- /**
- * Combines two queries subset into one. This operation will be valid only if {@link #canBeMerged(OIndexSearchResult)} method will
- * return <code>true</code> for the same passed in parameter.
- *
- * @param searchResult
- * Query subset to merge.
- * @return New instance that presents merged query.
- */
- OIndexSearchResult merge(final OIndexSearchResult searchResult) {
- final OQueryOperator operator;
- final OIndexSearchResult result;
+ /**
+ * Combines two queries subset into one. This operation will be valid only if {@link #canBeMerged(OIndexSearchResult)} method will
+ * return <code>true</code> for the same passed in parameter.
+ *
+ * @param searchResult
+ * Query subset to merge.
+ * @return New instance that presents merged query.
+ */
+ OIndexSearchResult merge(final OIndexSearchResult searchResult) {
+ final OQueryOperator operator;
+ final OIndexSearchResult result;
- if (searchResult.lastOperator instanceof OQueryOperatorEquals) {
- result = new OIndexSearchResult(this.lastOperator, lastField, lastValue);
- result.fieldValuePairs.putAll(searchResult.fieldValuePairs);
- result.fieldValuePairs.putAll(fieldValuePairs);
- result.fieldValuePairs.put(searchResult.lastField.getItemName(0), searchResult.lastValue);
- } else {
- operator = searchResult.lastOperator;
- result = new OIndexSearchResult(operator, searchResult.lastField, searchResult.lastValue);
- result.fieldValuePairs.putAll(searchResult.fieldValuePairs);
- result.fieldValuePairs.putAll(fieldValuePairs);
- result.fieldValuePairs.put(lastField.getItemName(0), lastValue);
- }
- return result;
- }
+ if (searchResult.lastOperator instanceof OQueryOperatorEquals) {
+ result = new OIndexSearchResult(this.lastOperator, lastField, lastValue);
+ result.fieldValuePairs.putAll(searchResult.fieldValuePairs);
+ result.fieldValuePairs.putAll(fieldValuePairs);
+ result.fieldValuePairs.put(searchResult.lastField.getItemName(0), searchResult.lastValue);
+ } else {
+ operator = searchResult.lastOperator;
+ result = new OIndexSearchResult(operator, searchResult.lastField, searchResult.lastValue);
+ result.fieldValuePairs.putAll(searchResult.fieldValuePairs);
+ result.fieldValuePairs.putAll(fieldValuePairs);
+ result.fieldValuePairs.put(lastField.getItemName(0), lastValue);
+ }
+ return result;
+ }
- /**
- * @param searchResult
- * Query subset is going to be merged with given one.
- * @return <code>true</code> if two query subsets can be merged.
- */
- boolean canBeMerged(final OIndexSearchResult searchResult) {
- if (lastField.isLong() || searchResult.lastField.isLong()) {
- return false;
- }
- return (lastOperator instanceof OQueryOperatorEquals) || (searchResult.lastOperator instanceof OQueryOperatorEquals);
- }
+ /**
+ * @param searchResult
+ * Query subset is going to be merged with given one.
+ * @return <code>true</code> if two query subsets can be merged.
+ */
+ boolean canBeMerged(final OIndexSearchResult searchResult) {
+ if (lastField.isLong() || searchResult.lastField.isLong()) {
+ return false;
+ }
+ return isIndexEqualityOperator(lastOperator) || isIndexEqualityOperator(searchResult.lastOperator);
+ }
- List<String> fields() {
- final List<String> result = new ArrayList<String>(fieldValuePairs.size() + 1);
- result.addAll(fieldValuePairs.keySet());
- result.add(lastField.getItemName(0));
- return result;
- }
+ List<String> fields() {
+ final List<String> result = new ArrayList<String>(fieldValuePairs.size() + 1);
+ result.addAll(fieldValuePairs.keySet());
+ result.add(lastField.getItemName(0));
+ return result;
+ }
- int getFieldCount() {
- return fieldValuePairs.size() + 1;
- }
-}
\ No newline at end of file
+ int getFieldCount() {
+ return fieldValuePairs.size() + 1;
+ }
+
+ public static boolean isIndexEqualityOperator(OQueryOperator queryOperator) {
+ return queryOperator instanceof OQueryOperatorEquals || queryOperator instanceof OQueryOperatorContains
+ || queryOperator instanceof OQueryOperatorContainsKey || queryOperator instanceof OQueryOperatorContainsValue;
+ }
+}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorBetween.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorBetween.java
index 6d3a7c4089e..57e8dbcb8e3 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorBetween.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorBetween.java
@@ -26,6 +26,7 @@
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexInternal;
@@ -108,6 +109,8 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
else
result = index.getValuesBetween(keyOne, true, keyTwo, true);
} else {
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
final Object[] betweenKeys = (Object[]) keyParams.get(keyParams.size() - 1);
final Object betweenKeyOne = OSQLHelper.getValue(betweenKeys[0]);
@@ -128,12 +131,12 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
betweenKeyTwoParams.addAll(keyParams.subList(0, keyParams.size() - 1));
betweenKeyTwoParams.add(betweenKeyTwo);
- final Object keyOne = indexDefinition.createValue(betweenKeyOneParams);
+ final Object keyOne = compositeIndexDefinition.createSingleValue(betweenKeyOneParams);
if (keyOne == null)
return null;
- final Object keyTwo = indexDefinition.createValue(betweenKeyTwoParams);
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(betweenKeyTwoParams);
if (keyTwo == null)
return null;
@@ -146,6 +149,8 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (OProfiler.getInstance().isRecording()) {
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContains.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContains.java
index 0d4faf90b3e..bdc7782e424 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContains.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContains.java
@@ -15,21 +15,23 @@
*/
package com.orientechnologies.orient.core.sql.operator;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
import com.orientechnologies.orient.core.index.OIndexInternal;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
/**
* CONTAINS operator.
*
@@ -135,11 +137,37 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (indexResult instanceof Collection)
return (Collection<OIdentifiable>) indexResult;
- if(indexResult == null)
- return Collections.emptyList();
- return Collections.singletonList((OIdentifiable) indexResult);
+ if (indexResult == null)
+ return Collections.emptyList();
+ return Collections.singletonList((OIdentifiable) indexResult);
+ } else {
+ // in case of composite keys several items can be returned in case of we perform search
+ // using part of composite key stored in index.
+
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
+ final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
+
+ if (keyOne == null)
+ return null;
+
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams);
+
+ final Collection<OIdentifiable> result;
+ if (fetchLimit > -1)
+ result = index.getValuesBetween(keyOne, true, keyTwo, true, fetchLimit);
+ else
+ result = index.getValuesBetween(keyOne, true, keyTwo, true);
+
+ if (OProfiler.getInstance().isRecording()) {
+ OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
+ OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
+ }
+
+ return result;
}
- return null;
}
@Override
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContainsKey.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContainsKey.java
index ce7891be5a3..6f4f0b8f4f9 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContainsKey.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContainsKey.java
@@ -15,9 +15,16 @@
*/
package com.orientechnologies.orient.core.sql.operator;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
@@ -25,11 +32,6 @@
import com.orientechnologies.orient.core.index.OPropertyMapIndexDefinition;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
/**
* CONTAINS KEY operator.
*
@@ -69,20 +71,16 @@ public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight
public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object> keyParams, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
- if (!((index.getDefinition() instanceof OPropertyMapIndexDefinition) && ((OPropertyMapIndexDefinition) index.getDefinition())
- .getIndexBy() == OPropertyMapIndexDefinition.INDEX_BY.KEY))
- return null;
-
final OIndexInternal<?> internalIndex = index.getInternal();
if (!internalIndex.canBeUsedInEqualityOperators())
return null;
if (indexDefinition.getParamCount() == 1) {
- final Object key;
- if (indexDefinition instanceof OIndexDefinitionMultiValue)
- key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
- else
- key = indexDefinition.createValue(keyParams);
+ if (!((indexDefinition instanceof OPropertyMapIndexDefinition) && ((OPropertyMapIndexDefinition) indexDefinition)
+ .getIndexBy() == OPropertyMapIndexDefinition.INDEX_BY.KEY))
+ return null;
+
+ final Object key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
if (key == null)
return null;
@@ -91,12 +89,42 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (indexResult instanceof Collection)
return (Collection<OIdentifiable>) indexResult;
- if(indexResult == null)
- return Collections.emptyList();
- return Collections.singletonList((OIdentifiable) indexResult);
- }
+ if (indexResult == null)
+ return Collections.emptyList();
+ return Collections.singletonList((OIdentifiable) indexResult);
+ } else {
+ // in case of composite keys several items can be returned in case of we perform search
+ // using part of composite key stored in index.
- return null;
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
+ if (!((compositeIndexDefinition.getMultiValueDefinition() instanceof OPropertyMapIndexDefinition) && ((OPropertyMapIndexDefinition) compositeIndexDefinition
+ .getMultiValueDefinition()).getIndexBy() == OPropertyMapIndexDefinition.INDEX_BY.KEY))
+ return null;
+
+ final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
+
+ if (keyOne == null)
+ return null;
+
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams);
+
+ final Collection<OIdentifiable> result;
+ if (fetchLimit > -1)
+ result = index.getValuesBetween(keyOne, true, keyTwo, true, fetchLimit);
+ else
+ result = index.getValuesBetween(keyOne, true, keyTwo, true);
+
+ if (OProfiler.getInstance().isRecording()) {
+ OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
+ OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
+ }
+
+ return result;
+
+ }
}
@Override
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContainsValue.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContainsValue.java
index 8295ed4123e..95b6d0829da 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContainsValue.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContainsValue.java
@@ -15,12 +15,19 @@
*/
package com.orientechnologies.orient.core.sql.operator;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
import com.orientechnologies.common.exception.OException;
+import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.id.ORID;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
@@ -30,11 +37,6 @@
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
/**
* CONTAINS KEY operator.
*
@@ -114,20 +116,16 @@ public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight
public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object> keyParams, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
- if (!((index.getDefinition() instanceof OPropertyMapIndexDefinition) && ((OPropertyMapIndexDefinition) index.getDefinition())
- .getIndexBy() == OPropertyMapIndexDefinition.INDEX_BY.VALUE))
- return null;
-
final OIndexInternal<?> internalIndex = index.getInternal();
if (!internalIndex.canBeUsedInEqualityOperators())
return null;
if (indexDefinition.getParamCount() == 1) {
- final Object key;
- if (indexDefinition instanceof OIndexDefinitionMultiValue)
- key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
- else
- key = indexDefinition.createValue(keyParams);
+ if (!((indexDefinition instanceof OPropertyMapIndexDefinition) && ((OPropertyMapIndexDefinition) indexDefinition)
+ .getIndexBy() == OPropertyMapIndexDefinition.INDEX_BY.VALUE))
+ return null;
+
+ final Object key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
if (key == null)
return null;
@@ -136,11 +134,40 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (indexResult instanceof Collection)
return (Collection<OIdentifiable>) indexResult;
- if(indexResult == null)
- return Collections.emptyList();
- return Collections.singletonList((OIdentifiable) indexResult);
- }
- return null;
+ if (indexResult == null)
+ return Collections.emptyList();
+ return Collections.singletonList((OIdentifiable) indexResult);
+ } else {
+ // in case of composite keys several items can be returned in case of we perform search
+ // using part of composite key stored in index.
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
+ if (!((compositeIndexDefinition.getMultiValueDefinition() instanceof OPropertyMapIndexDefinition) && ((OPropertyMapIndexDefinition) compositeIndexDefinition
+ .getMultiValueDefinition()).getIndexBy() == OPropertyMapIndexDefinition.INDEX_BY.VALUE))
+ return null;
+
+ final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
+
+ if (keyOne == null)
+ return null;
+
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams);
+
+ final Collection<OIdentifiable> result;
+ if (fetchLimit > -1)
+ result = index.getValuesBetween(keyOne, true, keyTwo, true, fetchLimit);
+ else
+ result = index.getValuesBetween(keyOne, true, keyTwo, true);
+
+ if (OProfiler.getInstance().isRecording()) {
+ OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
+ OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
+ }
+
+ return result;
+ }
}
@Override
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java
index d8ae966b95f..b02cb692d81 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java
@@ -15,10 +15,15 @@
*/
package com.orientechnologies.orient.core.sql.operator;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
@@ -31,10 +36,6 @@
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemParameter;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
/**
* EQUALS operator.
*
@@ -120,19 +121,21 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (indexResult instanceof Collection)
return (Collection<OIdentifiable>) indexResult;
- if(indexResult == null)
- return Collections.emptyList();
- return Collections.singletonList((OIdentifiable) indexResult);
- } else {
+ if (indexResult == null)
+ return Collections.emptyList();
+ return Collections.singletonList((OIdentifiable) indexResult);
+ } else {
// in case of composite keys several items can be returned in case of we perform search
// using part of composite key stored in index.
- final Object keyOne = indexDefinition.createValue(keyParams);
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
+ final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
if (keyOne == null)
return null;
- final Object keyTwo = indexDefinition.createValue(keyParams);
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams);
final Collection<OIdentifiable> result;
if (fetchLimit > -1)
@@ -143,6 +146,8 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (OProfiler.getInstance().isRecording()) {
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
}
return result;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMajor.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMajor.java
index 0f258d3d683..0dcbbcccca6 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMajor.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMajor.java
@@ -23,6 +23,7 @@
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
@@ -91,12 +92,14 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
// index that contains keys with values field1=1 and field2=2 and which right included boundary
// is the biggest composite key in the index that contains key with value field1=1.
- final Object keyOne = indexDefinition.createValue(keyParams);
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
+ final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
if (keyOne == null)
return null;
- final Object keyTwo = indexDefinition.createValue(keyParams.subList(0, keyParams.size() - 1));
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams.subList(0, keyParams.size() - 1));
if (keyTwo == null)
return null;
@@ -109,6 +112,8 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (OProfiler.getInstance().isRecording()) {
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMajorEquals.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMajorEquals.java
index 151e05c3b6b..86aae9a5b83 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMajorEquals.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMajorEquals.java
@@ -22,6 +22,7 @@
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
@@ -90,12 +91,14 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
// index that contains keys with values field1=1 and field2=2 and which right included boundary
// is the biggest composite key in the index that contains key with value field1=1.
- final Object keyOne = indexDefinition.createValue(keyParams);
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
+ final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
if (keyOne == null)
return null;
- final Object keyTwo = indexDefinition.createValue(keyParams.subList(0, keyParams.size() - 1));
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams.subList(0, keyParams.size() - 1));
if (keyTwo == null)
return null;
@@ -108,6 +111,8 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (OProfiler.getInstance().isRecording()) {
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
}
}
return result;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMinor.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMinor.java
index 747a27f6b8c..f67eae28964 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMinor.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMinor.java
@@ -22,6 +22,7 @@
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
@@ -90,12 +91,14 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
// index that contains key with value field1=1 and which right not included boundary
// is the biggest composite key in the index that contains key with values field1=1 and field2=2.
- final Object keyOne = indexDefinition.createValue(keyParams.subList(0, keyParams.size() - 1));
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
+ final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams.subList(0, keyParams.size() - 1));
if (keyOne == null)
return null;
- final Object keyTwo = indexDefinition.createValue(keyParams);
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams);
if (keyTwo == null)
return null;
@@ -108,6 +111,8 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (OProfiler.getInstance().isRecording()) {
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMinorEquals.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMinorEquals.java
index d9bed3fc5f4..80cb554f2c0 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMinorEquals.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorMinorEquals.java
@@ -22,6 +22,7 @@
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexDefinitionMultiValue;
@@ -90,12 +91,14 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
// index that contains key with value field1=1 and which right not included boundary
// is the biggest composite key in the index that contains key with value field1=1 and field2=2.
- final Object keyOne = indexDefinition.createValue(keyParams.subList(0, keyParams.size() - 1));
+ final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
+
+ final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams.subList(0, keyParams.size() - 1));
if (keyOne == null)
return null;
- final Object keyTwo = indexDefinition.createValue(keyParams);
+ final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams);
if (keyTwo == null)
return null;
@@ -108,6 +111,8 @@ public Collection<OIdentifiable> executeIndexQuery(OIndex<?> index, List<Object>
if (OProfiler.getInstance().isRecording()) {
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage", 1);
OProfiler.getInstance().updateCounter("Query.compositeIndexUsage." + indexDefinition.getParamCount(), 1);
+ OProfiler.getInstance().updateCounter(
+ "Query.compositeIndexUsage." + indexDefinition.getParamCount() + '.' + keyParams.size(), 1);
}
}
return result;
diff --git a/core/src/test/java/com/orientechnologies/orient/core/index/OCompositeIndexDefinitionTest.java b/core/src/test/java/com/orientechnologies/orient/core/index/OCompositeIndexDefinitionTest.java
index dda2cae1050..c9752799bba 100644
--- a/core/src/test/java/com/orientechnologies/orient/core/index/OCompositeIndexDefinitionTest.java
+++ b/core/src/test/java/com/orientechnologies/orient/core/index/OCompositeIndexDefinitionTest.java
@@ -1,14 +1,24 @@
package com.orientechnologies.orient.core.index;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.orientechnologies.common.collection.OCompositeKey;
+import com.orientechnologies.common.exception.OException;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
+import com.orientechnologies.orient.core.db.record.OMultiValueChangeEvent;
+import com.orientechnologies.orient.core.db.record.OMultiValueChangeListener;
+import com.orientechnologies.orient.core.db.record.OTrackedList;
+import com.orientechnologies.orient.core.db.record.OTrackedMap;
+import com.orientechnologies.orient.core.db.record.OTrackedSet;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
@@ -36,14 +46,97 @@ public void testGetFields() {
@Test
public void testCreateValueSuccessful() {
- final Comparable<?> result = compositeIndex.createValue(Arrays.asList("12", "test"));
+ final Object result = compositeIndex.createValue(Arrays.asList("12", "test"));
Assert.assertEquals(result, new OCompositeKey(Arrays.asList(12, "test")));
}
+ @Test
+ public void testCreateMapValueSuccessful() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyMapIndexDefinition("testCollectionClass", "fTwo", OType.STRING,
+ OPropertyMapIndexDefinition.INDEX_BY.KEY));
+
+ final Map<String, String> stringMap = new HashMap<String, String>();
+ stringMap.put("key1", "val1");
+ stringMap.put("key2", "val2");
+
+ final Object result = compositeIndexDefinition.createValue(12, stringMap);
+
+ final Collection<OCompositeKey> collectionResult = (Collection<OCompositeKey>) result;
+
+ Assert.assertEquals(collectionResult.size(), 2);
+ Assert.assertTrue(collectionResult.contains(new OCompositeKey(12, "key1")));
+ Assert.assertTrue(collectionResult.contains(new OCompositeKey(12, "key2")));
+ }
+
+ @Test
+ public void testCreateCollectionValueSuccessfulOne() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
+
+ final Object result = compositeIndexDefinition.createValue(12, Arrays.asList(1, 2));
+
+ final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();
+
+ expectedResult.add(new OCompositeKey(12, 1));
+ expectedResult.add(new OCompositeKey(12, 2));
+
+ Assert.assertEquals(result, expectedResult);
+ }
+
+ @Test
+ public void testCreateCollectionValueSuccessfulTwo() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+
+ final Object result = compositeIndexDefinition.createValue(Arrays.asList(Arrays.asList(1, 2), 12));
+
+ final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();
+
+ expectedResult.add(new OCompositeKey(1, 12));
+ expectedResult.add(new OCompositeKey(2, 12));
+
+ Assert.assertEquals(result, expectedResult);
+ }
+
+ @Test
+ public void testCreateCollectionValueSuccessfulThree() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.STRING));
+
+ final Object result = compositeIndexDefinition.createValue(12, Arrays.asList(1, 2), "test");
+
+ final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();
+
+ expectedResult.add(new OCompositeKey(12, 1, "test"));
+ expectedResult.add(new OCompositeKey(12, 2, "test"));
+
+ Assert.assertEquals(result, expectedResult);
+ }
+
+ @Test(expectedExceptions = OIndexException.class)
+ public void testCreateCollectionValueTwoCollections() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+
+ compositeIndexDefinition.createValue(Arrays.asList(1, 2), Arrays.asList(12));
+ }
+
@Test
public void testCreateValueWrongParam() {
- final Comparable<?> result = compositeIndex.createValue(Arrays.asList("1t2", "test"));
+ final Object result = compositeIndex.createValue(Arrays.asList("1t2", "test"));
Assert.assertNull(result);
}
@@ -92,6 +185,113 @@ public void testDocumentToIndexSuccessful() {
Assert.assertEquals(result, new OCompositeKey(Arrays.asList(12, "test")));
}
+ @Test
+ public void testDocumentToIndexMapValueSuccessful() {
+ final ODocument document = new ODocument();
+
+ final Map<String, String> stringMap = new HashMap<String, String>();
+ stringMap.put("key1", "val1");
+ stringMap.put("key2", "val2");
+
+ document.field("fOne", 12);
+ document.field("fTwo", stringMap);
+
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyMapIndexDefinition("testCollectionClass", "fTwo", OType.STRING,
+ OPropertyMapIndexDefinition.INDEX_BY.KEY));
+
+ final Object result = compositeIndexDefinition.getDocumentValueToIndex(document);
+ final Collection<OCompositeKey> collectionResult = (Collection<OCompositeKey>) result;
+
+ Assert.assertEquals(collectionResult.size(), 2);
+ Assert.assertTrue(collectionResult.contains(new OCompositeKey(12, "key1")));
+ Assert.assertTrue(collectionResult.contains(new OCompositeKey(12, "key2")));
+ }
+
+ @Test
+ public void testDocumentToIndexCollectionValueSuccessfulOne() {
+ final ODocument document = new ODocument();
+
+ document.field("fOne", 12);
+ document.field("fTwo", Arrays.asList(1, 2));
+
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
+
+ final Object result = compositeIndexDefinition.getDocumentValueToIndex(document);
+
+ final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();
+
+ expectedResult.add(new OCompositeKey(12, 1));
+ expectedResult.add(new OCompositeKey(12, 2));
+
+ Assert.assertEquals(result, expectedResult);
+ }
+
+ @Test
+ public void testDocumentToIndexCollectionValueSuccessfulTwo() {
+ final ODocument document = new ODocument();
+
+ document.field("fOne", 12);
+ document.field("fTwo", Arrays.asList(1, 2));
+
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+
+ final Object result = compositeIndexDefinition.getDocumentValueToIndex(document);
+
+ final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();
+
+ expectedResult.add(new OCompositeKey(1, 12));
+ expectedResult.add(new OCompositeKey(2, 12));
+
+ Assert.assertEquals(result, expectedResult);
+ }
+
+ @Test
+ public void testDocumentToIndexCollectionValueSuccessfulThree() {
+ final ODocument document = new ODocument();
+
+ document.field("fOne", 12);
+ document.field("fTwo", Arrays.asList(1, 2));
+ document.field("fThree", "test");
+
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.STRING));
+
+ final Object result = compositeIndexDefinition.getDocumentValueToIndex(document);
+
+ final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();
+
+ expectedResult.add(new OCompositeKey(12, 1, "test"));
+ expectedResult.add(new OCompositeKey(12, 2, "test"));
+
+ Assert.assertEquals(result, expectedResult);
+ }
+
+ @Test(expectedExceptions = OException.class)
+ public void testDocumentToIndexCollectionValueTwoCollections() {
+ final ODocument document = new ODocument();
+
+ document.field("fOne", Arrays.asList(12));
+ document.field("fTwo", Arrays.asList(1, 2));
+
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");
+
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
+ compositeIndexDefinition.getDocumentValueToIndex(document);
+ }
+
@Test
public void testDocumentToIndexWrongField() {
final ODocument document = new ODocument();
@@ -179,6 +379,246 @@ public void testClassOnlyConstructor() {
Assert.assertEquals(result, emptyCompositeIndexTwo);
}
+ public void testProcessChangeListEventsOne() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.STRING));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));
+
+ final ODocument doc = new ODocument();
+ doc.unsetDirty();
+ Assert.assertFalse(doc.isDirty());
+
+ final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
+ final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
+
+ trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
+ public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
+ firedEvents.add(event);
+ }
+ });
+
+ trackedList.add("l1");
+ trackedList.add("l2");
+ trackedList.add("l3");
+ trackedList.remove("l2");
+
+ Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
+ Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();
+
+ for (OMultiValueChangeEvent<Integer, String> multiValueChangeEvent : firedEvents)
+ compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);
+
+ Assert.assertEquals(keysToRemove.size(), 0);
+ Assert.assertEquals(keysToAdd.size(), 2);
+
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l1", 3)));
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l3", 3)));
+ }
+
+ public void testProcessChangeListEventsTwo() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.STRING));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));
+
+ final ODocument doc = new ODocument();
+ doc.unsetDirty();
+ Assert.assertFalse(doc.isDirty());
+
+ final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
+ final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();
+
+ trackedList.add("l1");
+ trackedList.add("l2");
+ trackedList.add("l3");
+ trackedList.remove("l2");
+
+ trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
+ public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
+ firedEvents.add(event);
+ }
+ });
+
+ trackedList.add("l4");
+ trackedList.remove("l1");
+
+ Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
+ Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();
+
+ for (OMultiValueChangeEvent<Integer, String> multiValueChangeEvent : firedEvents)
+ compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);
+
+ Assert.assertEquals(keysToRemove.size(), 1);
+ Assert.assertEquals(keysToAdd.size(), 1);
+
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l4", 3)));
+ Assert.assertTrue(keysToRemove.containsKey(new OCompositeKey(2, "l1", 3)));
+ }
+
+ public void testProcessChangeSetEventsOne() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.STRING));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));
+
+ final ODocument doc = new ODocument();
+ doc.unsetDirty();
+ Assert.assertFalse(doc.isDirty());
+
+ final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
+ final List<OMultiValueChangeEvent<String, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<String, String>>();
+
+ trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
+ public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
+ firedEvents.add(event);
+ }
+ });
+
+ trackedSet.add("l1");
+ trackedSet.add("l2");
+ trackedSet.add("l3");
+ trackedSet.remove("l2");
+
+ Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
+ Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();
+
+ for (OMultiValueChangeEvent<String, String> multiValueChangeEvent : firedEvents)
+ compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);
+
+ Assert.assertEquals(keysToRemove.size(), 0);
+ Assert.assertEquals(keysToAdd.size(), 2);
+
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l1", 3)));
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l3", 3)));
+ }
+
+ public void testProcessChangeSetEventsTwo() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.STRING));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));
+
+ final ODocument doc = new ODocument();
+ doc.unsetDirty();
+ Assert.assertFalse(doc.isDirty());
+
+ final OTrackedSet<String> trackedMap = new OTrackedSet<String>(doc);
+ final List<OMultiValueChangeEvent<String, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<String, String>>();
+
+ trackedMap.add("l1");
+ trackedMap.add("l2");
+ trackedMap.add("l3");
+ trackedMap.remove("l2");
+
+ trackedMap.addChangeListener(new OMultiValueChangeListener<String, String>() {
+ public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
+ firedEvents.add(event);
+ }
+ });
+
+ trackedMap.add("l4");
+ trackedMap.remove("l1");
+
+ Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
+ Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();
+
+ for (OMultiValueChangeEvent<String, String> multiValueChangeEvent : firedEvents)
+ compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);
+
+ Assert.assertEquals(keysToRemove.size(), 1);
+ Assert.assertEquals(keysToAdd.size(), 1);
+
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l4", 3)));
+ Assert.assertTrue(keysToRemove.containsKey(new OCompositeKey(2, "l1", 3)));
+ }
+
+ public void testProcessChangeKeyMapEventsOne() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyMapIndexDefinition("testCollectionClass", "fTwo", OType.STRING,
+ OPropertyMapIndexDefinition.INDEX_BY.KEY));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));
+
+ final ODocument doc = new ODocument();
+ doc.unsetDirty();
+ Assert.assertFalse(doc.isDirty());
+
+ final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc);
+ final List<OMultiValueChangeEvent<Object, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Object, String>>();
+
+ trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() {
+ public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) {
+ firedEvents.add(event);
+ }
+ });
+
+ trackedMap.put("k1", "v1");
+ trackedMap.put("k2", "v2");
+ trackedMap.put("k3", "v3");
+ trackedMap.remove("k2");
+
+ Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
+ Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();
+
+ for (OMultiValueChangeEvent<Object, String> multiValueChangeEvent : firedEvents)
+ compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);
+
+ Assert.assertEquals(keysToRemove.size(), 0);
+ Assert.assertEquals(keysToAdd.size(), 2);
+
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "k1", 3)));
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "k3", 3)));
+ }
+
+ public void testProcessChangeKeyMapEventsTwo() {
+ final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();
+
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
+ compositeIndexDefinition.addIndex(new OPropertyMapIndexDefinition("testCollectionClass", "fTwo", OType.STRING,
+ OPropertyMapIndexDefinition.INDEX_BY.KEY));
+ compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));
+
+ final ODocument doc = new ODocument();
+ doc.unsetDirty();
+ Assert.assertFalse(doc.isDirty());
+
+ final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc);
+
+ trackedMap.put("k1", "v1");
+ trackedMap.put("k2", "v2");
+ trackedMap.put("k3", "v3");
+ trackedMap.remove("k2");
+
+ final List<OMultiValueChangeEvent<Object, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Object, String>>();
+
+ trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() {
+ public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) {
+ firedEvents.add(event);
+ }
+ });
+
+ trackedMap.put("k4", "v4");
+ trackedMap.remove("k1");
+
+ Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
+ Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();
+
+ for (OMultiValueChangeEvent<Object, String> multiValueChangeEvent : firedEvents)
+ compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);
+
+ Assert.assertEquals(keysToRemove.size(), 1);
+ Assert.assertEquals(keysToAdd.size(), 1);
+
+ Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "k4", 3)));
+ Assert.assertTrue(keysToRemove.containsKey(new OCompositeKey(2, "k1", 3)));
+ }
+
@Test
public void testClassName() {
Assert.assertEquals("testClass", compositeIndex.getClassName());
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ClassIndexManagerTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ClassIndexManagerTest.java
index f6a09dfbf0d..4cf2f5fa933 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ClassIndexManagerTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ClassIndexManagerTest.java
@@ -1,6 +1,7 @@
package com.orientechnologies.orient.test.database.auto;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
@@ -16,6 +17,7 @@
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
+import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OIndexDefinition;
@@ -29,839 +31,1275 @@
@Test(groups = { "index" })
public class ClassIndexManagerTest {
- private final ODatabaseDocumentTx database;
-
- @Parameters(value = "url")
- public ClassIndexManagerTest(final String iURL) {
- database = new ODatabaseDocumentTx(iURL);
- }
-
- @BeforeClass
- public void beforeClass() {
- if (database.isClosed())
- database.open("admin", "admin");
-
- final OSchema schema = database.getMetadata().getSchema();
- final OClass superClass = schema.createClass("classIndexManagerTestSuperClass");
- final OProperty propertyZero = superClass.createProperty("prop0", OType.STRING);
- propertyZero.createIndex(OClass.INDEX_TYPE.UNIQUE);
-
- final OClass oClass = schema.createClass("classIndexManagerTestClass", superClass);
- final OProperty propOne = oClass.createProperty("prop1", OType.STRING);
- propOne.createIndex(OClass.INDEX_TYPE.UNIQUE);
-
- final OProperty propTwo = oClass.createProperty("prop2", OType.INTEGER);
- propTwo.createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
-
- oClass.createProperty("prop3", OType.BOOLEAN);
-
- final OProperty propFour = oClass.createProperty("prop4", OType.EMBEDDEDLIST, OType.STRING);
- propFour.createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
-
- oClass.createProperty("prop5", OType.EMBEDDEDMAP, OType.STRING);
- oClass.createIndex("classIndexManagerTestIndexByKey", OClass.INDEX_TYPE.NOTUNIQUE, "prop5");
- oClass.createIndex("classIndexManagerTestIndexByValue", OClass.INDEX_TYPE.NOTUNIQUE, "prop5 by value");
-
- final OProperty propSix = oClass.createProperty("prop6", OType.EMBEDDEDSET, OType.STRING);
- propSix.createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
-
- oClass.createIndex("classIndexManagerComposite", OClass.INDEX_TYPE.UNIQUE, "prop1", "prop2");
-
- final OClass oClassTwo = schema.createClass("classIndexManagerTestClassTwo");
- oClassTwo.createProperty("prop1", OType.STRING);
- oClassTwo.createProperty("prop2", OType.INTEGER);
-
- schema.save();
-
- database.close();
- }
-
- @BeforeMethod
- public void beforeMethod() {
- if (database.isClosed())
- database.open("admin", "admin");
- }
-
- @AfterMethod
- public void afterMethod() {
- database.command(new OCommandSQL("delete from classIndexManagerTestClass")).execute();
- database.command(new OCommandSQL("delete from classIndexManagerTestClassTwo")).execute();
- database.command(new OCommandSQL("delete from classIndexManagerTestSuperClass")).execute();
- database.close();
- }
-
- @AfterClass
- public void afterClass() {
- if (database.isClosed())
- database.open("admin", "admin");
- database.command(new OCommandSQL("drop class classIndexManagerTestClass")).execute();
- database.command(new OCommandSQL("drop class classIndexManagerTestClassTwo")).execute();
- database.command(new OCommandSQL("drop class classIndexManagerTestSuperClass")).execute();
- database.getMetadata().getSchema().reload();
- database.getLevel2Cache().clear();
- database.close();
- }
-
- public void testPropertiesCheckUniqueIndexDubKeysCreate() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
-
- docOne.field("prop1", "a");
- docOne.save();
-
- boolean exceptionThrown = false;
- try {
- docTwo.field("prop1", "a");
- docTwo.save();
- } catch (OIndexException e) {
- exceptionThrown = true;
- }
- Assert.assertTrue(exceptionThrown);
- }
-
- public void testPropertiesCheckUniqueIndexDubKeyIsNullCreate() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
-
- docOne.field("prop1", "a");
- docOne.save();
-
- docTwo.field("prop1", (String)null);
- docTwo.save();
- }
-
- public void testPropertiesCheckUniqueIndexDubKeyIsNullCreateInTx() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
-
- database.begin();
- docOne.field("prop1", "a");
- docOne.save();
-
- docTwo.field("prop1", (String)null);
- docTwo.save();
- database.commit();
- }
-
- public void testPropertiesCheckUniqueIndexInParentDubKeysCreate() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
-
- docOne.field("prop0", "a");
- docOne.save();
-
- boolean exceptionThrown = false;
- try {
- docTwo.field("prop0", "a");
- docTwo.save();
- } catch (OIndexException e) {
- exceptionThrown = true;
- }
- Assert.assertTrue(exceptionThrown);
- }
-
- public void testPropertiesCheckUniqueIndexDubKeysUpdate() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
-
- boolean exceptionThrown = false;
- docOne.field("prop1", "a");
- docOne.save();
-
- docTwo.field("prop1", "b");
- docTwo.save();
-
- try {
- docTwo.field("prop1", "a");
- docTwo.save();
- } catch (OIndexException e) {
- exceptionThrown = true;
- }
- Assert.assertTrue(exceptionThrown);
- }
-
- public void testPropertiesCheckUniqueIndexDubKeyIsNullUpdate() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
-
- docOne.field("prop1", "a");
- docOne.save();
-
- docTwo.field("prop1", "b");
- docTwo.save();
-
- docTwo.field("prop1", (String)null);
- docTwo.save();
- }
-
- public void testPropertiesCheckUniqueIndexDubKeyIsNullUpdateInTX() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
-
- database.begin();
- docOne.field("prop1", "a");
- docOne.save();
-
- docTwo.field("prop1", "b");
- docTwo.save();
-
- docTwo.field("prop1", (String)null);
- docTwo.save();
- database.commit();
- }
-
- public void testPropertiesCheckNonUniqueIndexDubKeys() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- docOne.field("prop2", 1);
- docOne.save();
-
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
- docTwo.field("prop2", 1);
- docTwo.save();
- }
-
- public void testPropertiesCheckUniqueNullKeys() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- docOne.field("prop3", "a");
- docOne.save();
-
- final ODocument docTwo = new ODocument("classIndexManagerTestClass");
- docTwo.field("prop3", "a");
- docTwo.save();
- }
-
- public void testCreateDocumentWithoutClass() {
- final Collection<? extends OIndex<?>> beforeIndexes = database.getMetadata().getIndexManager().getIndexes();
- final Map<String, Long> indexSizeMap = new HashMap<String, Long>();
-
- for (final OIndex<?> index : beforeIndexes)
- indexSizeMap.put(index.getName(), index.getSize());
-
- final ODocument docOne = new ODocument();
- docOne.field("prop1", "a");
- docOne.save();
-
- final ODocument docTwo = new ODocument();
- docTwo.field("prop1", "a");
- docTwo.save();
-
- final Collection<? extends OIndex<?>> afterIndexes = database.getMetadata().getIndexManager().getIndexes();
- for (final OIndex<?> index : afterIndexes)
- Assert.assertEquals(index.getSize(), indexSizeMap.get(index.getName()).longValue());
- }
-
- public void testUpdateDocumentWithoutClass() {
- final Collection<? extends OIndex<?>> beforeIndexes = database.getMetadata().getIndexManager().getIndexes();
- final Map<String, Long> indexSizeMap = new HashMap<String, Long>();
-
- for (final OIndex<?> index : beforeIndexes)
- indexSizeMap.put(index.getName(), index.getSize());
-
- final ODocument docOne = new ODocument();
- docOne.field("prop1", "a");
- docOne.save();
-
- final ODocument docTwo = new ODocument();
- docTwo.field("prop1", "b");
- docTwo.save();
+ private final ODatabaseDocumentTx database;
+
+ @Parameters(value = "url")
+ public ClassIndexManagerTest(final String iURL) {
+ database = new ODatabaseDocumentTx(iURL);
+ }
+
+ @BeforeClass
+ public void beforeClass() {
+ if (database.isClosed())
+ database.open("admin", "admin");
+
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass superClass = schema.createClass("classIndexManagerTestSuperClass");
+ final OProperty propertyZero = superClass.createProperty("prop0", OType.STRING);
+ propertyZero.createIndex(OClass.INDEX_TYPE.UNIQUE);
+
+ final OClass oClass = schema.createClass("classIndexManagerTestClass", superClass);
+ final OProperty propOne = oClass.createProperty("prop1", OType.STRING);
+ propOne.createIndex(OClass.INDEX_TYPE.UNIQUE);
+
+ final OProperty propTwo = oClass.createProperty("prop2", OType.INTEGER);
+ propTwo.createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
+
+ oClass.createProperty("prop3", OType.BOOLEAN);
+
+ final OProperty propFour = oClass.createProperty("prop4", OType.EMBEDDEDLIST, OType.STRING);
+ propFour.createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
+
+ oClass.createProperty("prop5", OType.EMBEDDEDMAP, OType.STRING);
+ oClass.createIndex("classIndexManagerTestIndexByKey", OClass.INDEX_TYPE.NOTUNIQUE, "prop5");
+ oClass.createIndex("classIndexManagerTestIndexByValue", OClass.INDEX_TYPE.NOTUNIQUE, "prop5 by value");
+
+ final OProperty propSix = oClass.createProperty("prop6", OType.EMBEDDEDSET, OType.STRING);
+ propSix.createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
+
+ oClass.createIndex("classIndexManagerComposite", OClass.INDEX_TYPE.UNIQUE, "prop1", "prop2");
+
+ final OClass oClassTwo = schema.createClass("classIndexManagerTestClassTwo");
+ oClassTwo.createProperty("prop1", OType.STRING);
+ oClassTwo.createProperty("prop2", OType.INTEGER);
+
+ final OClass compositeCollectionClass = schema.createClass("classIndexManagerTestCompositeCollectionClass");
+ compositeCollectionClass.createProperty("prop1", OType.STRING);
+ compositeCollectionClass.createProperty("prop2", OType.EMBEDDEDLIST, OType.INTEGER);
+
+ compositeCollectionClass
+ .createIndex("classIndexManagerTestIndexValueAndCollection", OClass.INDEX_TYPE.UNIQUE, "prop1", "prop2");
+
+ schema.save();
+
+ database.close();
+ }
+
+ @BeforeMethod
+ public void beforeMethod() {
+ if (database.isClosed())
+ database.open("admin", "admin");
+ }
+
+ @AfterMethod
+ public void afterMethod() {
+ database.command(new OCommandSQL("delete from classIndexManagerTestClass")).execute();
+ database.command(new OCommandSQL("delete from classIndexManagerTestClassTwo")).execute();
+ database.command(new OCommandSQL("delete from classIndexManagerTestSuperClass")).execute();
+ database.close();
+ }
+
+ @AfterClass
+ public void afterClass() {
+ if (database.isClosed())
+ database.open("admin", "admin");
+ database.command(new OCommandSQL("drop class classIndexManagerTestClass")).execute();
+ database.command(new OCommandSQL("drop class classIndexManagerTestClassTwo")).execute();
+ database.command(new OCommandSQL("drop class classIndexManagerTestSuperClass")).execute();
+ database.getMetadata().getSchema().reload();
+ database.getLevel2Cache().clear();
+ database.close();
+ }
+
+ public void testPropertiesCheckUniqueIndexDubKeysCreate() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+
+ docOne.field("prop1", "a");
+ docOne.save();
+
+ boolean exceptionThrown = false;
+ try {
+ docTwo.field("prop1", "a");
+ docTwo.save();
+ } catch (OIndexException e) {
+ exceptionThrown = true;
+ }
+ Assert.assertTrue(exceptionThrown);
+ }
+
+ public void testPropertiesCheckUniqueIndexDubKeyIsNullCreate() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+
+ docOne.field("prop1", "a");
+ docOne.save();
+
+ docTwo.field("prop1", (String) null);
+ docTwo.save();
+ }
+
+ public void testPropertiesCheckUniqueIndexDubKeyIsNullCreateInTx() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+
+ database.begin();
+ docOne.field("prop1", "a");
+ docOne.save();
+
+ docTwo.field("prop1", (String) null);
+ docTwo.save();
+ database.commit();
+ }
+
+ public void testPropertiesCheckUniqueIndexInParentDubKeysCreate() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+
+ docOne.field("prop0", "a");
+ docOne.save();
+
+ boolean exceptionThrown = false;
+ try {
+ docTwo.field("prop0", "a");
+ docTwo.save();
+ } catch (OIndexException e) {
+ exceptionThrown = true;
+ }
+ Assert.assertTrue(exceptionThrown);
+ }
+
+ public void testPropertiesCheckUniqueIndexDubKeysUpdate() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+
+ boolean exceptionThrown = false;
+ docOne.field("prop1", "a");
+ docOne.save();
+
+ docTwo.field("prop1", "b");
+ docTwo.save();
+
+ try {
+ docTwo.field("prop1", "a");
+ docTwo.save();
+ } catch (OIndexException e) {
+ exceptionThrown = true;
+ }
+ Assert.assertTrue(exceptionThrown);
+ }
+
+ public void testPropertiesCheckUniqueIndexDubKeyIsNullUpdate() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+
+ docOne.field("prop1", "a");
+ docOne.save();
+
+ docTwo.field("prop1", "b");
+ docTwo.save();
+
+ docTwo.field("prop1", (String) null);
+ docTwo.save();
+ }
+
+ public void testPropertiesCheckUniqueIndexDubKeyIsNullUpdateInTX() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+
+ database.begin();
+ docOne.field("prop1", "a");
+ docOne.save();
+
+ docTwo.field("prop1", "b");
+ docTwo.save();
+
+ docTwo.field("prop1", (String) null);
+ docTwo.save();
+ database.commit();
+ }
+
+ public void testPropertiesCheckNonUniqueIndexDubKeys() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ docOne.field("prop2", 1);
+ docOne.save();
+
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+ docTwo.field("prop2", 1);
+ docTwo.save();
+ }
+
+ public void testPropertiesCheckUniqueNullKeys() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ docOne.field("prop3", "a");
+ docOne.save();
+
+ final ODocument docTwo = new ODocument("classIndexManagerTestClass");
+ docTwo.field("prop3", "a");
+ docTwo.save();
+ }
+
+ public void testCreateDocumentWithoutClass() {
+ final Collection<? extends OIndex<?>> beforeIndexes = database.getMetadata().getIndexManager().getIndexes();
+ final Map<String, Long> indexSizeMap = new HashMap<String, Long>();
+
+ for (final OIndex<?> index : beforeIndexes)
+ indexSizeMap.put(index.getName(), index.getSize());
+
+ final ODocument docOne = new ODocument();
+ docOne.field("prop1", "a");
+ docOne.save();
+
+ final ODocument docTwo = new ODocument();
+ docTwo.field("prop1", "a");
+ docTwo.save();
+
+ final Collection<? extends OIndex<?>> afterIndexes = database.getMetadata().getIndexManager().getIndexes();
+ for (final OIndex<?> index : afterIndexes)
+ Assert.assertEquals(index.getSize(), indexSizeMap.get(index.getName()).longValue());
+ }
+
+ public void testUpdateDocumentWithoutClass() {
+ final Collection<? extends OIndex<?>> beforeIndexes = database.getMetadata().getIndexManager().getIndexes();
+ final Map<String, Long> indexSizeMap = new HashMap<String, Long>();
+
+ for (final OIndex<?> index : beforeIndexes)
+ indexSizeMap.put(index.getName(), index.getSize());
+
+ final ODocument docOne = new ODocument();
+ docOne.field("prop1", "a");
+ docOne.save();
+
+ final ODocument docTwo = new ODocument();
+ docTwo.field("prop1", "b");
+ docTwo.save();
- docOne.field("prop1", "a");
- docOne.save();
+ docOne.field("prop1", "a");
+ docOne.save();
- final Collection<? extends OIndex<?>> afterIndexes = database.getMetadata().getIndexManager().getIndexes();
- for (final OIndex<?> index : afterIndexes)
- Assert.assertEquals(index.getSize(), indexSizeMap.get(index.getName()).longValue());
- }
+ final Collection<? extends OIndex<?>> afterIndexes = database.getMetadata().getIndexManager().getIndexes();
+ for (final OIndex<?> index : afterIndexes)
+ Assert.assertEquals(index.getSize(), indexSizeMap.get(index.getName()).longValue());
+ }
- public void testDeleteDocumentWithoutClass() {
- final ODocument docOne = new ODocument();
- docOne.field("prop1", "a");
- docOne.save();
+ public void testDeleteDocumentWithoutClass() {
+ final ODocument docOne = new ODocument();
+ docOne.field("prop1", "a");
+ docOne.save();
- docOne.delete();
- }
+ docOne.delete();
+ }
- public void testDeleteModifiedDocumentWithoutClass() {
- final ODocument docOne = new ODocument();
- docOne.field("prop1", "a");
- docOne.save();
+ public void testDeleteModifiedDocumentWithoutClass() {
+ final ODocument docOne = new ODocument();
+ docOne.field("prop1", "a");
+ docOne.save();
- docOne.field("prop1", "b");
+ docOne.field("prop1", "b");
- docOne.delete();
- }
-
- public void testDocumentUpdateWithoutDirtyFields() {
- final ODocument docOne = new ODocument("classIndexManagerTestClass");
- docOne.field("prop1", "a");
- docOne.save();
+ docOne.delete();
+ }
+
+ public void testDocumentUpdateWithoutDirtyFields() {
+ final ODocument docOne = new ODocument("classIndexManagerTestClass");
+ docOne.field("prop1", "a");
+ docOne.save();
- docOne.setDirty();
- docOne.save();
- }
+ docOne.setDirty();
+ docOne.save();
+ }
- public void testCreateDocumentIndexRecordAdded() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop0", "x");
- doc.field("prop1", "a");
- doc.field("prop2", 1);
-
- doc.save();
+ public void testCreateDocumentIndexRecordAdded() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop0", "x");
+ doc.field("prop1", "a");
+ doc.field("prop2", 1);
+
+ doc.save();
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
- final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- Assert.assertNotNull(propOneIndex.get("a"));
- Assert.assertEquals(propOneIndex.getSize(), 1);
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ Assert.assertNotNull(propOneIndex.get("a"));
+ Assert.assertEquals(propOneIndex.getSize(), 1);
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
- final OIndexDefinition compositeIndexDefinition = compositeIndex.getDefinition();
- Assert.assertNotNull(compositeIndex.get(compositeIndexDefinition.createValue("a", 1)));
- Assert.assertEquals(compositeIndex.getSize(), 1);
+ final OIndexDefinition compositeIndexDefinition = compositeIndex.getDefinition();
+ Assert.assertNotNull(compositeIndex.get(compositeIndexDefinition.createValue("a", 1)));
+ Assert.assertEquals(compositeIndex.getSize(), 1);
- final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
- Assert.assertNotNull(propZeroIndex.get("x"));
- Assert.assertEquals(propZeroIndex.getSize(), 1);
- }
+ final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
+ Assert.assertNotNull(propZeroIndex.get("x"));
+ Assert.assertEquals(propZeroIndex.getSize(), 1);
+ }
- public void testUpdateDocumentIndexRecordRemoved() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop0", "x");
- doc.field("prop1", "a");
- doc.field("prop2", 1);
+ public void testUpdateDocumentIndexRecordRemoved() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop0", "x");
+ doc.field("prop1", "a");
+ doc.field("prop2", 1);
- doc.save();
+ doc.save();
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
- final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 1);
- Assert.assertEquals(propZeroIndex.getSize(), 1);
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 1);
+ Assert.assertEquals(propZeroIndex.getSize(), 1);
- doc.removeField("prop2");
- doc.removeField("prop0");
- doc.save();
+ doc.removeField("prop2");
+ doc.removeField("prop0");
+ doc.save();
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 0);
- Assert.assertEquals(propZeroIndex.getSize(), 0);
- }
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
+ Assert.assertEquals(propZeroIndex.getSize(), 0);
+ }
- public void testUpdateDocumentNullKeyIndexRecordRemoved() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
+ public void testUpdateDocumentNullKeyIndexRecordRemoved() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop0", "x");
- doc.field("prop1", "a");
- doc.field("prop2", 1);
+ doc.field("prop0", "x");
+ doc.field("prop1", "a");
+ doc.field("prop2", 1);
- doc.save();
+ doc.save();
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
- final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 1);
- Assert.assertEquals(propZeroIndex.getSize(), 1);
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 1);
+ Assert.assertEquals(propZeroIndex.getSize(), 1);
- doc.field("prop2", (Object) null);
- doc.field("prop0", (Object) null);
- doc.save();
+ doc.field("prop2", (Object) null);
+ doc.field("prop0", (Object) null);
+ doc.save();
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 0);
- Assert.assertEquals(propZeroIndex.getSize(), 0);
- }
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
+ Assert.assertEquals(propZeroIndex.getSize(), 0);
+ }
- public void testUpdateDocumentIndexRecordUpdated() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop0", "x");
- doc.field("prop1", "a");
- doc.field("prop2", 1);
+ public void testUpdateDocumentIndexRecordUpdated() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop0", "x");
+ doc.field("prop1", "a");
+ doc.field("prop2", 1);
- doc.save();
+ doc.save();
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
- final OIndexDefinition compositeIndexDefinition = compositeIndex.getDefinition();
+ final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ final OIndexDefinition compositeIndexDefinition = compositeIndex.getDefinition();
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 1);
- Assert.assertEquals(propZeroIndex.getSize(), 1);
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 1);
+ Assert.assertEquals(propZeroIndex.getSize(), 1);
- doc.field("prop2", 2);
- doc.field("prop0", "y");
- doc.save();
+ doc.field("prop2", 2);
+ doc.field("prop0", "y");
+ doc.save();
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 1);
- Assert.assertEquals(propZeroIndex.getSize(), 1);
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 1);
+ Assert.assertEquals(propZeroIndex.getSize(), 1);
- Assert.assertNotNull(propZeroIndex.get("y"));
- Assert.assertNotNull(propOneIndex.get("a"));
- Assert.assertNotNull(compositeIndex.get(compositeIndexDefinition.createValue("a", 2)));
- }
+ Assert.assertNotNull(propZeroIndex.get("y"));
+ Assert.assertNotNull(propOneIndex.get("a"));
+ Assert.assertNotNull(compositeIndex.get(compositeIndexDefinition.createValue("a", 2)));
+ }
- public void testUpdateDocumentIndexRecordUpdatedFromNullField() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop1", "a");
- doc.field("prop2", (Object) null);
+ public void testUpdateDocumentIndexRecordUpdatedFromNullField() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop1", "a");
+ doc.field("prop2", (Object) null);
- doc.save();
+ doc.save();
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
- final OIndexDefinition compositeIndexDefinition = compositeIndex.getDefinition();
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ final OIndexDefinition compositeIndexDefinition = compositeIndex.getDefinition();
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 0);
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
- doc.field("prop2", 2);
- doc.save();
+ doc.field("prop2", 2);
+ doc.save();
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 1);
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 1);
- Assert.assertNotNull(propOneIndex.get("a"));
- Assert.assertNotNull(compositeIndex.get(compositeIndexDefinition.createValue("a", 2)));
- }
+ Assert.assertNotNull(propOneIndex.get("a"));
+ Assert.assertNotNull(compositeIndex.get(compositeIndexDefinition.createValue("a", 2)));
+ }
- public void testListUpdate() {
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ public void testListUpdate() {
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- final OIndex<?> propFourIndex = oClass.getClassIndex("classIndexManagerTestClass.prop4");
+ final OIndex<?> propFourIndex = oClass.getClassIndex("classIndexManagerTestClass.prop4");
- Assert.assertEquals(propFourIndex.getSize(), 0);
+ Assert.assertEquals(propFourIndex.getSize(), 0);
- final ODocument doc = new ODocument("classIndexManagerTestClass");
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
- final List<String> listProperty = new ArrayList<String>();
- listProperty.add("value1");
- listProperty.add("value2");
+ final List<String> listProperty = new ArrayList<String>();
+ listProperty.add("value1");
+ listProperty.add("value2");
- doc.field("prop4", listProperty);
- doc.save();
+ doc.field("prop4", listProperty);
+ doc.save();
- Assert.assertEquals(propFourIndex.getSize(), 2);
- Assert.assertNotNull(propFourIndex.get("value1"));
- Assert.assertNotNull(propFourIndex.get("value2"));
+ Assert.assertEquals(propFourIndex.getSize(), 2);
+ Assert.assertNotNull(propFourIndex.get("value1"));
+ Assert.assertNotNull(propFourIndex.get("value2"));
- List<String> trackedList = doc.field("prop4");
- trackedList.set(0, "value3");
+ List<String> trackedList = doc.field("prop4");
+ trackedList.set(0, "value3");
- trackedList.add("value4");
- trackedList.add("value4");
- trackedList.add("value4");
- trackedList.remove("value4");
- trackedList.remove("value2");
- trackedList.add("value5");
+ trackedList.add("value4");
+ trackedList.add("value4");
+ trackedList.add("value4");
+ trackedList.remove("value4");
+ trackedList.remove("value2");
+ trackedList.add("value5");
- doc.save();
+ doc.save();
- Assert.assertEquals(propFourIndex.getSize(), 3);
- Assert.assertNotNull(propFourIndex.get("value3"));
- Assert.assertNotNull(propFourIndex.get("value4"));
- Assert.assertNotNull(propFourIndex.get("value5"));
- }
+ Assert.assertEquals(propFourIndex.getSize(), 3);
+ Assert.assertNotNull(propFourIndex.get("value3"));
+ Assert.assertNotNull(propFourIndex.get("value4"));
+ Assert.assertNotNull(propFourIndex.get("value5"));
+ }
+ public void testMapUpdate() {
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- public void testMapUpdate() {
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ final OIndex<?> propFiveIndexKey = oClass.getClassIndex("classIndexManagerTestIndexByKey");
+ final OIndex<?> propFiveIndexValue = oClass.getClassIndex("classIndexManagerTestIndexByValue");
- final OIndex<?> propFiveIndexKey = oClass.getClassIndex("classIndexManagerTestIndexByKey");
- final OIndex<?> propFiveIndexValue = oClass.getClassIndex("classIndexManagerTestIndexByValue");
+ Assert.assertEquals(propFiveIndexKey.getSize(), 0);
- Assert.assertEquals(propFiveIndexKey.getSize(), 0);
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
- final ODocument doc = new ODocument("classIndexManagerTestClass");
+ final Map<String, String> mapProperty = new HashMap<String, String>();
+ mapProperty.put("key1", "value1");
+ mapProperty.put("key2", "value2");
- final Map<String, String> mapProperty = new HashMap<String, String>();
- mapProperty.put("key1", "value1");
- mapProperty.put("key2", "value2");
+ doc.field("prop5", mapProperty);
+ doc.save();
- doc.field("prop5", mapProperty);
- doc.save();
+ Assert.assertEquals(propFiveIndexKey.getSize(), 2);
+ Assert.assertNotNull(propFiveIndexKey.get("key1"));
+ Assert.assertNotNull(propFiveIndexKey.get("key2"));
- Assert.assertEquals(propFiveIndexKey.getSize(), 2);
- Assert.assertNotNull(propFiveIndexKey.get("key1"));
- Assert.assertNotNull(propFiveIndexKey.get("key2"));
+ Map<String, String> trackedMap = doc.field("prop5");
+ trackedMap.put("key3", "value3");
+ trackedMap.put("key4", "value4");
+ trackedMap.remove("key1");
+ trackedMap.put("key1", "value5");
+ trackedMap.remove("key2");
+ trackedMap.put("key6", "value6");
+ trackedMap.put("key7", "value6");
+ trackedMap.put("key8", "value6");
+ trackedMap.put("key4", "value7");
- Map<String, String> trackedMap = doc.field("prop5");
- trackedMap.put("key3", "value3");
- trackedMap.put("key4", "value4");
- trackedMap.remove("key1");
- trackedMap.put("key1", "value5");
- trackedMap.remove("key2");
- trackedMap.put("key6", "value6");
- trackedMap.put("key7", "value6");
- trackedMap.put("key8", "value6");
- trackedMap.put("key4", "value7");
+ trackedMap.remove("key8");
- trackedMap.remove("key8");
+ doc.save();
+ Assert.assertEquals(propFiveIndexKey.getSize(), 5);
+ Assert.assertNotNull(propFiveIndexKey.get("key1"));
+ Assert.assertNotNull(propFiveIndexKey.get("key3"));
+ Assert.assertNotNull(propFiveIndexKey.get("key4"));
+ Assert.assertNotNull(propFiveIndexKey.get("key6"));
+ Assert.assertNotNull(propFiveIndexKey.get("key7"));
- doc.save();
+ Assert.assertEquals(propFiveIndexValue.getSize(), 4);
+ Assert.assertNotNull(propFiveIndexValue.get("value5"));
+ Assert.assertNotNull(propFiveIndexValue.get("value3"));
+ Assert.assertNotNull(propFiveIndexValue.get("value7"));
+ Assert.assertNotNull(propFiveIndexValue.get("value6"));
- Assert.assertEquals(propFiveIndexKey.getSize(), 5);
- Assert.assertNotNull(propFiveIndexKey.get("key1"));
- Assert.assertNotNull(propFiveIndexKey.get("key3"));
- Assert.assertNotNull(propFiveIndexKey.get("key4"));
- Assert.assertNotNull(propFiveIndexKey.get("key6"));
- Assert.assertNotNull(propFiveIndexKey.get("key7"));
+ }
- Assert.assertEquals(propFiveIndexValue.getSize(), 4);
- Assert.assertNotNull(propFiveIndexValue.get("value5"));
- Assert.assertNotNull(propFiveIndexValue.get("value3"));
- Assert.assertNotNull(propFiveIndexValue.get("value7"));
- Assert.assertNotNull(propFiveIndexValue.get("value6"));
+ public void testSetUpdate() {
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- }
+ final OIndex<?> propSixIndex = oClass.getClassIndex("classIndexManagerTestClass.prop6");
- public void testSetUpdate() {
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ Assert.assertEquals(propSixIndex.getSize(), 0);
- final OIndex<?> propSixIndex = oClass.getClassIndex("classIndexManagerTestClass.prop6");
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
- Assert.assertEquals(propSixIndex.getSize(), 0);
+ final Set<String> setProperty = new HashSet<String>();
+ setProperty.add("value1");
+ setProperty.add("value2");
- final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop6", setProperty);
+ doc.save();
- final Set<String> setProperty = new HashSet<String>();
- setProperty.add("value1");
- setProperty.add("value2");
+ Assert.assertEquals(propSixIndex.getSize(), 2);
+ Assert.assertNotNull(propSixIndex.get("value1"));
+ Assert.assertNotNull(propSixIndex.get("value2"));
- doc.field("prop6", setProperty);
- doc.save();
+ Set<String> trackedSet = doc.field("prop6");
- Assert.assertEquals(propSixIndex.getSize(), 2);
- Assert.assertNotNull(propSixIndex.get("value1"));
- Assert.assertNotNull(propSixIndex.get("value2"));
+ trackedSet.add("value4");
+ trackedSet.add("value4");
+ trackedSet.add("value4");
+ trackedSet.remove("value4");
+ trackedSet.remove("value2");
+ trackedSet.add("value5");
- Set<String> trackedSet = doc.field("prop6");
+ doc.save();
- trackedSet.add("value4");
- trackedSet.add("value4");
- trackedSet.add("value4");
- trackedSet.remove("value4");
- trackedSet.remove("value2");
- trackedSet.add("value5");
+ Assert.assertEquals(propSixIndex.getSize(), 2);
+ Assert.assertNotNull(propSixIndex.get("value1"));
+ Assert.assertNotNull(propSixIndex.get("value5"));
+ }
- doc.save();
+ public void testListDelete() {
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- Assert.assertEquals(propSixIndex.getSize(), 2);
- Assert.assertNotNull(propSixIndex.get("value1"));
- Assert.assertNotNull(propSixIndex.get("value5"));
- }
+ final OIndex<?> propFourIndex = oClass.getClassIndex("classIndexManagerTestClass.prop4");
- public void testListDelete() {
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ Assert.assertEquals(propFourIndex.getSize(), 0);
- final OIndex<?> propFourIndex = oClass.getClassIndex("classIndexManagerTestClass.prop4");
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
- Assert.assertEquals(propFourIndex.getSize(), 0);
+ final List<String> listProperty = new ArrayList<String>();
+ listProperty.add("value1");
+ listProperty.add("value2");
- final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop4", listProperty);
+ doc.save();
- final List<String> listProperty = new ArrayList<String>();
- listProperty.add("value1");
- listProperty.add("value2");
+ Assert.assertEquals(propFourIndex.getSize(), 2);
+ Assert.assertNotNull(propFourIndex.get("value1"));
+ Assert.assertNotNull(propFourIndex.get("value2"));
- doc.field("prop4", listProperty);
- doc.save();
+ List<String> trackedList = doc.field("prop4");
+ trackedList.set(0, "value3");
- Assert.assertEquals(propFourIndex.getSize(), 2);
- Assert.assertNotNull(propFourIndex.get("value1"));
- Assert.assertNotNull(propFourIndex.get("value2"));
+ trackedList.add("value4");
+ trackedList.add("value4");
+ trackedList.add("value4");
+ trackedList.remove("value4");
+ trackedList.remove("value2");
+ trackedList.add("value5");
- List<String> trackedList = doc.field("prop4");
- trackedList.set(0, "value3");
+ doc.save();
- trackedList.add("value4");
- trackedList.add("value4");
- trackedList.add("value4");
- trackedList.remove("value4");
- trackedList.remove("value2");
- trackedList.add("value5");
+ Assert.assertEquals(propFourIndex.getSize(), 3);
+ Assert.assertNotNull(propFourIndex.get("value3"));
+ Assert.assertNotNull(propFourIndex.get("value4"));
+ Assert.assertNotNull(propFourIndex.get("value5"));
- doc.save();
+ trackedList = doc.field("prop4");
+ trackedList.remove("value3");
+ trackedList.remove("value4");
+ trackedList.add("value8");
- Assert.assertEquals(propFourIndex.getSize(), 3);
- Assert.assertNotNull(propFourIndex.get("value3"));
- Assert.assertNotNull(propFourIndex.get("value4"));
- Assert.assertNotNull(propFourIndex.get("value5"));
+ doc.delete();
- trackedList = doc.field("prop4");
- trackedList.remove("value3");
- trackedList.remove("value4");
- trackedList.add("value8");
+ Assert.assertEquals(propFourIndex.getSize(), 0);
+ }
- doc.delete();
+ public void testMapDelete() {
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- Assert.assertEquals(propFourIndex.getSize(), 0);
- }
+ final OIndex<?> propFiveIndexKey = oClass.getClassIndex("classIndexManagerTestIndexByKey");
+ final OIndex<?> propFiveIndexValue = oClass.getClassIndex("classIndexManagerTestIndexByValue");
+ Assert.assertEquals(propFiveIndexKey.getSize(), 0);
- public void testMapDelete() {
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
- final OIndex<?> propFiveIndexKey = oClass.getClassIndex("classIndexManagerTestIndexByKey");
- final OIndex<?> propFiveIndexValue = oClass.getClassIndex("classIndexManagerTestIndexByValue");
+ final Map<String, String> mapProperty = new HashMap<String, String>();
+ mapProperty.put("key1", "value1");
+ mapProperty.put("key2", "value2");
- Assert.assertEquals(propFiveIndexKey.getSize(), 0);
+ doc.field("prop5", mapProperty);
+ doc.save();
- final ODocument doc = new ODocument("classIndexManagerTestClass");
+ Assert.assertEquals(propFiveIndexKey.getSize(), 2);
+ Assert.assertNotNull(propFiveIndexKey.get("key1"));
+ Assert.assertNotNull(propFiveIndexKey.get("key2"));
- final Map<String, String> mapProperty = new HashMap<String, String>();
- mapProperty.put("key1", "value1");
- mapProperty.put("key2", "value2");
+ Map<String, String> trackedMap = doc.field("prop5");
+ trackedMap.put("key3", "value3");
+ trackedMap.put("key4", "value4");
+ trackedMap.remove("key1");
+ trackedMap.put("key1", "value5");
+ trackedMap.remove("key2");
+ trackedMap.put("key6", "value6");
+ trackedMap.put("key7", "value6");
+ trackedMap.put("key8", "value6");
+ trackedMap.put("key4", "value7");
- doc.field("prop5", mapProperty);
- doc.save();
+ trackedMap.remove("key8");
- Assert.assertEquals(propFiveIndexKey.getSize(), 2);
- Assert.assertNotNull(propFiveIndexKey.get("key1"));
- Assert.assertNotNull(propFiveIndexKey.get("key2"));
+ doc.save();
- Map<String, String> trackedMap = doc.field("prop5");
- trackedMap.put("key3", "value3");
- trackedMap.put("key4", "value4");
- trackedMap.remove("key1");
- trackedMap.put("key1", "value5");
- trackedMap.remove("key2");
- trackedMap.put("key6", "value6");
- trackedMap.put("key7", "value6");
- trackedMap.put("key8", "value6");
- trackedMap.put("key4", "value7");
+ Assert.assertEquals(propFiveIndexKey.getSize(), 5);
+ Assert.assertNotNull(propFiveIndexKey.get("key1"));
+ Assert.assertNotNull(propFiveIndexKey.get("key3"));
+ Assert.assertNotNull(propFiveIndexKey.get("key4"));
+ Assert.assertNotNull(propFiveIndexKey.get("key6"));
+ Assert.assertNotNull(propFiveIndexKey.get("key7"));
- trackedMap.remove("key8");
+ Assert.assertEquals(propFiveIndexValue.getSize(), 4);
+ Assert.assertNotNull(propFiveIndexValue.get("value5"));
+ Assert.assertNotNull(propFiveIndexValue.get("value3"));
+ Assert.assertNotNull(propFiveIndexValue.get("value7"));
+ Assert.assertNotNull(propFiveIndexValue.get("value6"));
+ trackedMap = doc.field("prop5");
- doc.save();
+ trackedMap.remove("key1");
+ trackedMap.remove("key3");
+ trackedMap.remove("key4");
+ trackedMap.put("key6", "value10");
+ trackedMap.put("key11", "value11");
- Assert.assertEquals(propFiveIndexKey.getSize(), 5);
- Assert.assertNotNull(propFiveIndexKey.get("key1"));
- Assert.assertNotNull(propFiveIndexKey.get("key3"));
- Assert.assertNotNull(propFiveIndexKey.get("key4"));
- Assert.assertNotNull(propFiveIndexKey.get("key6"));
- Assert.assertNotNull(propFiveIndexKey.get("key7"));
+ doc.delete();
- Assert.assertEquals(propFiveIndexValue.getSize(), 4);
- Assert.assertNotNull(propFiveIndexValue.get("value5"));
- Assert.assertNotNull(propFiveIndexValue.get("value3"));
- Assert.assertNotNull(propFiveIndexValue.get("value7"));
- Assert.assertNotNull(propFiveIndexValue.get("value6"));
+ Assert.assertEquals(propFiveIndexKey.getSize(), 0);
+ Assert.assertEquals(propFiveIndexValue.getSize(), 0);
+ }
- trackedMap = doc.field("prop5");
+ public void testSetDelete() {
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- trackedMap.remove("key1");
- trackedMap.remove("key3");
- trackedMap.remove("key4");
- trackedMap.put("key6", "value10");
- trackedMap.put("key11", "value11");
+ final OIndex<?> propSixIndex = oClass.getClassIndex("classIndexManagerTestClass.prop6");
- doc.delete();
+ Assert.assertEquals(propSixIndex.getSize(), 0);
- Assert.assertEquals(propFiveIndexKey.getSize(), 0);
- Assert.assertEquals(propFiveIndexValue.getSize(), 0);
- }
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
- public void testSetDelete() {
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ final Set<String> setProperty = new HashSet<String>();
+ setProperty.add("value1");
+ setProperty.add("value2");
- final OIndex<?> propSixIndex = oClass.getClassIndex("classIndexManagerTestClass.prop6");
+ doc.field("prop6", setProperty);
+ doc.save();
- Assert.assertEquals(propSixIndex.getSize(), 0);
+ Assert.assertEquals(propSixIndex.getSize(), 2);
+ Assert.assertNotNull(propSixIndex.get("value1"));
+ Assert.assertNotNull(propSixIndex.get("value2"));
- final ODocument doc = new ODocument("classIndexManagerTestClass");
+ Set<String> trackedSet = doc.field("prop6");
- final Set<String> setProperty = new HashSet<String>();
- setProperty.add("value1");
- setProperty.add("value2");
+ trackedSet.add("value4");
+ trackedSet.add("value4");
+ trackedSet.add("value4");
+ trackedSet.remove("value4");
+ trackedSet.remove("value2");
+ trackedSet.add("value5");
- doc.field("prop6", setProperty);
- doc.save();
+ doc.save();
- Assert.assertEquals(propSixIndex.getSize(), 2);
- Assert.assertNotNull(propSixIndex.get("value1"));
- Assert.assertNotNull(propSixIndex.get("value2"));
+ Assert.assertEquals(propSixIndex.getSize(), 2);
+ Assert.assertNotNull(propSixIndex.get("value1"));
+ Assert.assertNotNull(propSixIndex.get("value5"));
- Set<String> trackedSet = doc.field("prop6");
+ trackedSet = doc.field("prop6");
+ trackedSet.remove("value1");
+ trackedSet.add("value6");
- trackedSet.add("value4");
- trackedSet.add("value4");
- trackedSet.add("value4");
- trackedSet.remove("value4");
- trackedSet.remove("value2");
- trackedSet.add("value5");
+ doc.delete();
- doc.save();
+ Assert.assertEquals(propSixIndex.getSize(), 0);
+ }
- Assert.assertEquals(propSixIndex.getSize(), 2);
- Assert.assertNotNull(propSixIndex.get("value1"));
- Assert.assertNotNull(propSixIndex.get("value5"));
+ public void testDeleteDocumentIndexRecordDeleted() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop0", "x");
+ doc.field("prop1", "a");
+ doc.field("prop2", 1);
- trackedSet = doc.field("prop6");
- trackedSet.remove("value1");
- trackedSet.add("value6");
+ doc.save();
- doc.delete();
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- Assert.assertEquals(propSixIndex.getSize(), 0);
- }
+ final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ Assert.assertEquals(propZeroIndex.getSize(), 1);
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 1);
- public void testDeleteDocumentIndexRecordDeleted() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop0", "x");
- doc.field("prop1", "a");
- doc.field("prop2", 1);
+ doc.delete();
- doc.save();
+ Assert.assertEquals(propZeroIndex.getSize(), 0);
+ Assert.assertEquals(propOneIndex.getSize(), 0);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
+ }
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ public void testDeleteUpdatedDocumentIndexRecordDeleted() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop0", "x");
+ doc.field("prop1", "a");
+ doc.field("prop2", 1);
- final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ doc.save();
- Assert.assertEquals(propZeroIndex.getSize(), 1);
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 1);
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- doc.delete();
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
- Assert.assertEquals(propZeroIndex.getSize(), 0);
- Assert.assertEquals(propOneIndex.getSize(), 0);
- Assert.assertEquals(compositeIndex.getSize(), 0);
- }
+ final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
+ Assert.assertEquals(propZeroIndex.getSize(), 1);
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 1);
- public void testDeleteUpdatedDocumentIndexRecordDeleted() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop0", "x");
- doc.field("prop1", "a");
- doc.field("prop2", 1);
+ doc.field("prop2", 2);
+ doc.field("prop0", "y");
- doc.save();
+ doc.delete();
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oSuperClass = schema.getClass("classIndexManagerTestSuperClass");
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ Assert.assertEquals(propZeroIndex.getSize(), 0);
+ Assert.assertEquals(propOneIndex.getSize(), 0);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
+ }
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ public void testDeleteUpdatedDocumentNullFieldIndexRecordDeleted() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop1", "a");
+ doc.field("prop2", (Object) null);
- final OIndex<?> propZeroIndex = oSuperClass.getClassIndex("classIndexManagerTestSuperClass.prop0");
- Assert.assertEquals(propZeroIndex.getSize(), 1);
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 1);
+ doc.save();
- doc.field("prop2", 2);
- doc.field("prop0", "y");
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- doc.delete();
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
- Assert.assertEquals(propZeroIndex.getSize(), 0);
- Assert.assertEquals(propOneIndex.getSize(), 0);
- Assert.assertEquals(compositeIndex.getSize(), 0);
- }
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
- public void testDeleteUpdatedDocumentNullFieldIndexRecordDeleted() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop1", "a");
- doc.field("prop2", (Object) null);
+ doc.delete();
- doc.save();
+ Assert.assertEquals(propOneIndex.getSize(), 0);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
+ }
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ public void testDeleteUpdatedDocumentOrigNullFieldIndexRecordDeleted() {
+ final ODocument doc = new ODocument("classIndexManagerTestClass");
+ doc.field("prop1", "a");
+ doc.field("prop2", (Object) null);
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ doc.save();
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 0);
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- doc.delete();
+ final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
+ final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
- Assert.assertEquals(propOneIndex.getSize(), 0);
- Assert.assertEquals(compositeIndex.getSize(), 0);
- }
+ Assert.assertEquals(propOneIndex.getSize(), 1);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
- public void testDeleteUpdatedDocumentOrigNullFieldIndexRecordDeleted() {
- final ODocument doc = new ODocument("classIndexManagerTestClass");
- doc.field("prop1", "a");
- doc.field("prop2", (Object) null);
+ doc.field("prop2", 2);
- doc.save();
+ doc.delete();
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ Assert.assertEquals(propOneIndex.getSize(), 0);
+ Assert.assertEquals(compositeIndex.getSize(), 0);
+ }
- final OIndex<?> propOneIndex = oClass.getClassIndex("classIndexManagerTestClass.prop1");
- final OIndex<?> compositeIndex = oClass.getClassIndex("classIndexManagerComposite");
+ public void testNoClassIndexesUpdate() {
+ final ODocument doc = new ODocument("classIndexManagerTestClassTwo");
+ doc.field("prop1", "a");
+ doc.save();
- Assert.assertEquals(propOneIndex.getSize(), 1);
- Assert.assertEquals(compositeIndex.getSize(), 0);
+ doc.field("prop1", "b");
+ doc.save();
- doc.field("prop2", 2);
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.getClass("classIndexManagerTestClass");
- doc.delete();
+ final Collection<OIndex<?>> indexes = oClass.getIndexes();
+ for (final OIndex<?> index : indexes) {
+ Assert.assertEquals(index.getSize(), 0);
+ }
+ }
- Assert.assertEquals(propOneIndex.getSize(), 0);
- Assert.assertEquals(compositeIndex.getSize(), 0);
- }
+ public void testNoClassIndexesDelete() {
+ final ODocument doc = new ODocument("classIndexManagerTestClassTwo");
+ doc.field("prop1", "a");
+ doc.save();
- public void testNoClassIndexesUpdate() {
- final ODocument doc = new ODocument("classIndexManagerTestClassTwo");
- doc.field("prop1", "a");
- doc.save();
+ doc.delete();
+ }
- doc.field("prop1", "b");
- doc.save();
+ public void testCollectionCompositeCreation() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.getClass("classIndexManagerTestClass");
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
- final Collection<OIndex<?>> indexes = oClass.getIndexes();
- for (final OIndex<?> index : indexes) {
- Assert.assertEquals(index.getSize(), 0);
- }
- }
+ doc.save();
- public void testNoClassIndexesDelete() {
- final ODocument doc = new ODocument("classIndexManagerTestClassTwo");
- doc.field("prop1", "a");
- doc.save();
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ Assert.assertEquals(index.get(new OCompositeKey("test1", 1)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test1", 2)), doc.getIdentity());
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeNullSimpleFieldCreation() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", (Object) null);
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 0);
+
+ doc.delete();
+ }
+
+ public void testCollectionCompositeNullCollectionFieldCreation() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", (Object) null);
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 0);
+
+ doc.delete();
+ }
+
+ public void testCollectionCompositeUpdateSimpleField() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop1", "test2");
+
+ doc.save();
+
+ Assert.assertEquals(index.get(new OCompositeKey("test2", 1)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test2", 2)), doc.getIdentity());
+
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeUpdateCollectionWasAssigned() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop2", Arrays.asList(1, 3));
+
+ doc.save();
+
+ Assert.assertEquals(index.get(new OCompositeKey("test1", 1)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test1", 3)), doc.getIdentity());
+
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeUpdateCollectionWasChanged() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ List<Integer> docList = doc.field("prop2");
+ docList.add(3);
+ docList.add(4);
+ docList.add(5);
+
+ docList.remove(0);
+
+ doc.save();
+
+ Assert.assertEquals(index.get(new OCompositeKey("test1", 2)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test1", 3)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test1", 4)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test1", 5)), doc.getIdentity());
+
+ Assert.assertEquals(index.getSize(), 4);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeUpdateCollectionWasChangedSimpleFieldWasAssigned() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ List<Integer> docList = doc.field("prop2");
+ docList.add(3);
+ docList.add(4);
+ docList.add(5);
+
+ docList.remove(0);
+
+ doc.field("prop1", "test2");
+
+ doc.save();
+
+ Assert.assertEquals(index.getSize(), 4);
+
+ Assert.assertEquals(index.get(new OCompositeKey("test2", 2)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test2", 3)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test2", 4)), doc.getIdentity());
+ Assert.assertEquals(index.get(new OCompositeKey("test2", 5)), doc.getIdentity());
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeUpdateSimpleFieldNull() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop1", (Object) null);
+
+ doc.save();
+
+ Assert.assertEquals(index.getSize(), 0);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeUpdateCollectionWasAssignedNull() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop2", (Object) null);
+
+ doc.save();
+
+ Assert.assertEquals(index.getSize(), 0);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeUpdateBothAssignedNull() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop2", (Object) null);
+ doc.field("prop1", (Object) null);
+
+ doc.save();
+
+ Assert.assertEquals(index.getSize(), 0);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeUpdateCollectionWasChangedSimpleFieldWasAssignedNull() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ List<Integer> docList = doc.field("prop2");
+ docList.add(3);
+ docList.add(4);
+ docList.add(5);
+
+ docList.remove(0);
+
+ doc.field("prop1", (Object) null);
+
+ doc.save();
+
+ Assert.assertEquals(index.getSize(), 0);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteSimpleFieldAssigend() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop1", "test2");
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteCollectionFieldAssigend() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop2", Arrays.asList(1, 3));
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteCollectionFieldChanged() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ List<Integer> docList = doc.field("prop2");
+ docList.add(3);
+ docList.add(4);
+
+ docList.remove(1);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteBothCollectionSimpleFieldChanged() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ List<Integer> docList = doc.field("prop2");
+ docList.add(3);
+ docList.add(4);
+
+ docList.remove(1);
+
+ doc.field("prop1", "test2");
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteBothCollectionSimpleFieldAssigend() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop2", Arrays.asList(1, 3));
+ doc.field("prop1", "test2");
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteSimpleFieldNull() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop1", (Object) null);
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteCollectionFieldNull() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop2", (Object) null);
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteBothSimpleCollectionFieldNull() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ doc.field("prop2", (Object) null);
+ doc.field("prop1", (Object) null);
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
+
+ public void testCollectionCompositeDeleteCollectionFieldChangedSimpleFieldNull() {
+ final ODocument doc = new ODocument("classIndexManagerTestCompositeCollectionClass");
+
+ doc.field("prop1", "test1");
+ doc.field("prop2", Arrays.asList(1, 2));
+
+ doc.save();
+
+ final OIndex<?> index = database.getMetadata().getIndexManager().getIndex("classIndexManagerTestIndexValueAndCollection");
+ Assert.assertEquals(index.getSize(), 2);
+
+ List<Integer> docList = doc.field("prop2");
+ docList.add(3);
+ docList.add(4);
+
+ docList.remove(1);
+
+ doc.field("prop1", (Object) null);
+
+ doc.delete();
+
+ Assert.assertEquals(index.getSize(), 0);
+ }
- doc.delete();
- }
}
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ClassIndexTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ClassIndexTest.java
index 95ddf4feb9e..49edf9e8388 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ClassIndexTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/ClassIndexTest.java
@@ -1,13 +1,10 @@
package com.orientechnologies.orient.test.database.auto;
-import com.orientechnologies.common.listener.OProgressListener;
-import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
-import com.orientechnologies.orient.core.index.*;
-import com.orientechnologies.orient.core.metadata.schema.OClass;
-import com.orientechnologies.orient.core.metadata.schema.OSchema;
-import com.orientechnologies.orient.core.metadata.schema.OType;
-import com.orientechnologies.orient.core.sql.OCommandSQL;
-import org.testng.annotations.*;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
@@ -15,82 +12,108 @@
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.testng.Assert.*;
-import static org.testng.Assert.assertEquals;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Parameters;
+import org.testng.annotations.Test;
-@Test(groups = {"index"})
-public class ClassIndexTest
-{
+import com.orientechnologies.common.listener.OProgressListener;
+import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
+import com.orientechnologies.orient.core.index.OCompositeIndexDefinition;
+import com.orientechnologies.orient.core.index.OIndex;
+import com.orientechnologies.orient.core.index.OIndexDefinition;
+import com.orientechnologies.orient.core.index.OIndexException;
+import com.orientechnologies.orient.core.index.OPropertyIndexDefinition;
+import com.orientechnologies.orient.core.index.OPropertyListIndexDefinition;
+import com.orientechnologies.orient.core.index.OPropertyMapIndexDefinition;
+import com.orientechnologies.orient.core.metadata.schema.OClass;
+import com.orientechnologies.orient.core.metadata.schema.OSchema;
+import com.orientechnologies.orient.core.metadata.schema.OType;
+import com.orientechnologies.orient.core.sql.OCommandSQL;
+
+@Test(groups = { "index" })
+public class ClassIndexTest {
private final ODatabaseDocumentTx database;
- private OClass oClass;
- private OClass oSuperClass;
+ private OClass oClass;
+ private OClass oSuperClass;
@Parameters(value = "url")
- public ClassIndexTest( final String iURL )
- {
- database = new ODatabaseDocumentTx( iURL );
+ public ClassIndexTest(final String iURL) {
+ database = new ODatabaseDocumentTx(iURL);
}
@BeforeClass
- public void beforeClass()
- {
- if ( database.isClosed() ) {
- database.open( "admin", "admin" );
+ public void beforeClass() {
+ if (database.isClosed()) {
+ database.open("admin", "admin");
}
final OSchema schema = database.getMetadata().getSchema();
- oClass = schema.createClass( "ClassIndexTestClass" );
- oSuperClass = schema.createClass( "ClassIndexTestSuperClass" );
+ oClass = schema.createClass("ClassIndexTestClass");
+ oSuperClass = schema.createClass("ClassIndexTestSuperClass");
+
+ oClass.createProperty("fOne", OType.INTEGER);
+ oClass.createProperty("fTwo", OType.STRING);
+ oClass.createProperty("fThree", OType.BOOLEAN);
+ oClass.createProperty("fFour", OType.INTEGER);
+
+ oClass.createProperty("fSix", OType.STRING);
+ oClass.createProperty("fSeven", OType.STRING);
+
+ oClass.createProperty("fEight", OType.INTEGER);
+ oClass.createProperty("fTen", OType.INTEGER);
+ oClass.createProperty("fEleven", OType.INTEGER);
+ oClass.createProperty("fTwelve", OType.INTEGER);
+ oClass.createProperty("fThirteen", OType.INTEGER);
+ oClass.createProperty("fFourteen", OType.INTEGER);
+ oClass.createProperty("fFifteen", OType.INTEGER);
+ oClass.createProperty("fEmbeddedMap", OType.EMBEDDEDMAP, OType.INTEGER);
+ oClass.createProperty("fEmbeddedMapWithoutLinkedType", OType.EMBEDDEDMAP);
+ oClass.createProperty("fLinkMap", OType.LINKMAP);
- oClass.createProperty( "fOne", OType.INTEGER );
- oClass.createProperty( "fTwo", OType.STRING );
- oClass.createProperty( "fThree", OType.BOOLEAN );
- oClass.createProperty( "fFour", OType.INTEGER );
+ oClass.createProperty("fLinkList", OType.LINKLIST);
+ oClass.createProperty("fEmbeddedList", OType.EMBEDDEDLIST, OType.INTEGER);
- oClass.createProperty( "fSix", OType.STRING );
- oClass.createProperty( "fSeven", OType.STRING );
- oClass.createProperty( "fEmbeddedMap", OType.EMBEDDEDMAP, OType.INTEGER );
- oClass.createProperty( "fEmbeddedMapWithoutLinkedType", OType.EMBEDDEDMAP );
- oClass.createProperty( "fLinkMap", OType.LINKMAP );
+ oClass.createProperty("fEmbeddedSet", OType.EMBEDDEDSET, OType.INTEGER);
+ oClass.createProperty("fLinkSet", OType.LINKSET);
- oSuperClass.createProperty( "fNine", OType.INTEGER );
- oClass.setSuperClass( oSuperClass );
+ oSuperClass.createProperty("fNine", OType.INTEGER);
+ oClass.setSuperClass(oSuperClass);
schema.save();
database.close();
}
@BeforeMethod
- public void beforeMethod()
- {
- database.open( "admin", "admin" );
+ public void beforeMethod() {
+ database.open("admin", "admin");
}
@AfterMethod
- public void afterMethod()
- {
+ public void afterMethod() {
database.close();
}
@AfterClass
- public void afterClass()
- {
- if ( database.isClosed() ) {
- database.open( "admin", "admin" );
+ public void afterClass() {
+ if (database.isClosed()) {
+ database.open("admin", "admin");
}
- database.command( new OCommandSQL( "delete from ClassIndexTestClass" ) ).execute();
- database.command( new OCommandSQL( "delete from ClassIndexTestSuperClass" ) ).execute();
- database.command( new OCommandSQL( "delete from ClassIndexInTest" ) ).execute();
+ database.command(new OCommandSQL("delete from ClassIndexTestClass")).execute();
+ database.command(new OCommandSQL("delete from ClassIndexTestSuperClass")).execute();
+ database.command(new OCommandSQL("delete from ClassIndexInTest")).execute();
- database.command( new OCommandSQL( "drop class ClassIndexInTest" ) ).execute();
- database.command( new OCommandSQL( "drop class ClassIndexTestClass" ) ).execute();
+ database.command(new OCommandSQL("drop class ClassIndexInTest")).execute();
+ database.command(new OCommandSQL("drop class ClassIndexTestClass")).execute();
database.getMetadata().getSchema().reload();
- database.command( new OCommandSQL( "drop class ClassIndexTestSuperClass" ) ).execute();
+ database.command(new OCommandSQL("drop class ClassIndexTestSuperClass")).execute();
database.getMetadata().getSchema().reload();
database.getMetadata().getIndexManager().reload();
@@ -99,978 +122,1153 @@ public void afterClass()
}
@Test
- public void testCreateOnePropertyIndexTest()
- {
- final OIndex result = oClass.createIndex( "ClassIndexTestPropertyOne", OClass.INDEX_TYPE.UNIQUE, "fOne" );
+ public void testCreateOnePropertyIndexTest() {
+ final OIndex result = oClass.createIndex("ClassIndexTestPropertyOne", OClass.INDEX_TYPE.UNIQUE, "fOne");
- assertEquals( result.getName(), "ClassIndexTestPropertyOne" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestPropertyOne" ).getName(), result.getName() );
- assertEquals(
- database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestPropertyOne" ).getName(),
- result.getName() );
+ assertEquals(result.getName(), "ClassIndexTestPropertyOne");
+ assertEquals(oClass.getClassIndex("ClassIndexTestPropertyOne").getName(), result.getName());
+ assertEquals(database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestPropertyOne")
+ .getName(), result.getName());
}
- @Test
- public void testCreateOnePropertyIndexInvalidName()
- {
- try {
- oClass.createIndex( "ClassIndex:TestPropertyOne", OClass.INDEX_TYPE.UNIQUE, "fOne" );
- fail();
- } catch (Exception e) {
- if(e.getCause() != null)
- e = (Exception)e.getCause();
+ @Test
+ public void testCreateOnePropertyIndexInvalidName() {
+ try {
+ oClass.createIndex("ClassIndex:TestPropertyOne", OClass.INDEX_TYPE.UNIQUE, "fOne");
+ fail();
+ } catch (Exception e) {
+ if (e.getCause() != null)
+ e = (Exception) e.getCause();
- assertTrue(e instanceof IllegalArgumentException);
- }
- }
+ assertTrue(e instanceof IllegalArgumentException);
+ }
+ }
- @Test
- public void createCompositeIndexTestWithoutListener()
- {
- final OIndex result = oClass.createIndex( "ClassIndexTestCompositeOne", OClass.INDEX_TYPE.UNIQUE, "fOne", "fTwo" );
+ @Test
+ public void createCompositeIndexTestWithoutListener() {
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeOne", OClass.INDEX_TYPE.UNIQUE, "fOne", "fTwo");
- assertEquals( result.getName(), "ClassIndexTestCompositeOne" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestCompositeOne" ).getName(), result.getName() );
- assertEquals( database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestCompositeOne" ).getName(),
- result.getName() );
+ assertEquals(result.getName(), "ClassIndexTestCompositeOne");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeOne").getName(), result.getName());
+ assertEquals(database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeOne")
+ .getName(), result.getName());
}
@Test
- public void createCompositeIndexTestWithListener()
- {
- final AtomicInteger atomicInteger = new AtomicInteger( 0 );
- final OProgressListener progressListener = new OProgressListener()
- {
- public void onBegin( final Object iTask, final long iTotal )
- {
+ public void createCompositeIndexTestWithListener() {
+ final AtomicInteger atomicInteger = new AtomicInteger(0);
+ final OProgressListener progressListener = new OProgressListener() {
+ public void onBegin(final Object iTask, final long iTotal) {
atomicInteger.incrementAndGet();
}
- public boolean onProgress( final Object iTask, final long iCounter, final float iPercent )
- {
+ public boolean onProgress(final Object iTask, final long iCounter, final float iPercent) {
return true;
}
- public void onCompletition( final Object iTask, final boolean iSucceed )
- {
+ public void onCompletition(final Object iTask, final boolean iSucceed) {
atomicInteger.incrementAndGet();
}
};
- final OIndex result = oClass.createIndex( "ClassIndexTestCompositeTwo", OClass.INDEX_TYPE.UNIQUE,
- progressListener, "fOne", "fTwo", "fThree" );
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeTwo", OClass.INDEX_TYPE.UNIQUE, progressListener, "fOne",
+ "fTwo", "fThree");
+
+ assertEquals(result.getName(), "ClassIndexTestCompositeTwo");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeTwo").getName(), result.getName());
+ assertEquals(database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeTwo")
+ .getName(), result.getName());
+ assertEquals(atomicInteger.get(), 2);
+ }
+
+ @Test
+ public void testCreateOnePropertyEmbeddedMapIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestPropertyEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap");
+
+ assertEquals(result.getName(), "ClassIndexTestPropertyEmbeddedMap");
+ assertEquals(oClass.getClassIndex("ClassIndexTestPropertyEmbeddedMap").getName(), result.getName());
+ assertEquals(database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestPropertyEmbeddedMap")
+ .getName(), result.getName());
+
+ final OIndexDefinition indexDefinition = result.getDefinition();
+
+ assertTrue(indexDefinition instanceof OPropertyMapIndexDefinition);
+ assertEquals(indexDefinition.getFields().get(0), "fEmbeddedMap");
+ assertEquals(indexDefinition.getTypes()[0], OType.STRING);
+ assertEquals(((OPropertyMapIndexDefinition) indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.KEY);
+ }
+
+ @Test
+ public void testCreateCompositeEmbeddedMapIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fFifteen",
+ "fEmbeddedMap");
+
+ assertEquals(result.getName(), "ClassIndexTestCompositeEmbeddedMap");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeEmbeddedMap").getName(), result.getName());
+ assertEquals(database.getMetadata().getIndexManager()
+ .getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeEmbeddedMap").getName(), result.getName());
- assertEquals( result.getName(), "ClassIndexTestCompositeTwo" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestCompositeTwo" ).getName(), result.getName() );
- assertEquals( database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestCompositeTwo" ).getName(),
- result.getName() );
- assertEquals( atomicInteger.get(), 2 );
+ final OIndexDefinition indexDefinition = result.getDefinition();
+
+ assertTrue(indexDefinition instanceof OCompositeIndexDefinition);
+ assertEquals(indexDefinition.getFields().toArray(), new String[] { "fFifteen", "fEmbeddedMap" });
+
+ assertEquals(indexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.STRING });
+ assertEquals(indexDefinition.getParamCount(), 2);
}
@Test
- public void testCreateOnePropertyEmbeddedMapIndex()
- {
- final OIndex result = oClass.createIndex( "ClassIndexTestPropertyEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap" );
+ public void testCreateCompositeEmbeddedMapByKeyIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeEmbeddedMapByKey", OClass.INDEX_TYPE.UNIQUE, "fEight",
+ "fEmbeddedMap");
- assertEquals( result.getName(), "ClassIndexTestPropertyEmbeddedMap" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestPropertyEmbeddedMap" ).getName(), result.getName() );
+ assertEquals(result.getName(), "ClassIndexTestCompositeEmbeddedMapByKey");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeEmbeddedMapByKey").getName(), result.getName());
assertEquals(
- database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestPropertyEmbeddedMap" ).getName(),
- result.getName() );
+ database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeEmbeddedMapByKey")
+ .getName(), result.getName());
final OIndexDefinition indexDefinition = result.getDefinition();
- assertTrue( indexDefinition instanceof OPropertyMapIndexDefinition );
- assertEquals( indexDefinition.getFields().get( 0 ), "fEmbeddedMap" );
- assertEquals( indexDefinition.getTypes()[0], OType.STRING );
- assertEquals(((OPropertyMapIndexDefinition)indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.KEY );
+ assertTrue(indexDefinition instanceof OCompositeIndexDefinition);
+ assertEquals(indexDefinition.getFields().toArray(), new String[] { "fEight", "fEmbeddedMap" });
+
+ assertEquals(indexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.STRING });
+ assertEquals(indexDefinition.getParamCount(), 2);
}
@Test
- public void testCreateOnePropertyLinkedMapIndex()
- {
- final OIndex result = oClass.createIndex( "ClassIndexTestPropertyLinkedMap", OClass.INDEX_TYPE.UNIQUE, "fLinkMap" );
+ public void testCreateCompositeEmbeddedMapByValueIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeEmbeddedMapByValue", OClass.INDEX_TYPE.UNIQUE, "fTen",
+ "fEmbeddedMap by value");
- assertEquals( result.getName(), "ClassIndexTestPropertyLinkedMap" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestPropertyLinkedMap" ).getName(), result.getName() );
+ assertEquals(result.getName(), "ClassIndexTestCompositeEmbeddedMapByValue");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeEmbeddedMapByValue").getName(), result.getName());
assertEquals(
- database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestPropertyLinkedMap" ).getName(),
- result.getName() );
+ database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeEmbeddedMapByValue")
+ .getName(), result.getName());
final OIndexDefinition indexDefinition = result.getDefinition();
- assertTrue( indexDefinition instanceof OPropertyMapIndexDefinition );
- assertEquals( indexDefinition.getFields().get( 0 ), "fLinkMap" );
- assertEquals( indexDefinition.getTypes()[0], OType.STRING );
- assertEquals(((OPropertyMapIndexDefinition)indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.KEY );
+ assertTrue(indexDefinition instanceof OCompositeIndexDefinition);
+ assertEquals(indexDefinition.getFields().toArray(), new String[] { "fTen", "fEmbeddedMap" });
+
+ assertEquals(indexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.INTEGER });
+ assertEquals(indexDefinition.getParamCount(), 2);
}
@Test
- public void testCreateOnePropertyLinkMapByKeyIndex()
- {
- final OIndex result = oClass.createIndex( "ClassIndexTestPropertyLinkedMap", OClass.INDEX_TYPE.UNIQUE, "fLinkMap by key" );
+ public void testCreateCompositeLinkMapByValueIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeLinkMapByValue", OClass.INDEX_TYPE.UNIQUE, "fEleven",
+ "fLinkMap by value");
- assertEquals( result.getName(), "ClassIndexTestPropertyLinkedMap" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestPropertyLinkedMap" ).getName(), result.getName() );
+ assertEquals(result.getName(), "ClassIndexTestCompositeLinkMapByValue");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeLinkMapByValue").getName(), result.getName());
assertEquals(
- database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestPropertyLinkedMap" ).getName(),
- result.getName() );
+ database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeLinkMapByValue")
+ .getName(), result.getName());
final OIndexDefinition indexDefinition = result.getDefinition();
- assertTrue( indexDefinition instanceof OPropertyMapIndexDefinition );
- assertEquals( indexDefinition.getFields().get( 0 ), "fLinkMap" );
- assertEquals( indexDefinition.getTypes()[0], OType.STRING );
- assertEquals(((OPropertyMapIndexDefinition)indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.KEY );
+ assertTrue(indexDefinition instanceof OCompositeIndexDefinition);
+ assertEquals(indexDefinition.getFields().toArray(), new String[] { "fEleven", "fLinkMap" });
+
+ assertEquals(indexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.LINK });
+ assertEquals(indexDefinition.getParamCount(), 2);
+ }
+
+ @Test
+ public void testCreateCompositeEmbeddedSetIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeEmbeddedSet", OClass.INDEX_TYPE.UNIQUE, "fTwelve",
+ "fEmbeddedSet");
+
+ assertEquals(result.getName(), "ClassIndexTestCompositeEmbeddedSet");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeEmbeddedSet").getName(), result.getName());
+ assertEquals(database.getMetadata().getIndexManager()
+ .getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeEmbeddedSet").getName(), result.getName());
+
+ final OIndexDefinition indexDefinition = result.getDefinition();
+
+ assertTrue(indexDefinition instanceof OCompositeIndexDefinition);
+ assertEquals(indexDefinition.getFields().toArray(), new String[] { "fTwelve", "fEmbeddedSet" });
+
+ assertEquals(indexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.INTEGER });
+ assertEquals(indexDefinition.getParamCount(), 2);
+ }
+
+ @Test(expectedExceptions = OIndexException.class)
+ public void testCreateCompositeLinkSetIndex() {
+ oClass.createIndex("ClassIndexTestCompositeLinkSet", OClass.INDEX_TYPE.UNIQUE, "fTwelve", "fLinkSet");
}
@Test
- public void testCreateOnePropertyLinkMapByValueIndex()
- {
- final OIndex result = oClass.createIndex( "ClassIndexTestPropertyLinkedMap", OClass.INDEX_TYPE.UNIQUE, "fLinkMap by value" );
+ public void testCreateCompositeEmbeddedListIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeEmbeddedList", OClass.INDEX_TYPE.UNIQUE, "fThirteen",
+ "fEmbeddedList");
- assertEquals( result.getName(), "ClassIndexTestPropertyLinkedMap" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestPropertyLinkedMap" ).getName(), result.getName() );
+ assertEquals(result.getName(), "ClassIndexTestCompositeEmbeddedList");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeEmbeddedList").getName(), result.getName());
assertEquals(
- database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestPropertyLinkedMap" ).getName(),
- result.getName() );
+ database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeEmbeddedList")
+ .getName(), result.getName());
final OIndexDefinition indexDefinition = result.getDefinition();
- assertTrue( indexDefinition instanceof OPropertyMapIndexDefinition );
- assertEquals( indexDefinition.getFields().get( 0 ), "fLinkMap" );
- assertEquals( indexDefinition.getTypes()[0], OType.LINK );
- assertEquals(((OPropertyMapIndexDefinition)indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.VALUE );
+ assertTrue(indexDefinition instanceof OCompositeIndexDefinition);
+ assertEquals(indexDefinition.getFields().toArray(), new String[] { "fThirteen", "fEmbeddedList" });
+
+ assertEquals(indexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.INTEGER });
+ assertEquals(indexDefinition.getParamCount(), 2);
}
+ @Test
+ public void testCreateCompositeLinkListIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestCompositeLinkList", OClass.INDEX_TYPE.UNIQUE, "fFourteen", "fLinkList");
+
+ assertEquals(result.getName(), "ClassIndexTestCompositeLinkList");
+ assertEquals(oClass.getClassIndex("ClassIndexTestCompositeLinkList").getName(), result.getName());
+ assertEquals(database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestCompositeLinkList")
+ .getName(), result.getName());
+
+ final OIndexDefinition indexDefinition = result.getDefinition();
+
+ assertTrue(indexDefinition instanceof OCompositeIndexDefinition);
+ assertEquals(indexDefinition.getFields().toArray(), new String[] { "fFourteen", "fLinkList" });
+
+ assertEquals(indexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.LINK });
+ assertEquals(indexDefinition.getParamCount(), 2);
+ }
@Test
- public void testCreateOnePropertyByKeyEmbeddedMapIndex()
- {
- final OIndex result = oClass.createIndex( "ClassIndexTestPropertyByKeyEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap by key" );
+ public void testCreateOnePropertyLinkedMapIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestPropertyLinkedMap", OClass.INDEX_TYPE.UNIQUE, "fLinkMap");
+
+ assertEquals(result.getName(), "ClassIndexTestPropertyLinkedMap");
+ assertEquals(oClass.getClassIndex("ClassIndexTestPropertyLinkedMap").getName(), result.getName());
+ assertEquals(database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestPropertyLinkedMap")
+ .getName(), result.getName());
+
+ final OIndexDefinition indexDefinition = result.getDefinition();
- assertEquals( result.getName(), "ClassIndexTestPropertyByKeyEmbeddedMap" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestPropertyByKeyEmbeddedMap" ).getName(), result.getName() );
+ assertTrue(indexDefinition instanceof OPropertyMapIndexDefinition);
+ assertEquals(indexDefinition.getFields().get(0), "fLinkMap");
+ assertEquals(indexDefinition.getTypes()[0], OType.STRING);
+ assertEquals(((OPropertyMapIndexDefinition) indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.KEY);
+ }
+
+ @Test
+ public void testCreateOnePropertyLinkMapByKeyIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestPropertyLinkedMapByKey", OClass.INDEX_TYPE.UNIQUE, "fLinkMap by key");
+
+ assertEquals(result.getName(), "ClassIndexTestPropertyLinkedMapByKey");
+ assertEquals(oClass.getClassIndex("ClassIndexTestPropertyLinkedMapByKey").getName(), result.getName());
assertEquals(
- database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestPropertyByKeyEmbeddedMap" ).getName(),
- result.getName() );
+ database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestPropertyLinkedMapByKey")
+ .getName(), result.getName());
final OIndexDefinition indexDefinition = result.getDefinition();
- assertTrue( indexDefinition instanceof OPropertyMapIndexDefinition );
- assertEquals( indexDefinition.getFields().get( 0 ), "fEmbeddedMap" );
- assertEquals( indexDefinition.getTypes()[0], OType.STRING );
- assertEquals(((OPropertyMapIndexDefinition)indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.KEY );
+ assertTrue(indexDefinition instanceof OPropertyMapIndexDefinition);
+ assertEquals(indexDefinition.getFields().get(0), "fLinkMap");
+ assertEquals(indexDefinition.getTypes()[0], OType.STRING);
+ assertEquals(((OPropertyMapIndexDefinition) indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.KEY);
}
@Test
- public void testCreateOnePropertyByValueEmbeddedMapIndex()
- {
- final OIndex result = oClass.createIndex( "ClassIndexTestPropertyByValueEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap by value" );
+ public void testCreateOnePropertyLinkMapByValueIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestPropertyLinkedMapByValue", OClass.INDEX_TYPE.UNIQUE,
+ "fLinkMap by value");
- assertEquals( result.getName(), "ClassIndexTestPropertyByValueEmbeddedMap" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestPropertyByValueEmbeddedMap" ).getName(), result.getName() );
+ assertEquals(result.getName(), "ClassIndexTestPropertyLinkedMapByValue");
+ assertEquals(oClass.getClassIndex("ClassIndexTestPropertyLinkedMapByValue").getName(), result.getName());
assertEquals(
- database.getMetadata().getIndexManager().getClassIndex( "ClassIndexTestClass", "ClassIndexTestPropertyByValueEmbeddedMap" ).getName(),
- result.getName() );
+ database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestPropertyLinkedMapByValue")
+ .getName(), result.getName());
final OIndexDefinition indexDefinition = result.getDefinition();
- assertTrue( indexDefinition instanceof OPropertyMapIndexDefinition );
- assertEquals( indexDefinition.getFields().get( 0 ), "fEmbeddedMap" );
- assertEquals( indexDefinition.getTypes()[0], OType.INTEGER );
- assertEquals(((OPropertyMapIndexDefinition)indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.VALUE );
+ assertTrue(indexDefinition instanceof OPropertyMapIndexDefinition);
+ assertEquals(indexDefinition.getFields().get(0), "fLinkMap");
+ assertEquals(indexDefinition.getTypes()[0], OType.LINK);
+ assertEquals(((OPropertyMapIndexDefinition) indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.VALUE);
}
@Test
- public void testCreateOnePropertyWrongSpecifierEmbeddedMapIndexOne()
- {
+ public void testCreateOnePropertyByKeyEmbeddedMapIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestPropertyByKeyEmbeddedMap", OClass.INDEX_TYPE.UNIQUE,
+ "fEmbeddedMap by key");
+
+ assertEquals(result.getName(), "ClassIndexTestPropertyByKeyEmbeddedMap");
+ assertEquals(oClass.getClassIndex("ClassIndexTestPropertyByKeyEmbeddedMap").getName(), result.getName());
+ assertEquals(
+ database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestPropertyByKeyEmbeddedMap")
+ .getName(), result.getName());
+
+ final OIndexDefinition indexDefinition = result.getDefinition();
+
+ assertTrue(indexDefinition instanceof OPropertyMapIndexDefinition);
+ assertEquals(indexDefinition.getFields().get(0), "fEmbeddedMap");
+ assertEquals(indexDefinition.getTypes()[0], OType.STRING);
+ assertEquals(((OPropertyMapIndexDefinition) indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.KEY);
+ }
+
+ @Test
+ public void testCreateOnePropertyByValueEmbeddedMapIndex() {
+ final OIndex result = oClass.createIndex("ClassIndexTestPropertyByValueEmbeddedMap", OClass.INDEX_TYPE.UNIQUE,
+ "fEmbeddedMap by value");
+
+ assertEquals(result.getName(), "ClassIndexTestPropertyByValueEmbeddedMap");
+ assertEquals(oClass.getClassIndex("ClassIndexTestPropertyByValueEmbeddedMap").getName(), result.getName());
+ assertEquals(
+ database.getMetadata().getIndexManager().getClassIndex("ClassIndexTestClass", "ClassIndexTestPropertyByValueEmbeddedMap")
+ .getName(), result.getName());
+
+ final OIndexDefinition indexDefinition = result.getDefinition();
+
+ assertTrue(indexDefinition instanceof OPropertyMapIndexDefinition);
+ assertEquals(indexDefinition.getFields().get(0), "fEmbeddedMap");
+ assertEquals(indexDefinition.getTypes()[0], OType.INTEGER);
+ assertEquals(((OPropertyMapIndexDefinition) indexDefinition).getIndexBy(), OPropertyMapIndexDefinition.INDEX_BY.VALUE);
+ }
+
+ @Test
+ public void testCreateOnePropertyWrongSpecifierEmbeddedMapIndexOne() {
boolean exceptionIsThrown = false;
try {
- oClass.createIndex( "ClassIndexTestPropertyWrongSpecifierEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap by ttt" );
- } catch( IllegalArgumentException e ) {
+ oClass.createIndex("ClassIndexTestPropertyWrongSpecifierEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap by ttt");
+ } catch (IllegalArgumentException e) {
exceptionIsThrown = true;
- assertEquals(e.getMessage(), "Illegal field name format, should be '<property> [by key|value]' but was 'fEmbeddedMap by ttt'" );
+ assertEquals(e.getMessage(), "Illegal field name format, should be '<property> [by key|value]' but was 'fEmbeddedMap by ttt'");
}
- assertTrue( exceptionIsThrown );
- assertNull( oClass.getClassIndex( "ClassIndexTestPropertyWrongSpecifierEmbeddedMap" ));
+ assertTrue(exceptionIsThrown);
+ assertNull(oClass.getClassIndex("ClassIndexTestPropertyWrongSpecifierEmbeddedMap"));
}
@Test
- public void testCreateOnePropertyWrongSpecifierEmbeddedMapIndexTwo()
- {
+ public void testCreateOnePropertyWrongSpecifierEmbeddedMapIndexTwo() {
boolean exceptionIsThrown = false;
try {
- oClass.createIndex( "ClassIndexTestPropertyWrongSpecifierEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap b value" );
- } catch( IllegalArgumentException e ) {
+ oClass.createIndex("ClassIndexTestPropertyWrongSpecifierEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap b value");
+ } catch (IllegalArgumentException e) {
exceptionIsThrown = true;
- assertEquals(e.getMessage(), "Illegal field name format, should be '<property> [by key|value]' but was 'fEmbeddedMap b value'" );
+ assertEquals(e.getMessage(),
+ "Illegal field name format, should be '<property> [by key|value]' but was 'fEmbeddedMap b value'");
}
- assertTrue( exceptionIsThrown );
- assertNull( oClass.getClassIndex( "ClassIndexTestPropertyWrongSpecifierEmbeddedMap" ));
+ assertTrue(exceptionIsThrown);
+ assertNull(oClass.getClassIndex("ClassIndexTestPropertyWrongSpecifierEmbeddedMap"));
}
@Test
- public void testCreateOnePropertyWrongSpecifierEmbeddedMapIndexThree()
- {
+ public void testCreateOnePropertyWrongSpecifierEmbeddedMapIndexThree() {
boolean exceptionIsThrown = false;
try {
- oClass.createIndex( "ClassIndexTestPropertyWrongSpecifierEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap by value t" );
- } catch( IllegalArgumentException e ) {
+ oClass.createIndex("ClassIndexTestPropertyWrongSpecifierEmbeddedMap", OClass.INDEX_TYPE.UNIQUE, "fEmbeddedMap by value t");
+ } catch (IllegalArgumentException e) {
exceptionIsThrown = true;
- assertEquals(e.getMessage(), "Illegal field name format, should be '<property> [by key|value]' but was 'fEmbeddedMap by value t'" );
+ assertEquals(e.getMessage(),
+ "Illegal field name format, should be '<property> [by key|value]' but was 'fEmbeddedMap by value t'");
}
- assertTrue( exceptionIsThrown );
- assertNull( oClass.getClassIndex( "ClassIndexTestPropertyWrongSpecifierEmbeddedMap" ));
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedOneProperty()
- {
- final boolean result = oClass.areIndexed( Arrays.asList( "fOne" ) );
-
- assertTrue( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedDoesNotContainProperty()
- {
- final boolean result = oClass.areIndexed( Arrays.asList( "fSix" ) );
-
- assertFalse( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedTwoProperties()
- {
- final boolean result = oClass.areIndexed( Arrays.asList( "fTwo", "fOne" ) );
-
- assertTrue( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedThreeProperties()
- {
- final boolean result = oClass.areIndexed( Arrays.asList( "fTwo", "fOne", "fThree" ) );
-
- assertTrue( result );
- }
-
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedPropertiesNotFirst()
- {
- final boolean result = oClass.areIndexed( Arrays.asList( "fTwo", "fTree" ) );
-
- assertFalse( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedPropertiesMoreThanNeeded()
- {
- final boolean result = oClass.areIndexed( Arrays.asList( "fTwo", "fOne", "fThee", "fFour" ) );
-
- assertFalse( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "createParentPropertyIndex", "testCreateOnePropertyEmbeddedMapIndex",
- "testCreateOnePropertyByKeyEmbeddedMapIndex", "testCreateOnePropertyByValueEmbeddedMapIndex",
- "testCreateOnePropertyLinkedMapIndex", "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedParentProperty()
- {
- final boolean result = oClass.areIndexed( Arrays.asList( "fNine" ) );
-
- assertTrue( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex"
- , "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedParentChildProperty()
- {
- final boolean result = oClass.areIndexed( Arrays.asList( "fOne, fNine" ) );
-
- assertFalse( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedOnePropertyArrayParams()
- {
- final boolean result = oClass.areIndexed( "fOne" );
-
- assertTrue( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedDoesNotContainPropertyArrayParams()
- {
- final boolean result = oClass.areIndexed( "fSix" );
-
- assertFalse( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedTwoPropertiesArrayParams()
- {
- final boolean result = oClass.areIndexed( "fTwo", "fOne" );
-
- assertTrue( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedThreePropertiesArrayParams()
- {
- final boolean result = oClass.areIndexed( "fTwo", "fOne", "fThree" );
-
- assertTrue( result );
- }
-
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedPropertiesNotFirstArrayParams()
- {
- final boolean result = oClass.areIndexed( "fTwo", "fTree" );
-
- assertFalse( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedPropertiesMoreThanNeededArrayParams()
- {
- final boolean result = oClass.areIndexed( "fTwo", "fOne", "fThee", "fFour" );
-
- assertFalse( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "createParentPropertyIndex", "testCreateOnePropertyEmbeddedMapIndex",
- "testCreateOnePropertyByKeyEmbeddedMapIndex", "testCreateOnePropertyByValueEmbeddedMapIndex",
- "testCreateOnePropertyLinkedMapIndex", "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedParentPropertyArrayParams()
- {
- final boolean result = oClass.areIndexed( "fNine" );
-
- assertTrue( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testAreIndexedParentChildPropertyArrayParams()
- {
- final boolean result = oClass.areIndexed( "fOne, fNine" );
-
- assertFalse( result );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesOnePropertyArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( "fOne" );
-
- assertEquals( result.size(), 3 );
-
- assertTrue( containsIndex( result, "ClassIndexTestPropertyOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeTwo" ) );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesTwoPropertiesArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( "fTwo", "fOne" );
- assertEquals( result.size(), 2 );
-
- assertTrue( containsIndex( result, "ClassIndexTestCompositeOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeTwo" ) );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesThreePropertiesArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( "fTwo", "fOne", "fThree" );
-
- assertEquals( result.size(), 1 );
- assertEquals( result.iterator().next().getName(), "ClassIndexTestCompositeTwo" );
- }
-
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesNotInvolvedPropertiesArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( "fTwo", "fFour" );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesPropertiesMorThanNeededArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( "fTwo", "fOne", "fThee", "fFour" );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesPropertiesMorThanNeeded()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( Arrays.asList( "fTwo", "fOne", "fThee", "fFour" ) );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesOneProperty()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( Arrays.asList( "fOne" ) );
-
- assertEquals( result.size(), 3 );
-
- assertTrue( containsIndex( result, "ClassIndexTestPropertyOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeTwo" ) );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesTwoProperties()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( Arrays.asList( "fTwo", "fOne" ) );
- assertEquals( result.size(), 2 );
-
- assertTrue( containsIndex( result, "ClassIndexTestCompositeOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeTwo" ) );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesThreeProperties()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( Arrays.asList( "fTwo", "fOne", "fThree" ) );
-
- assertEquals( result.size(), 1 );
- assertEquals( result.iterator().next().getName(), "ClassIndexTestCompositeTwo" );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesNotInvolvedProperties()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( Arrays.asList( "fTwo", "fFour" ) );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassInvolvedIndexesPropertiesMorThanNeeded()
- {
- final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes( Arrays.asList( "fTwo", "fOne", "fThee", "fFour" ) );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesOnePropertyArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( "fOne" );
-
- assertEquals( result.size(), 3 );
-
- assertTrue( containsIndex( result, "ClassIndexTestPropertyOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeTwo" ) );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesTwoPropertiesArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( "fTwo", "fOne" );
- assertEquals( result.size(), 2 );
-
- assertTrue( containsIndex( result, "ClassIndexTestCompositeOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeTwo" ) );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesThreePropertiesArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( "fTwo", "fOne", "fThree" );
-
- assertEquals( result.size(), 1 );
- assertEquals( result.iterator().next().getName(), "ClassIndexTestCompositeTwo" );
- }
-
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesNotInvolvedPropertiesArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( "fTwo", "fFour" );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetParentInvolvedIndexesArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( "fNine" );
-
- assertEquals( result.size(), 1 );
- assertEquals( result.iterator().next().getName(), "ClassIndexTestParentPropertyNine" );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetParentChildInvolvedIndexesArrayParams()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( "fOne", "fNine" );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesOneProperty()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( Arrays.asList( "fOne" ) );
-
- assertEquals( result.size(), 3 );
-
- assertTrue( containsIndex( result, "ClassIndexTestPropertyOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeTwo" ) );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesTwoProperties()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( Arrays.asList( "fTwo", "fOne" ) );
- assertEquals( result.size(), 2 );
-
- assertTrue( containsIndex( result, "ClassIndexTestCompositeOne" ) );
- assertTrue( containsIndex( result, "ClassIndexTestCompositeTwo" ) );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesThreeProperties()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( Arrays.asList( "fTwo", "fOne", "fThree" ) );
-
- assertEquals( result.size(), 1 );
- assertEquals( result.iterator().next().getName(), "ClassIndexTestCompositeTwo" );
- }
-
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetInvolvedIndexesNotInvolvedProperties()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( Arrays.asList( "fTwo", "fFour" ) );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetParentInvolvedIndexes()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( Arrays.asList( "fNine" ) );
-
- assertEquals( result.size(), 1 );
- assertEquals( result.iterator().next().getName(), "ClassIndexTestParentPropertyNine" );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetParentChildInvolvedIndexes()
- {
- final Set<OIndex<?>> result = oClass.getInvolvedIndexes( Arrays.asList( "fOne", "fNine" ) );
-
- assertEquals( result.size(), 0 );
- }
-
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
- "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
- "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetClassIndexes()
- {
- final Set<OIndex<?>> indexes = oClass.getClassIndexes();
- final Set<OIndexDefinition> expectedIndexDefinitions = new HashSet<OIndexDefinition>();
+ assertTrue(exceptionIsThrown);
+ assertNull(oClass.getClassIndex("ClassIndexTestPropertyWrongSpecifierEmbeddedMap"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedOneProperty() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fOne"));
- final OCompositeIndexDefinition compositeIndexOne = new OCompositeIndexDefinition( "ClassIndexTestClass" );
+ assertTrue(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapIndex", "testCreateCompositeEmbeddedMapByKeyIndex",
+ "testCreateCompositeEmbeddedMapByValueIndex", "testCreateCompositeLinkMapByValueIndex",
+ "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedEightProperty() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fEight"));
+ assertTrue(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByKeyIndex",
+ "testCreateCompositeEmbeddedMapByValueIndex", "testCreateCompositeLinkMapByValueIndex",
+ "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedEightPropertyEmbeddedMap() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fEmbeddedMap", "fEight"));
+ assertTrue(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedDoesNotContainProperty() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fSix"));
- compositeIndexOne.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fOne", OType.INTEGER ) );
- compositeIndexOne.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fTwo", OType.STRING ) );
- expectedIndexDefinitions.add( compositeIndexOne );
+ assertFalse(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedTwoProperties() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fTwo", "fOne"));
- final OCompositeIndexDefinition compositeIndexTwo = new OCompositeIndexDefinition( "ClassIndexTestClass" );
+ assertTrue(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedThreeProperties() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fTwo", "fOne", "fThree"));
- compositeIndexTwo.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fOne", OType.INTEGER ) );
- compositeIndexTwo.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fTwo", OType.STRING ) );
- compositeIndexTwo.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fThree", OType.BOOLEAN ) );
- expectedIndexDefinitions.add( compositeIndexTwo );
+ assertTrue(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedPropertiesNotFirst() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fTwo", "fTree"));
- final OPropertyIndexDefinition propertyIndex = new OPropertyIndexDefinition( "ClassIndexTestClass", "fOne", OType.INTEGER );
- expectedIndexDefinitions.add( propertyIndex );
+ assertFalse(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedPropertiesMoreThanNeeded() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fTwo", "fOne", "fThee", "fFour"));
- final OPropertyMapIndexDefinition propertyMapIndexDefinition = new OPropertyMapIndexDefinition( "ClassIndexTestClass", "fEmbeddedMap", OType.STRING,
- OPropertyMapIndexDefinition.INDEX_BY.KEY );
- expectedIndexDefinitions.add( propertyMapIndexDefinition );
-
- final OPropertyMapIndexDefinition propertyMapByValueIndexDefinition = new OPropertyMapIndexDefinition( "ClassIndexTestClass", "fEmbeddedMap", OType.INTEGER,
- OPropertyMapIndexDefinition.INDEX_BY.VALUE );
- expectedIndexDefinitions.add( propertyMapByValueIndexDefinition );
-
- final OPropertyMapIndexDefinition propertyLinkMapByKeyIndexDefinition = new OPropertyMapIndexDefinition( "ClassIndexTestClass", "fLinkMap", OType.STRING,
- OPropertyMapIndexDefinition.INDEX_BY.KEY );
- expectedIndexDefinitions.add( propertyLinkMapByKeyIndexDefinition );
-
- final OPropertyMapIndexDefinition propertyLinkMapByValueIndexDefinition = new OPropertyMapIndexDefinition( "ClassIndexTestClass", "fLinkMap", OType.LINK,
- OPropertyMapIndexDefinition.INDEX_BY.VALUE );
- expectedIndexDefinitions.add( propertyLinkMapByValueIndexDefinition );
-
- assertEquals( indexes.size(), 7);
-
- for( final OIndex index : indexes ) {
- assertTrue( expectedIndexDefinitions.contains( index.getDefinition() ) );
- }
+ assertFalse(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "createParentPropertyIndex", "testCreateOnePropertyEmbeddedMapIndex",
+ "testCreateOnePropertyByKeyEmbeddedMapIndex", "testCreateOnePropertyByValueEmbeddedMapIndex",
+ "testCreateOnePropertyLinkedMapIndex", "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex",
+ "testCreateCompositeEmbeddedMapIndex", "testCreateCompositeEmbeddedMapByKeyIndex",
+ "testCreateCompositeEmbeddedMapByValueIndex", "testCreateCompositeLinkMapByValueIndex",
+ "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedParentProperty() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fNine"));
+
+ assertTrue(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedParentChildProperty() {
+ final boolean result = oClass.areIndexed(Arrays.asList("fOne, fNine"));
+
+ assertFalse(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedOnePropertyArrayParams() {
+ final boolean result = oClass.areIndexed("fOne");
+
+ assertTrue(result);
+ }
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedDoesNotContainPropertyArrayParams() {
+ final boolean result = oClass.areIndexed("fSix");
+
+ assertFalse(result);
}
- @Test(dependsOnMethods = {
- "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
- "testCreateOnePropertyIndexTest", "createParentPropertyIndex", "testCreateOnePropertyEmbeddedMapIndex",
- "testCreateOnePropertyByKeyEmbeddedMapIndex", "testCreateOnePropertyByValueEmbeddedMapIndex",
- "testCreateOnePropertyLinkedMapIndex", "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex"
- })
- public void testGetIndexes()
- {
- final Set<OIndex<?>> indexes = oClass.getIndexes();
- final Set<OIndexDefinition> expectedIndexDefinitions = new HashSet<OIndexDefinition>();
-
- final OCompositeIndexDefinition compositeIndexOne = new OCompositeIndexDefinition( "ClassIndexTestClass" );
-
- compositeIndexOne.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fOne", OType.INTEGER ) );
- compositeIndexOne.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fTwo", OType.STRING ) );
- expectedIndexDefinitions.add( compositeIndexOne );
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedTwoPropertiesArrayParams() {
+ final boolean result = oClass.areIndexed("fTwo", "fOne");
+
+ assertTrue(result);
+ }
- final OCompositeIndexDefinition compositeIndexTwo = new OCompositeIndexDefinition( "ClassIndexTestClass" );
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedThreePropertiesArrayParams() {
+ final boolean result = oClass.areIndexed("fTwo", "fOne", "fThree");
+
+ assertTrue(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedPropertiesNotFirstArrayParams() {
+ final boolean result = oClass.areIndexed("fTwo", "fTree");
+
+ assertFalse(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedPropertiesMoreThanNeededArrayParams() {
+ final boolean result = oClass.areIndexed("fTwo", "fOne", "fThee", "fFour");
+
+ assertFalse(result);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "createParentPropertyIndex", "testCreateOnePropertyEmbeddedMapIndex",
+ "testCreateOnePropertyByKeyEmbeddedMapIndex", "testCreateOnePropertyByValueEmbeddedMapIndex",
+ "testCreateOnePropertyLinkedMapIndex", "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex",
+ "testCreateCompositeEmbeddedMapIndex", "testCreateCompositeEmbeddedMapByKeyIndex",
+ "testCreateCompositeEmbeddedMapByValueIndex", "testCreateCompositeLinkMapByValueIndex",
+ "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedParentPropertyArrayParams() {
+ final boolean result = oClass.areIndexed("fNine");
+
+ assertTrue(result);
+ }
- compositeIndexTwo.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fOne", OType.INTEGER ) );
- compositeIndexTwo.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fTwo", OType.STRING ) );
- compositeIndexTwo.addIndex( new OPropertyIndexDefinition( "ClassIndexTestClass", "fThree", OType.BOOLEAN ) );
- expectedIndexDefinitions.add( compositeIndexTwo );
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testAreIndexedParentChildPropertyArrayParams() {
+ final boolean result = oClass.areIndexed("fOne, fNine");
- final OPropertyIndexDefinition propertyIndex = new OPropertyIndexDefinition( "ClassIndexTestClass", "fOne", OType.INTEGER );
- expectedIndexDefinitions.add( propertyIndex );
+ assertFalse(result);
+ }
- final OPropertyIndexDefinition parentPropertyIndex = new OPropertyIndexDefinition( "ClassIndexTestSuperClass", "fNine", OType.INTEGER );
- expectedIndexDefinitions.add( parentPropertyIndex );
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesOnePropertyArrayParams() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes("fOne");
- final OPropertyMapIndexDefinition propertyMapIndexDefinition = new OPropertyMapIndexDefinition( "ClassIndexTestClass", "fEmbeddedMap", OType.STRING,
- OPropertyMapIndexDefinition.INDEX_BY.KEY );
- expectedIndexDefinitions.add( propertyMapIndexDefinition );
+ assertEquals(result.size(), 3);
- final OPropertyMapIndexDefinition propertyMapByValueIndexDefinition = new OPropertyMapIndexDefinition( "ClassIndexTestClass", "fEmbeddedMap", OType.INTEGER,
- OPropertyMapIndexDefinition.INDEX_BY.VALUE );
- expectedIndexDefinitions.add( propertyMapByValueIndexDefinition );
+ assertTrue(containsIndex(result, "ClassIndexTestPropertyOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeTwo"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesTwoPropertiesArrayParams() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes("fTwo", "fOne");
+ assertEquals(result.size(), 2);
+
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeTwo"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesThreePropertiesArrayParams() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes("fTwo", "fOne", "fThree");
+
+ assertEquals(result.size(), 1);
+ assertEquals(result.iterator().next().getName(), "ClassIndexTestCompositeTwo");
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesNotInvolvedPropertiesArrayParams() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes("fTwo", "fFour");
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesPropertiesMorThanNeededArrayParams() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes("fTwo", "fOne", "fThee", "fFour");
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesPropertiesMorThanNeeded() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes(Arrays.asList("fTwo", "fOne", "fThee", "fFour"));
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesOneProperty() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes(Arrays.asList("fOne"));
+
+ assertEquals(result.size(), 3);
+
+ assertTrue(containsIndex(result, "ClassIndexTestPropertyOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeTwo"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesTwoProperties() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes(Arrays.asList("fTwo", "fOne"));
+ assertEquals(result.size(), 2);
+
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeTwo"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesThreeProperties() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes(Arrays.asList("fTwo", "fOne", "fThree"));
+
+ assertEquals(result.size(), 1);
+ assertEquals(result.iterator().next().getName(), "ClassIndexTestCompositeTwo");
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesNotInvolvedProperties() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes(Arrays.asList("fTwo", "fFour"));
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassInvolvedIndexesPropertiesMorThanNeeded() {
+ final Set<OIndex<?>> result = oClass.getClassInvolvedIndexes(Arrays.asList("fTwo", "fOne", "fThee", "fFour"));
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesOnePropertyArrayParams() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes("fOne");
+
+ assertEquals(result.size(), 3);
+
+ assertTrue(containsIndex(result, "ClassIndexTestPropertyOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeTwo"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesTwoPropertiesArrayParams() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes("fTwo", "fOne");
+ assertEquals(result.size(), 2);
+
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeTwo"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesThreePropertiesArrayParams() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes("fTwo", "fOne", "fThree");
+
+ assertEquals(result.size(), 1);
+ assertEquals(result.iterator().next().getName(), "ClassIndexTestCompositeTwo");
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesNotInvolvedPropertiesArrayParams() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes("fTwo", "fFour");
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetParentInvolvedIndexesArrayParams() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes("fNine");
+
+ assertEquals(result.size(), 1);
+ assertEquals(result.iterator().next().getName(), "ClassIndexTestParentPropertyNine");
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetParentChildInvolvedIndexesArrayParams() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes("fOne", "fNine");
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesOneProperty() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes(Arrays.asList("fOne"));
+
+ assertEquals(result.size(), 3);
+
+ assertTrue(containsIndex(result, "ClassIndexTestPropertyOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeTwo"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesTwoProperties() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes(Arrays.asList("fTwo", "fOne"));
+ assertEquals(result.size(), 2);
+
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeOne"));
+ assertTrue(containsIndex(result, "ClassIndexTestCompositeTwo"));
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesThreeProperties() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes(Arrays.asList("fTwo", "fOne", "fThree"));
+
+ assertEquals(result.size(), 1);
+ assertEquals(result.iterator().next().getName(), "ClassIndexTestCompositeTwo");
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetInvolvedIndexesNotInvolvedProperties() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes(Arrays.asList("fTwo", "fFour"));
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetParentInvolvedIndexes() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes(Arrays.asList("fNine"));
+
+ assertEquals(result.size(), 1);
+ assertEquals(result.iterator().next().getName(), "ClassIndexTestParentPropertyNine");
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetParentChildInvolvedIndexes() {
+ final Set<OIndex<?>> result = oClass.getInvolvedIndexes(Arrays.asList("fOne", "fNine"));
+
+ assertEquals(result.size(), 0);
+ }
+
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "testCreateOnePropertyEmbeddedMapIndex", "testCreateOnePropertyByKeyEmbeddedMapIndex",
+ "testCreateOnePropertyByValueEmbeddedMapIndex", "testCreateOnePropertyLinkedMapIndex",
+ "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex", "testCreateCompositeEmbeddedMapIndex",
+ "testCreateCompositeEmbeddedMapByKeyIndex", "testCreateCompositeEmbeddedMapByValueIndex",
+ "testCreateCompositeLinkMapByValueIndex", "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetClassIndexes() {
+ final Set<OIndex<?>> indexes = oClass.getClassIndexes();
+ final Set<OIndexDefinition> expectedIndexDefinitions = new HashSet<OIndexDefinition>();
- final OPropertyMapIndexDefinition propertyLinkMapByKeyIndexDefinition = new OPropertyMapIndexDefinition( "ClassIndexTestClass", "fLinkMap", OType.STRING,
- OPropertyMapIndexDefinition.INDEX_BY.KEY );
- expectedIndexDefinitions.add( propertyLinkMapByKeyIndexDefinition );
+ final OCompositeIndexDefinition compositeIndexOne = new OCompositeIndexDefinition("ClassIndexTestClass");
+
+ compositeIndexOne.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fOne", OType.INTEGER));
+ compositeIndexOne.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fTwo", OType.STRING));
+ expectedIndexDefinitions.add(compositeIndexOne);
+
+ final OCompositeIndexDefinition compositeIndexTwo = new OCompositeIndexDefinition("ClassIndexTestClass");
+
+ compositeIndexTwo.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fOne", OType.INTEGER));
+ compositeIndexTwo.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fTwo", OType.STRING));
+ compositeIndexTwo.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fThree", OType.BOOLEAN));
+ expectedIndexDefinitions.add(compositeIndexTwo);
+
+ final OCompositeIndexDefinition compositeIndexThree = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexThree.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fEight", OType.INTEGER));
+ compositeIndexThree.addIndex(new OPropertyMapIndexDefinition("ClassIndexTestClass", "fEmbeddedMap", OType.STRING,
+ OPropertyMapIndexDefinition.INDEX_BY.KEY));
+ expectedIndexDefinitions.add(compositeIndexThree);
+
+ final OCompositeIndexDefinition compositeIndexFour = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexFour.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fTen", OType.INTEGER));
+ compositeIndexFour.addIndex(new OPropertyMapIndexDefinition("ClassIndexTestClass", "fEmbeddedMap", OType.INTEGER,
+ OPropertyMapIndexDefinition.INDEX_BY.VALUE));
+ expectedIndexDefinitions.add(compositeIndexFour);
+
+ final OCompositeIndexDefinition compositeIndexFive = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexFive.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fEleven", OType.INTEGER));
+ compositeIndexFive.addIndex(new OPropertyMapIndexDefinition("ClassIndexTestClass", "fLinkMap", OType.LINK,
+ OPropertyMapIndexDefinition.INDEX_BY.VALUE));
+ expectedIndexDefinitions.add(compositeIndexFive);
+
+ final OCompositeIndexDefinition compositeIndexSix = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexSix.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fTwelve", OType.INTEGER));
+ compositeIndexSix.addIndex(new OPropertyListIndexDefinition("ClassIndexTestClass", "fEmbeddedSet", OType.INTEGER));
+ expectedIndexDefinitions.add(compositeIndexSix);
+
+ final OCompositeIndexDefinition compositeIndexSeven = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexSeven.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fThirteen", OType.INTEGER));
+ compositeIndexSeven.addIndex(new OPropertyListIndexDefinition("ClassIndexTestClass", "fEmbeddedList", OType.INTEGER));
+ expectedIndexDefinitions.add(compositeIndexSeven);
+
+ final OCompositeIndexDefinition compositeIndexEight = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexEight.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fFourteen", OType.INTEGER));
+ compositeIndexEight.addIndex(new OPropertyListIndexDefinition("ClassIndexTestClass", "fEmbeddedList", OType.LINK));
+ expectedIndexDefinitions.add(compositeIndexEight);
+
+ final OCompositeIndexDefinition compositeIndexNine = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexNine.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fFifteen", OType.INTEGER));
+ compositeIndexNine.addIndex(new OPropertyMapIndexDefinition("ClassIndexTestClass", "fEmbeddedMap", OType.STRING,
+ OPropertyMapIndexDefinition.INDEX_BY.KEY));
+ expectedIndexDefinitions.add(compositeIndexNine);
+
+ final OPropertyIndexDefinition propertyIndex = new OPropertyIndexDefinition("ClassIndexTestClass", "fOne", OType.INTEGER);
+ expectedIndexDefinitions.add(propertyIndex);
+
+ final OPropertyMapIndexDefinition propertyMapIndexDefinition = new OPropertyMapIndexDefinition("ClassIndexTestClass",
+ "fEmbeddedMap", OType.STRING, OPropertyMapIndexDefinition.INDEX_BY.KEY);
+ expectedIndexDefinitions.add(propertyMapIndexDefinition);
+
+ final OPropertyMapIndexDefinition propertyMapByValueIndexDefinition = new OPropertyMapIndexDefinition("ClassIndexTestClass",
+ "fEmbeddedMap", OType.INTEGER, OPropertyMapIndexDefinition.INDEX_BY.VALUE);
+ expectedIndexDefinitions.add(propertyMapByValueIndexDefinition);
+
+ final OPropertyMapIndexDefinition propertyLinkMapByKeyIndexDefinition = new OPropertyMapIndexDefinition("ClassIndexTestClass",
+ "fLinkMap", OType.STRING, OPropertyMapIndexDefinition.INDEX_BY.KEY);
+ expectedIndexDefinitions.add(propertyLinkMapByKeyIndexDefinition);
+
+ final OPropertyMapIndexDefinition propertyLinkMapByValueIndexDefinition = new OPropertyMapIndexDefinition(
+ "ClassIndexTestClass", "fLinkMap", OType.LINK, OPropertyMapIndexDefinition.INDEX_BY.VALUE);
+ expectedIndexDefinitions.add(propertyLinkMapByValueIndexDefinition);
+
+ assertEquals(indexes.size(), 15);
+
+ for (final OIndex index : indexes) {
+ assertTrue(expectedIndexDefinitions.contains(index.getDefinition()));
+ }
- final OPropertyMapIndexDefinition propertyLinkMapByValueIndexDefinition = new OPropertyMapIndexDefinition( "ClassIndexTestClass", "fLinkMap", OType.LINK,
- OPropertyMapIndexDefinition.INDEX_BY.VALUE );
- expectedIndexDefinitions.add( propertyLinkMapByValueIndexDefinition );
+ }
- assertEquals( indexes.size(), 8 );
+ @Test(dependsOnMethods = { "createCompositeIndexTestWithListener", "createCompositeIndexTestWithoutListener",
+ "testCreateOnePropertyIndexTest", "createParentPropertyIndex", "testCreateOnePropertyEmbeddedMapIndex",
+ "testCreateOnePropertyByKeyEmbeddedMapIndex", "testCreateOnePropertyByValueEmbeddedMapIndex",
+ "testCreateOnePropertyLinkedMapIndex", "testCreateOnePropertyLinkMapByKeyIndex", "testCreateOnePropertyLinkMapByValueIndex",
+ "testCreateCompositeEmbeddedMapIndex", "testCreateCompositeEmbeddedMapByKeyIndex",
+ "testCreateCompositeEmbeddedMapByValueIndex", "testCreateCompositeLinkMapByValueIndex",
+ "testCreateCompositeEmbeddedSetIndex", "testCreateCompositeEmbeddedListIndex" })
+ public void testGetIndexes() {
+ final Set<OIndex<?>> indexes = oClass.getIndexes();
+ final Set<OIndexDefinition> expectedIndexDefinitions = new HashSet<OIndexDefinition>();
- for( final OIndex index : indexes ) {
- assertTrue( expectedIndexDefinitions.contains( index.getDefinition() ) );
+ final OCompositeIndexDefinition compositeIndexOne = new OCompositeIndexDefinition("ClassIndexTestClass");
+
+ compositeIndexOne.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fOne", OType.INTEGER));
+ compositeIndexOne.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fTwo", OType.STRING));
+ expectedIndexDefinitions.add(compositeIndexOne);
+
+ final OCompositeIndexDefinition compositeIndexTwo = new OCompositeIndexDefinition("ClassIndexTestClass");
+
+ compositeIndexTwo.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fOne", OType.INTEGER));
+ compositeIndexTwo.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fTwo", OType.STRING));
+ compositeIndexTwo.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fThree", OType.BOOLEAN));
+ expectedIndexDefinitions.add(compositeIndexTwo);
+
+ final OCompositeIndexDefinition compositeIndexThree = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexThree.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fEight", OType.INTEGER));
+ compositeIndexThree.addIndex(new OPropertyMapIndexDefinition("ClassIndexTestClass", "fEmbeddedMap", OType.STRING,
+ OPropertyMapIndexDefinition.INDEX_BY.KEY));
+ expectedIndexDefinitions.add(compositeIndexThree);
+
+ final OCompositeIndexDefinition compositeIndexFour = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexFour.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fTen", OType.INTEGER));
+ compositeIndexFour.addIndex(new OPropertyMapIndexDefinition("ClassIndexTestClass", "fEmbeddedMap", OType.INTEGER,
+ OPropertyMapIndexDefinition.INDEX_BY.VALUE));
+ expectedIndexDefinitions.add(compositeIndexFour);
+
+ final OCompositeIndexDefinition compositeIndexFive = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexFive.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fEleven", OType.INTEGER));
+ compositeIndexFive.addIndex(new OPropertyMapIndexDefinition("ClassIndexTestClass", "fLinkMap", OType.LINK,
+ OPropertyMapIndexDefinition.INDEX_BY.VALUE));
+ expectedIndexDefinitions.add(compositeIndexFive);
+
+ final OCompositeIndexDefinition compositeIndexSix = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexSix.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fTwelve", OType.INTEGER));
+ compositeIndexSix.addIndex(new OPropertyListIndexDefinition("ClassIndexTestClass", "fEmbeddedSet", OType.INTEGER));
+ expectedIndexDefinitions.add(compositeIndexSix);
+
+ final OCompositeIndexDefinition compositeIndexSeven = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexSeven.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fThirteen", OType.INTEGER));
+ compositeIndexSeven.addIndex(new OPropertyListIndexDefinition("ClassIndexTestClass", "fEmbeddedList", OType.INTEGER));
+ expectedIndexDefinitions.add(compositeIndexSeven);
+
+ final OCompositeIndexDefinition compositeIndexEight = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexEight.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fFourteen", OType.INTEGER));
+ compositeIndexEight.addIndex(new OPropertyListIndexDefinition("ClassIndexTestClass", "fEmbeddedList", OType.LINK));
+ expectedIndexDefinitions.add(compositeIndexEight);
+
+ final OCompositeIndexDefinition compositeIndexNine = new OCompositeIndexDefinition("ClassIndexTestClass");
+ compositeIndexNine.addIndex(new OPropertyIndexDefinition("ClassIndexTestClass", "fFifteen", OType.INTEGER));
+ compositeIndexNine.addIndex(new OPropertyMapIndexDefinition("ClassIndexTestClass", "fEmbeddedMap", OType.STRING,
+ OPropertyMapIndexDefinition.INDEX_BY.KEY));
+ expectedIndexDefinitions.add(compositeIndexNine);
+
+ final OPropertyIndexDefinition propertyIndex = new OPropertyIndexDefinition("ClassIndexTestClass", "fOne", OType.INTEGER);
+ expectedIndexDefinitions.add(propertyIndex);
+
+ final OPropertyIndexDefinition parentPropertyIndex = new OPropertyIndexDefinition("ClassIndexTestSuperClass", "fNine",
+ OType.INTEGER);
+ expectedIndexDefinitions.add(parentPropertyIndex);
+
+ final OPropertyMapIndexDefinition propertyMapIndexDefinition = new OPropertyMapIndexDefinition("ClassIndexTestClass",
+ "fEmbeddedMap", OType.STRING, OPropertyMapIndexDefinition.INDEX_BY.KEY);
+ expectedIndexDefinitions.add(propertyMapIndexDefinition);
+
+ final OPropertyMapIndexDefinition propertyMapByValueIndexDefinition = new OPropertyMapIndexDefinition("ClassIndexTestClass",
+ "fEmbeddedMap", OType.INTEGER, OPropertyMapIndexDefinition.INDEX_BY.VALUE);
+ expectedIndexDefinitions.add(propertyMapByValueIndexDefinition);
+
+ final OPropertyMapIndexDefinition propertyLinkMapByKeyIndexDefinition = new OPropertyMapIndexDefinition("ClassIndexTestClass",
+ "fLinkMap", OType.STRING, OPropertyMapIndexDefinition.INDEX_BY.KEY);
+ expectedIndexDefinitions.add(propertyLinkMapByKeyIndexDefinition);
+
+ final OPropertyMapIndexDefinition propertyLinkMapByValueIndexDefinition = new OPropertyMapIndexDefinition(
+ "ClassIndexTestClass", "fLinkMap", OType.LINK, OPropertyMapIndexDefinition.INDEX_BY.VALUE);
+ expectedIndexDefinitions.add(propertyLinkMapByValueIndexDefinition);
+
+ assertEquals(indexes.size(), 16);
+
+ for (final OIndex index : indexes) {
+ assertTrue(expectedIndexDefinitions.contains(index.getDefinition()));
}
}
@Test
- public void testGetIndexesWithoutParent()
- {
-
- final OClass inClass = database.getMetadata().getSchema().createClass( "ClassIndexInTest" );
- inClass.createProperty( "fOne", OType.INTEGER );
+ public void testGetIndexesWithoutParent() {
+ final OClass inClass = database.getMetadata().getSchema().createClass("ClassIndexInTest");
+ inClass.createProperty("fOne", OType.INTEGER);
- final OIndex result = inClass.createIndex( "ClassIndexTestPropertyOne", OClass.INDEX_TYPE.UNIQUE, "fOne" );
+ final OIndex result = inClass.createIndex("ClassIndexTestPropertyOne", OClass.INDEX_TYPE.UNIQUE, "fOne");
- assertEquals( result.getName(), "ClassIndexTestPropertyOne" );
- assertEquals( inClass.getClassIndex( "ClassIndexTestPropertyOne" ).getName(), result.getName() );
+ assertEquals(result.getName(), "ClassIndexTestPropertyOne");
+ assertEquals(inClass.getClassIndex("ClassIndexTestPropertyOne").getName(), result.getName());
final Set<OIndex<?>> indexes = inClass.getIndexes();
- final OPropertyIndexDefinition propertyIndexDefinition = new OPropertyIndexDefinition( "ClassIndexInTest", "fOne", OType.INTEGER );
+ final OPropertyIndexDefinition propertyIndexDefinition = new OPropertyIndexDefinition("ClassIndexInTest", "fOne", OType.INTEGER);
- assertEquals( indexes.size(), 1 );
+ assertEquals(indexes.size(), 1);
- assertTrue( indexes.iterator().next().getDefinition().equals( propertyIndexDefinition ) );
+ assertTrue(indexes.iterator().next().getDefinition().equals(propertyIndexDefinition));
}
@Test(expectedExceptions = OIndexException.class)
- public void testCreateIndexEmptyFields()
- {
- oClass.createIndex( "ClassIndexTestCompositeEmpty", OClass.INDEX_TYPE.UNIQUE );
+ public void testCreateIndexEmptyFields() {
+ oClass.createIndex("ClassIndexTestCompositeEmpty", OClass.INDEX_TYPE.UNIQUE);
}
@Test(expectedExceptions = OIndexException.class)
- public void testCreateIndexAbsentFields()
- {
- oClass.createIndex( "ClassIndexTestCompositeFieldAbsent", OClass.INDEX_TYPE.UNIQUE, "fFive" );
+ public void testCreateIndexAbsentFields() {
+ oClass.createIndex("ClassIndexTestCompositeFieldAbsent", OClass.INDEX_TYPE.UNIQUE, "fFive");
}
@Test(expectedExceptions = OIndexException.class)
- public void testCreateProxyIndex()
- {
- oClass.createIndex( "ClassIndexTestProxyIndex", OClass.INDEX_TYPE.PROXY, "fOne" );
+ public void testCreateProxyIndex() {
+ oClass.createIndex("ClassIndexTestProxyIndex", OClass.INDEX_TYPE.PROXY, "fOne");
}
@Test(expectedExceptions = OIndexException.class)
- public void testCreateFullTextIndexTwoProperties()
- {
- oClass.createIndex( "ClassIndexTestFulltextIndex", OClass.INDEX_TYPE.FULLTEXT, "fSix", "fSeven" );
+ public void testCreateFullTextIndexTwoProperties() {
+ oClass.createIndex("ClassIndexTestFulltextIndex", OClass.INDEX_TYPE.FULLTEXT, "fSix", "fSeven");
}
@Test
- public void testCreateFullTextIndexOneProperty()
- {
- final OIndex<?> result = oClass.createIndex( "ClassIndexTestFulltextIndex", OClass.INDEX_TYPE.FULLTEXT, "fSix" );
+ public void testCreateFullTextIndexOneProperty() {
+ final OIndex<?> result = oClass.createIndex("ClassIndexTestFulltextIndex", OClass.INDEX_TYPE.FULLTEXT, "fSix");
- assertEquals( result.getName(), "ClassIndexTestFulltextIndex" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestFulltextIndex" ).getName(), result.getName() );
- assertEquals( result.getType(), OClass.INDEX_TYPE.FULLTEXT.toString() );
+ assertEquals(result.getName(), "ClassIndexTestFulltextIndex");
+ assertEquals(oClass.getClassIndex("ClassIndexTestFulltextIndex").getName(), result.getName());
+ assertEquals(result.getType(), OClass.INDEX_TYPE.FULLTEXT.toString());
}
@Test
- public void testCreateDictionaryIndex()
- {
- final OIndex<?> result = oClass.createIndex( "ClassIndexTestDictionaryIndex", OClass.INDEX_TYPE.DICTIONARY, "fOne" );
+ public void testCreateDictionaryIndex() {
+ final OIndex<?> result = oClass.createIndex("ClassIndexTestDictionaryIndex", OClass.INDEX_TYPE.DICTIONARY, "fOne");
- assertEquals( result.getName(), "ClassIndexTestDictionaryIndex" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestDictionaryIndex" ).getName(), result.getName() );
- assertEquals( result.getType(), OClass.INDEX_TYPE.DICTIONARY.toString() );
+ assertEquals(result.getName(), "ClassIndexTestDictionaryIndex");
+ assertEquals(oClass.getClassIndex("ClassIndexTestDictionaryIndex").getName(), result.getName());
+ assertEquals(result.getType(), OClass.INDEX_TYPE.DICTIONARY.toString());
}
@Test
- public void testCreateNotUniqueIndex()
- {
- final OIndex<?> result = oClass.createIndex( "ClassIndexTestNotUniqueIndex", OClass.INDEX_TYPE.NOTUNIQUE, "fOne" );
+ public void testCreateNotUniqueIndex() {
+ final OIndex<?> result = oClass.createIndex("ClassIndexTestNotUniqueIndex", OClass.INDEX_TYPE.NOTUNIQUE, "fOne");
- assertEquals( result.getName(), "ClassIndexTestNotUniqueIndex" );
- assertEquals( oClass.getClassIndex( "ClassIndexTestNotUniqueIndex" ).getName(), result.getName() );
- assertEquals( result.getType(), OClass.INDEX_TYPE.NOTUNIQUE.toString() );
+ assertEquals(result.getName(), "ClassIndexTestNotUniqueIndex");
+ assertEquals(oClass.getClassIndex("ClassIndexTestNotUniqueIndex").getName(), result.getName());
+ assertEquals(result.getType(), OClass.INDEX_TYPE.NOTUNIQUE.toString());
}
@Test
public void testCreateMapWithoutLinkedType() {
try {
- oClass.createIndex( "ClassIndexMapWithoutLinkedTypeIndex", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedMapWithoutLinkedType by value" );
+ oClass.createIndex("ClassIndexMapWithoutLinkedTypeIndex", OClass.INDEX_TYPE.NOTUNIQUE,
+ "fEmbeddedMapWithoutLinkedType by value");
fail();
} catch (OIndexException e) {
- assertEquals(e.getMessage(), "Linked type was not provided. " +
- "You should provide linked type for embedded collections that are going to be indexed.");
+ assertEquals(e.getMessage(), "Linked type was not provided. "
+ + "You should provide linked type for embedded collections that are going to be indexed.");
}
}
-
- public void createParentPropertyIndex()
- {
- final OIndex result = oSuperClass.createIndex( "ClassIndexTestParentPropertyNine", OClass.INDEX_TYPE.UNIQUE, "fNine" );
- assertEquals( result.getName(), "ClassIndexTestParentPropertyNine" );
- assertEquals( oSuperClass.getClassIndex( "ClassIndexTestParentPropertyNine" ).getName(), result.getName() );
+ public void createParentPropertyIndex() {
+ final OIndex result = oSuperClass.createIndex("ClassIndexTestParentPropertyNine", OClass.INDEX_TYPE.UNIQUE, "fNine");
+
+ assertEquals(result.getName(), "ClassIndexTestParentPropertyNine");
+ assertEquals(oSuperClass.getClassIndex("ClassIndexTestParentPropertyNine").getName(), result.getName());
}
- private boolean containsIndex( final Collection<? extends OIndex> classIndexes, final String indexName )
- {
- for( final OIndex index : classIndexes ) {
- if ( index.getName().equals( indexName ) ) {
+ private boolean containsIndex(final Collection<? extends OIndex> classIndexes, final String indexName) {
+ for (final OIndex index : classIndexes) {
+ if (index.getName().equals(indexName)) {
return true;
}
}
@@ -1078,12 +1276,11 @@ private boolean containsIndex( final Collection<? extends OIndex> classIndexes,
}
@Test
- public void testDropProperty() throws Exception
- {
- oClass.createProperty( "fFive", OType.INTEGER );
+ public void testDropProperty() throws Exception {
+ oClass.createProperty("fFive", OType.INTEGER);
- oClass.dropProperty( "fFive" );
+ oClass.dropProperty("fFive");
- assertNull( oClass.getProperty( "fFive" ) );
+ assertNull(oClass.getProperty("fFive"));
}
}
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectIndexReuseTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectIndexReuseTest.java
index 6bb66684a70..c514c25cf63 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectIndexReuseTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectIndexReuseTest.java
@@ -2,8 +2,10 @@
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
@@ -18,2014 +20,2416 @@
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
-@Test(groups = {"index"})
+@Test(groups = { "index" })
public class SQLSelectIndexReuseTest extends AbstractIndexReuseTest {
- @Parameters(value = "url")
- public SQLSelectIndexReuseTest(final String iURL) {
- super(iURL);
- }
-
- @BeforeClass
- public void beforeClass() throws Exception {
- if (database.isClosed()) {
- database.open("admin", "admin");
- }
-
- final OSchema schema = database.getMetadata().getSchema();
- final OClass oClass = schema.createClass("sqlSelectIndexReuseTestClass");
-
- oClass.createProperty("prop1", OType.INTEGER);
- oClass.createProperty("prop2", OType.INTEGER);
- oClass.createProperty("prop3", OType.INTEGER);
- oClass.createProperty("prop4", OType.INTEGER);
- oClass.createProperty("prop5", OType.INTEGER);
- oClass.createProperty("prop6", OType.INTEGER);
- oClass.createProperty("prop7", OType.STRING);
- oClass.createProperty("fEmbeddedMap", OType.EMBEDDEDMAP, OType.INTEGER);
- oClass.createProperty("fLinkMap", OType.LINKMAP);
- oClass.createProperty("fEmbeddedList", OType.EMBEDDEDLIST, OType.INTEGER);
- oClass.createProperty("fLinkList", OType.LINKLIST);
-
- oClass.createIndex("indexone", OClass.INDEX_TYPE.UNIQUE, "prop1", "prop2");
- oClass.createIndex("indextwo", OClass.INDEX_TYPE.UNIQUE, "prop3");
- oClass.createIndex("indexthree", OClass.INDEX_TYPE.NOTUNIQUE, "prop1", "prop2", "prop4");
- oClass.createIndex("indexfour", OClass.INDEX_TYPE.NOTUNIQUE, "prop4", "prop1", "prop3");
- oClass.createIndex("indexfive", OClass.INDEX_TYPE.NOTUNIQUE, "prop6", "prop1", "prop3");
- oClass.createIndex("indexsix", OClass.INDEX_TYPE.FULLTEXT, "prop7");
- oClass.createIndex("sqlSelectIndexReuseTestEmbeddedMapByKey", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedMap");
- oClass.createIndex("sqlSelectIndexReuseTestEmbeddedMapByValue", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedMap by value");
- oClass.createIndex("sqlSelectIndexReuseTestEmbeddedList", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedList");
-
- schema.save();
-
- final String fullTextIndexStrings[] = {"Alice : What is the use of a book, without pictures or conversations?",
- "Rabbit : Oh my ears and whiskers, how late it's getting!",
- "Alice : If it had grown up, it would have made a dreadfully ugly child; but it makes rather a handsome pig, I think",
- "The Cat : We're all mad here.", "The Hatter : Why is a raven like a writing desk?",
- "The Hatter : Twinkle, twinkle, little bat! How I wonder what you're at.", "The Queen : Off with her head!",
- "The Duchess : Tut, tut, child! Everything's got a moral, if only you can find it.",
- "The Duchess : Take care of the sense, and the sounds will take care of themselves.",
- "The King : Begin at the beginning and go on till you come to the end: then stop."};
-
- for (int i = 0; i < 10; i++) {
- final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
-
- embeddedMap.put("key" + (i * 10 + 1), i * 10 + 1);
- embeddedMap.put("key" + (i * 10 + 2), i * 10 + 2);
- embeddedMap.put("key" + (i * 10 + 3), i * 10 + 3);
- embeddedMap.put("key" + (i * 10 + 4), i * 10 + 1);
-
- final List<Integer> embeddedList = new ArrayList<Integer>(3);
- embeddedList.add(i * 3);
- embeddedList.add(i * 3 + 1);
- embeddedList.add(i * 3 + 2);
-
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument("sqlSelectIndexReuseTestClass");
- document.field("prop1", i);
- document.field("prop2", j);
- document.field("prop3", i * 10 + j);
-
- document.field("prop4", i);
- document.field("prop5", i);
-
- document.field("prop6", j);
-
- document.field("prop7", fullTextIndexStrings[i]);
-
- document.field("fEmbeddedMap", embeddedMap);
-
- document.field("fEmbeddedList", embeddedList);
-
- document.save();
- }
- }
- database.close();
- }
-
- @AfterClass
- public void afterClass() throws Exception {
- if (database.isClosed()) {
- database.open("admin", "admin");
- }
-
- database.command(new OCommandSQL("drop class sqlSelectIndexReuseTestClass")).execute();
- database.getMetadata().getSchema().reload();
- database.getLevel2Cache().clear();
-
- database.close();
- }
-
- @Test
- public void testCompositeSearchEquals() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 2")).execute();
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 2);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchHasChainOperatorsEquals() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1.asInteger() = 1 and prop2 = 2"))
- .execute();
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 2);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchEqualsOneField() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1")).execute();
-
- Assert.assertEquals(result.size(), 10);
-
- for (int i = 0; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testNoCompositeSearchEquals() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 = 1")).execute();
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- Assert.assertEquals(result.size(), 10);
-
- for (int i = 0; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", 1);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- @Test
- public void testCompositeSearchEqualsWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 = ?")).execute(1, 2);
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 2);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchEqualsOneFieldWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ?")).execute(1);
-
- Assert.assertEquals(result.size(), 10);
-
- for (int i = 0; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testNoCompositeSearchEqualsWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 = ?")).execute(1);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- Assert.assertEquals(result.size(), 10);
-
- for (int i = 0; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", 1);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- @Test
- public void testCompositeSearchGT() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 > 2")).execute();
-
- Assert.assertEquals(result.size(), 7);
-
- for (int i = 3; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchGTOneField() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 > 7")).execute();
-
- Assert.assertEquals(result.size(), 20);
-
- for (int i = 8; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchGTOneFieldNoSearch() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 > 7")).execute();
-
- Assert.assertEquals(result.size(), 20);
-
- for (int i = 8; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchGTWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 > ?")).execute(1, 2);
-
- Assert.assertEquals(result.size(), 7);
-
- for (int i = 3; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchGTOneFieldWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 > ?")).execute(7);
-
- Assert.assertEquals(result.size(), 20);
-
- for (int i = 8; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchGTOneFieldNoSearchWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 > ?")).execute(7);
-
- Assert.assertEquals(result.size(), 20);
-
- for (int i = 8; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchGTQ() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 >= 2")).execute();
-
- Assert.assertEquals(result.size(), 8);
-
- for (int i = 2; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchGTQOneField() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 >= 7")).execute();
-
- Assert.assertEquals(result.size(), 30);
-
- for (int i = 7; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchGTQOneFieldNoSearch() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 >= 7")).execute();
-
- Assert.assertEquals(result.size(), 30);
-
- for (int i = 7; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchGTQWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 >= ?")).execute(1, 2);
-
- Assert.assertEquals(result.size(), 8);
-
- for (int i = 2; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchGTQOneFieldWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 >= ?")).execute(7);
-
- Assert.assertEquals(result.size(), 30);
-
- for (int i = 7; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchGTQOneFieldNoSearchWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 >= ?")).execute(7);
-
- Assert.assertEquals(result.size(), 30);
-
- for (int i = 7; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchLTQ() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 <= 2")).execute();
-
- Assert.assertEquals(result.size(), 3);
-
- for (int i = 0; i <= 2; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
-
- }
-
- @Test
- public void testCompositeSearchLTQOneField() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 <= 7")).execute();
-
- Assert.assertEquals(result.size(), 80);
-
- for (int i = 0; i <= 7; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchLTQOneFieldNoSearch() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 <= 7")).execute();
-
- Assert.assertEquals(result.size(), 80);
-
- for (int i = 0; i <= 7; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchLTQWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 <= ?")).execute(1, 2);
-
- Assert.assertEquals(result.size(), 3);
-
- for (int i = 0; i <= 2; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchLTQOneFieldWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 <= ?")).execute(7);
-
- Assert.assertEquals(result.size(), 80);
-
- for (int i = 0; i <= 7; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchLTQOneFieldNoSearchWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 <= ?")).execute(7);
-
- Assert.assertEquals(result.size(), 80);
-
- for (int i = 0; i <= 7; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchLT() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 < 2")).execute();
-
- Assert.assertEquals(result.size(), 2);
-
- for (int i = 0; i < 2; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchLTOneField() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 < 7")).execute();
-
- Assert.assertEquals(result.size(), 70);
-
- for (int i = 0; i < 7; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchLTOneFieldNoSearch() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 < 7")).execute();
-
- Assert.assertEquals(result.size(), 70);
-
- for (int i = 0; i < 7; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchLTWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 < ?")).execute(1, 2);
-
- Assert.assertEquals(result.size(), 2);
-
- for (int i = 0; i < 2; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchLTOneFieldWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 < ?")).execute(7);
-
- Assert.assertEquals(result.size(), 70);
-
- for (int i = 0; i < 7; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchLTOneFieldNoSearchWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 < ?")).execute(7);
-
- Assert.assertEquals(result.size(), 70);
-
- for (int i = 0; i < 7; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchBetween() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 between 1 and 3"))
- .execute();
-
- Assert.assertEquals(result.size(), 3);
-
- for (int i = 1; i <= 3; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchBetweenOneField() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 between 1 and 3")).execute();
-
- Assert.assertEquals(result.size(), 30);
-
- for (int i = 1; i <= 3; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchBetweenOneFieldNoSearch() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 between 1 and 3")).execute();
-
- Assert.assertEquals(result.size(), 30);
-
- for (int i = 1; i <= 3; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testCompositeSearchBetweenWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 between ? and ?"))
- .execute(1, 3);
-
- Assert.assertEquals(result.size(), 3);
-
- for (int i = 1; i <= 3; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchBetweenOneFieldWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 between ? and ?")).execute(1, 3);
-
- Assert.assertEquals(result.size(), 30);
-
- for (int i = 1; i <= 3; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", i);
- document.field("prop2", j);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testCompositeSearchBetweenOneFieldNoSearchWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 between ? and ?")).execute(1, 3);
-
- Assert.assertEquals(result.size(), 30);
-
- for (int i = 1; i <= 3; i++) {
- for (int j = 0; j < 10; j++) {
- final ODocument document = new ODocument();
- document.field("prop1", j);
- document.field("prop2", i);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- @Test
- public void testSingleSearchEquals() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 = 1")).execute();
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop3").intValue(), 1);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testSingleSearchEqualsWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 = ?")).execute(1);
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop3").intValue(), 1);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testSingleSearchGT() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 > 90")).execute();
+ @Parameters(value = "url")
+ public SQLSelectIndexReuseTest(final String iURL) {
+ super(iURL);
+ }
- Assert.assertEquals(result.size(), 9);
+ @BeforeClass
+ public void beforeClass() throws Exception {
+ if (database.isClosed()) {
+ database.open("admin", "admin");
+ }
- for (int i = 91; i < 100; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
+ final OSchema schema = database.getMetadata().getSchema();
+ final OClass oClass = schema.createClass("sqlSelectIndexReuseTestClass");
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testSingleSearchGTWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ oClass.createProperty("prop1", OType.INTEGER);
+ oClass.createProperty("prop2", OType.INTEGER);
+ oClass.createProperty("prop3", OType.INTEGER);
+ oClass.createProperty("prop4", OType.INTEGER);
+ oClass.createProperty("prop5", OType.INTEGER);
+ oClass.createProperty("prop6", OType.INTEGER);
+ oClass.createProperty("prop7", OType.STRING);
+ oClass.createProperty("prop8", OType.INTEGER);
+ oClass.createProperty("prop9", OType.INTEGER);
+
+ oClass.createProperty("fEmbeddedMap", OType.EMBEDDEDMAP, OType.INTEGER);
+ oClass.createProperty("fEmbeddedMapTwo", OType.EMBEDDEDMAP, OType.INTEGER);
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ oClass.createProperty("fLinkMap", OType.LINKMAP);
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 > ?")).execute(90);
+ oClass.createProperty("fEmbeddedList", OType.EMBEDDEDLIST, OType.INTEGER);
+ oClass.createProperty("fEmbeddedListTwo", OType.EMBEDDEDLIST, OType.INTEGER);
- Assert.assertEquals(result.size(), 9);
+ oClass.createProperty("fLinkList", OType.LINKLIST);
- for (int i = 91; i < 100; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
+ oClass.createProperty("fEmbeddedSet", OType.EMBEDDEDSET, OType.INTEGER);
+ oClass.createProperty("fEmbeddedSetTwo", OType.EMBEDDEDSET, OType.INTEGER);
+
+ oClass.createIndex("indexone", OClass.INDEX_TYPE.UNIQUE, "prop1", "prop2");
+ oClass.createIndex("indextwo", OClass.INDEX_TYPE.UNIQUE, "prop3");
+ oClass.createIndex("indexthree", OClass.INDEX_TYPE.NOTUNIQUE, "prop1", "prop2", "prop4");
+ oClass.createIndex("indexfour", OClass.INDEX_TYPE.NOTUNIQUE, "prop4", "prop1", "prop3");
+ oClass.createIndex("indexfive", OClass.INDEX_TYPE.NOTUNIQUE, "prop6", "prop1", "prop3");
+ oClass.createIndex("indexsix", OClass.INDEX_TYPE.FULLTEXT, "prop7");
+
+ oClass.createIndex("sqlSelectIndexReuseTestEmbeddedMapByKey", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedMap");
+ oClass.createIndex("sqlSelectIndexReuseTestEmbeddedMapByValue", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedMap by value");
+ oClass.createIndex("sqlSelectIndexReuseTestEmbeddedList", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedList");
+
+ oClass.createIndex("sqlSelectIndexReuseTestEmbeddedMapByKeyProp8", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedMapTwo", "prop8");
+ oClass.createIndex("sqlSelectIndexReuseTestEmbeddedMapByValueProp8", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedMapTwo by value",
+ "prop8");
+
+ oClass.createIndex("sqlSelectIndexReuseTestEmbeddedSetProp8", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedSetTwo", "prop8");
+ oClass.createIndex("sqlSelectIndexReuseTestProp9EmbeddedSetProp8", OClass.INDEX_TYPE.NOTUNIQUE, "prop9", "fEmbeddedSetTwo",
+ "prop8");
+
+ oClass.createIndex("sqlSelectIndexReuseTestEmbeddedListTwoProp8", OClass.INDEX_TYPE.NOTUNIQUE, "fEmbeddedListTwo", "prop8");
+
+ schema.save();
+
+ final String fullTextIndexStrings[] = { "Alice : What is the use of a book, without pictures or conversations?",
+ "Rabbit : Oh my ears and whiskers, how late it's getting!",
+ "Alice : If it had grown up, it would have made a dreadfully ugly child; but it makes rather a handsome pig, I think",
+ "The Cat : We're all mad here.", "The Hatter : Why is a raven like a writing desk?",
+ "The Hatter : Twinkle, twinkle, little bat! How I wonder what you're at.", "The Queen : Off with her head!",
+ "The Duchess : Tut, tut, child! Everything's got a moral, if only you can find it.",
+ "The Duchess : Take care of the sense, and the sounds will take care of themselves.",
+ "The King : Begin at the beginning and go on till you come to the end: then stop." };
+
+ for (int i = 0; i < 10; i++) {
+ final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+
+ embeddedMap.put("key" + (i * 10 + 1), i * 10 + 1);
+ embeddedMap.put("key" + (i * 10 + 2), i * 10 + 2);
+ embeddedMap.put("key" + (i * 10 + 3), i * 10 + 3);
+ embeddedMap.put("key" + (i * 10 + 4), i * 10 + 1);
+
+ final List<Integer> embeddedList = new ArrayList<Integer>(3);
+ embeddedList.add(i * 3);
+ embeddedList.add(i * 3 + 1);
+ embeddedList.add(i * 3 + 2);
+
+ final Set<Integer> embeddedSet = new HashSet<Integer>();
+ embeddedSet.add(i * 10);
+ embeddedSet.add(i * 10 + 1);
+ embeddedSet.add(i * 10 + 2);
+
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument("sqlSelectIndexReuseTestClass");
+ document.field("prop1", i);
+ document.field("prop2", j);
+ document.field("prop3", i * 10 + j);
+
+ document.field("prop4", i);
+ document.field("prop5", i);
+
+ document.field("prop6", j);
+
+ document.field("prop7", fullTextIndexStrings[i]);
+
+ document.field("prop8", j);
+
+ document.field("prop9", j % 2);
+
+ document.field("fEmbeddedMap", embeddedMap);
+ document.field("fEmbeddedMapTwo", embeddedMap);
+
+ document.field("fEmbeddedList", embeddedList);
+ document.field("fEmbeddedListTwo", embeddedList);
+
+ document.field("fEmbeddedSet", embeddedSet);
+ document.field("fEmbeddedSetTwo", embeddedSet);
+
+ document.save();
+ }
+ }
+ database.close();
+ }
+
+ @AfterClass
+ public void afterClass() throws Exception {
+ if (database.isClosed()) {
+ database.open("admin", "admin");
+ }
+
+ database.command(new OCommandSQL("drop class sqlSelectIndexReuseTestClass")).execute();
+ database.getMetadata().getSchema().reload();
+ database.getLevel2Cache().clear();
+
+ database.close();
+ }
+
+ @Test
+ public void testCompositeSearchEquals() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 2")).execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 2);
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchHasChainOperatorsEquals() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1.asInteger() = 1 and prop2 = 2"))
+ .execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 2);
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsOneField() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage21 = profiler.getCounter("Query.compositeIndexUsage.2.1");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1)
+ oldCompositeIndexUsage2 = 0;
+
+ if (oldCompositeIndexUsage21 == -1)
+ oldCompositeIndexUsage2 = 0;
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1")).execute();
+
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2.1"), oldCompositeIndexUsage21 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsOneFieldMapIndexByKey() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage21 = profiler.getCounter("Query.compositeIndexUsage.2.1");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+
+ if (oldCompositeIndexUsage2 == -1)
+ oldCompositeIndexUsage2 = 0;
+
+ if (oldCompositeIndexUsage21 == -1)
+ oldCompositeIndexUsage21 = 0;
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where fEmbeddedMapTwo containsKey 'key11'"))
+ .execute();
+
+ Assert.assertEquals(result.size(), 10);
+
+ final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+
+ embeddedMap.put("key11", 11);
+ embeddedMap.put("key12", 12);
+ embeddedMap.put("key13", 13);
+ embeddedMap.put("key14", 11);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop8", 1);
+ document.field("fEmbeddedMapTwo", embeddedMap);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2.1"), oldCompositeIndexUsage21 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsMapIndexByKey() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage22 = profiler.getCounter("Query.compositeIndexUsage.2.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ if (oldCompositeIndexUsage22 == -1)
+ oldCompositeIndexUsage22 = 0;
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass "
+ + "where prop8 = 1 and fEmbeddedMapTwo containsKey 'key11'")).execute();
+
+ final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+
+ embeddedMap.put("key11", 11);
+ embeddedMap.put("key12", 12);
+ embeddedMap.put("key13", 13);
+ embeddedMap.put("key14", 11);
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = new ODocument();
+ document.field("prop8", 1);
+ document.field("fEmbeddedMap", embeddedMap);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2.2"), oldCompositeIndexUsage22 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsOneFieldMapIndexByValue() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage21 = profiler.getCounter("Query.compositeIndexUsage.2.1");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+ if (oldCompositeIndexUsage21 == -1) {
+ oldCompositeIndexUsage21 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass " + "where fEmbeddedMapTwo containsValue 22"))
+ .execute();
+
+ final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+
+ embeddedMap.put("key21", 21);
+ embeddedMap.put("key22", 22);
+ embeddedMap.put("key23", 23);
+ embeddedMap.put("key24", 21);
+
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop8", i);
+ document.field("fEmbeddedMapTwo", embeddedMap);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2.1"), oldCompositeIndexUsage21 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsMapIndexByValue() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage22 = profiler.getCounter("Query.compositeIndexUsage.2.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+ if (oldCompositeIndexUsage22 == -1)
+ oldCompositeIndexUsage22 = 0;
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass "
+ + "where prop8 = 1 and fEmbeddedMapTwo containsValue 22")).execute();
+
+ final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+
+ embeddedMap.put("key21", 21);
+ embeddedMap.put("key22", 22);
+ embeddedMap.put("key23", 23);
+ embeddedMap.put("key24", 21);
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = new ODocument();
+ document.field("prop8", 1);
+ document.field("fEmbeddedMap", embeddedMap);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2.2"), oldCompositeIndexUsage22 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsEmbeddedSetIndex() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage22 = profiler.getCounter("Query.compositeIndexUsage.2.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ if (oldCompositeIndexUsage22 == -1)
+ oldCompositeIndexUsage22 = 0;
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass "
+ + "where prop8 = 1 and fEmbeddedSetTwo contains 12")).execute();
+
+ final Set<Integer> embeddedSet = new HashSet<Integer>();
+ embeddedSet.add(10);
+ embeddedSet.add(11);
+ embeddedSet.add(12);
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = new ODocument();
+ document.field("prop8", 1);
+ document.field("fEmbeddedSet", embeddedSet);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2.2"), oldCompositeIndexUsage22 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsEmbeddedSetInMiddleIndex() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage3 = profiler.getCounter("Query.compositeIndexUsage.3");
+ long oldCompositeIndexUsage33 = profiler.getCounter("Query.compositeIndexUsage.3.3");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ if (oldCompositeIndexUsage3 == -1)
+ oldCompositeIndexUsage3 = 0;
+
+ if (oldCompositeIndexUsage33 == -1)
+ oldCompositeIndexUsage33 = 0;
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass "
+ + "where prop9 = 0 and fEmbeddedSetTwo contains 92 and prop8 > 2")).execute();
+
+ final Set<Integer> embeddedSet = new HashSet<Integer>(3);
+ embeddedSet.add(90);
+ embeddedSet.add(91);
+ embeddedSet.add(92);
+
+ Assert.assertEquals(result.size(), 3);
+
+ for (int i = 0; i < 3; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop8", i * 2 + 4);
+ document.field("prop9", 0);
+ document.field("fEmbeddedSet", embeddedSet);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.3"), oldCompositeIndexUsage3 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.3.3"), oldCompositeIndexUsage33 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsOneFieldEmbeddedListIndex() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage21 = profiler.getCounter("Query.compositeIndexUsage.2.1");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+
+ if (oldCompositeIndexUsage2 == -1)
+ oldCompositeIndexUsage2 = 0;
+
+ if (oldCompositeIndexUsage21 == -1)
+ oldCompositeIndexUsage21 = 0;
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where fEmbeddedListTwo contains 4")).execute();
+
+ Assert.assertEquals(result.size(), 10);
+
+ final List<Integer> embeddedList = new ArrayList<Integer>(3);
+ embeddedList.add(3);
+ embeddedList.add(4);
+ embeddedList.add(5);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop8", i);
+ document.field("fEmbeddedListTwo", embeddedList);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2.1"), oldCompositeIndexUsage21 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsEmbeddedListIndex() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ long oldCompositeIndexUsage22 = profiler.getCounter("Query.compositeIndexUsage.2.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+ if (oldCompositeIndexUsage22 == -1)
+ oldCompositeIndexUsage22 = 0;
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where"
+ + " prop8 = 1 and fEmbeddedListTwo contains 4")).execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final List<Integer> embeddedList = new ArrayList<Integer>(3);
+ embeddedList.add(3);
+ embeddedList.add(4);
+ embeddedList.add(5);
+
+ final ODocument document = new ODocument();
+ document.field("prop8", 1);
+ document.field("fEmbeddedListTwo", embeddedList);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2.2"), oldCompositeIndexUsage22 + 1);
+ }
+
+ @Test
+ public void testNoCompositeSearchEquals() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 = 1")).execute();
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", 1);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ @Test
+ public void testCompositeSearchEqualsWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 = ?")).execute(1, 2);
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 2);
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchEqualsOneFieldWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ?")).execute(1);
+
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testNoCompositeSearchEqualsWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 = ?")).execute(1);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", 1);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ @Test
+ public void testCompositeSearchGT() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 > 2")).execute();
+
+ Assert.assertEquals(result.size(), 7);
+
+ for (int i = 3; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchGTOneField() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 > 7")).execute();
+
+ Assert.assertEquals(result.size(), 20);
+
+ for (int i = 8; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchGTOneFieldNoSearch() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 > 7")).execute();
+
+ Assert.assertEquals(result.size(), 20);
+
+ for (int i = 8; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchGTWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 > ?")).execute(1, 2);
+
+ Assert.assertEquals(result.size(), 7);
+
+ for (int i = 3; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchGTOneFieldWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 > ?")).execute(7);
+
+ Assert.assertEquals(result.size(), 20);
+
+ for (int i = 8; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchGTOneFieldNoSearchWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 > ?")).execute(7);
+
+ Assert.assertEquals(result.size(), 20);
+
+ for (int i = 8; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchGTQ() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 >= 2")).execute();
+
+ Assert.assertEquals(result.size(), 8);
+
+ for (int i = 2; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchGTQOneField() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 >= 7")).execute();
+
+ Assert.assertEquals(result.size(), 30);
+
+ for (int i = 7; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchGTQOneFieldNoSearch() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 >= 7")).execute();
+
+ Assert.assertEquals(result.size(), 30);
+
+ for (int i = 7; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchGTQWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 >= ?")).execute(1, 2);
+
+ Assert.assertEquals(result.size(), 8);
+
+ for (int i = 2; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchGTQOneFieldWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 >= ?")).execute(7);
+
+ Assert.assertEquals(result.size(), 30);
+
+ for (int i = 7; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchGTQOneFieldNoSearchWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 >= ?")).execute(7);
+
+ Assert.assertEquals(result.size(), 30);
+
+ for (int i = 7; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchLTQ() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 <= 2")).execute();
+
+ Assert.assertEquals(result.size(), 3);
+
+ for (int i = 0; i <= 2; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+
+ }
+
+ @Test
+ public void testCompositeSearchLTQOneField() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 <= 7")).execute();
+
+ Assert.assertEquals(result.size(), 80);
+
+ for (int i = 0; i <= 7; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchLTQOneFieldNoSearch() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 <= 7")).execute();
+
+ Assert.assertEquals(result.size(), 80);
+
+ for (int i = 0; i <= 7; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchLTQWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 <= ?")).execute(1, 2);
+
+ Assert.assertEquals(result.size(), 3);
+
+ for (int i = 0; i <= 2; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchLTQOneFieldWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 <= ?")).execute(7);
+
+ Assert.assertEquals(result.size(), 80);
+
+ for (int i = 0; i <= 7; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchLTQOneFieldNoSearchWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 <= ?")).execute(7);
+
+ Assert.assertEquals(result.size(), 80);
+
+ for (int i = 0; i <= 7; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchLT() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 < 2")).execute();
+
+ Assert.assertEquals(result.size(), 2);
+
+ for (int i = 0; i < 2; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchLTOneField() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 < 7")).execute();
+
+ Assert.assertEquals(result.size(), 70);
+
+ for (int i = 0; i < 7; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchLTOneFieldNoSearch() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 < 7")).execute();
+
+ Assert.assertEquals(result.size(), 70);
+
+ for (int i = 0; i < 7; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchLTWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = ? and prop2 < ?")).execute(1, 2);
+
+ Assert.assertEquals(result.size(), 2);
+
+ for (int i = 0; i < 2; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchLTOneFieldWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 < ?")).execute(7);
+
+ Assert.assertEquals(result.size(), 70);
+
+ for (int i = 0; i < 7; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchLTOneFieldNoSearchWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 < ?")).execute(7);
+
+ Assert.assertEquals(result.size(), 70);
+
+ for (int i = 0; i < 7; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchBetween() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 between 1 and 3"))
+ .execute();
+
+ Assert.assertEquals(result.size(), 3);
+
+ for (int i = 1; i <= 3; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchBetweenOneField() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 between 1 and 3")).execute();
+
+ Assert.assertEquals(result.size(), 30);
+
+ for (int i = 1; i <= 3; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchBetweenOneFieldNoSearch() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 between 1 and 3")).execute();
+
+ Assert.assertEquals(result.size(), 30);
+
+ for (int i = 1; i <= 3; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testCompositeSearchBetweenWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 between ? and ?"))
+ .execute(1, 3);
+
+ Assert.assertEquals(result.size(), 3);
+
+ for (int i = 1; i <= 3; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchBetweenOneFieldWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 between ? and ?")).execute(1, 3);
+
+ Assert.assertEquals(result.size(), 30);
+
+ for (int i = 1; i <= 3; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", i);
+ document.field("prop2", j);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testCompositeSearchBetweenOneFieldNoSearchWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop2 between ? and ?")).execute(1, 3);
+
+ Assert.assertEquals(result.size(), 30);
+
+ for (int i = 1; i <= 3; i++) {
+ for (int j = 0; j < 10; j++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", j);
+ document.field("prop2", i);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchEquals() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 = 1")).execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop3").intValue(), 1);
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchEqualsWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 = ?")).execute(1);
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop3").intValue(), 1);
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchGT() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 > 90")).execute();
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testSingleSearchGTQ() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ Assert.assertEquals(result.size(), 9);
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ for (int i = 91; i < 100; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 >= 90")).execute();
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchGTWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- Assert.assertEquals(result.size(), 10);
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- for (int i = 90; i < 100; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 > ?")).execute(90);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
+ Assert.assertEquals(result.size(), 9);
- @Test
- public void testSingleSearchGTQWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ for (int i = 91; i < 100; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchGTQ() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 >= ?")).execute(90);
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- Assert.assertEquals(result.size(), 10);
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 >= 90")).execute();
- for (int i = 90; i < 100; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
+ Assert.assertEquals(result.size(), 10);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testSingleSearchLTQ() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ for (int i = 90; i < 100; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 <= 10")).execute();
+ @Test
+ public void testSingleSearchGTQWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- Assert.assertEquals(result.size(), 11);
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- for (int i = 0; i <= 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 >= ?")).execute(90);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
+ Assert.assertEquals(result.size(), 10);
- @Test
- public void testSingleSearchLTQWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ for (int i = 90; i < 100; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchLTQ() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 <= ?")).execute(10);
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- Assert.assertEquals(result.size(), 11);
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 <= 10")).execute();
- for (int i = 0; i <= 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
+ Assert.assertEquals(result.size(), 11);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
+ for (int i = 0; i <= 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
- @Test
- public void testSingleSearchLT() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ @Test
+ public void testSingleSearchLTQWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 < 10")).execute();
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- Assert.assertEquals(result.size(), 10);
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 <= ?")).execute(10);
- for (int i = 0; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
+ Assert.assertEquals(result.size(), 11);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
+ for (int i = 0; i <= 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
- @Test
- public void testSingleSearchLTWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ @Test
+ public void testSingleSearchLT() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 < ?")).execute(10);
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- Assert.assertEquals(result.size(), 10);
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 < 10")).execute();
- for (int i = 0; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
+ Assert.assertEquals(result.size(), 10);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
- @Test
- public void testSingleSearchBetween() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 between 1 and 10")).execute();
-
- Assert.assertEquals(result.size(), 10);
-
- for (int i = 1; i <= 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testSingleSearchBetweenWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 between ? and ?")).execute(1, 10);
-
- Assert.assertEquals(result.size(), 10);
-
- for (int i = 1; i <= 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testSingleSearchIN() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 in [0, 5, 10]")).execute();
-
- Assert.assertEquals(result.size(), 3);
-
- for (int i = 0; i <= 10; i += 5) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testSingleSearchINWithArgs() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 in [?, ?, ?]")).execute(0, 5, 10);
-
- Assert.assertEquals(result.size(), 3);
-
- for (int i = 0; i <= 10; i += 5) {
- final ODocument document = new ODocument();
- document.field("prop3", i);
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testMostSpecificOnesProcessedFirst() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 1 and prop3 = 11"))
- .execute();
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop3").intValue(), 11);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testTripleSearch() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage3 = profiler.getCounter("Query.compositeIndexUsage.3");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage3 == -1) {
- oldCompositeIndexUsage3 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 1 and prop4 >= 1"))
- .execute();
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop4").intValue(), 1);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.3"), oldCompositeIndexUsage3 + 1);
- }
-
- @Test
- public void testTripleSearchLastFieldNotInIndexFirstCase() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 1 and prop5 >= 1"))
- .execute();
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop5").intValue(), 1);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testTripleSearchLastFieldNotInIndexSecondCase() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop4 >= 1")).execute();
-
- Assert.assertEquals(result.size(), 10);
-
- for (int i = 0; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
- document.field("prop4", 1);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testTripleSearchLastFieldInIndex() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage3 = profiler.getCounter("Query.compositeIndexUsage.3");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage3 == -1) {
- oldCompositeIndexUsage3 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop4 = 1")).execute();
-
- Assert.assertEquals(result.size(), 10);
-
- for (int i = 0; i < 10; i++) {
- final ODocument document = new ODocument();
- document.field("prop1", 1);
- document.field("prop2", i);
- document.field("prop4", 1);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.3"), oldCompositeIndexUsage3 + 1);
- }
-
- @Test
- public void testTripleSearchLastFieldsCanNotBeMerged() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage3 = profiler.getCounter("Query.compositeIndexUsage.3");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage3 == -1) {
- oldCompositeIndexUsage3 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop6 <= 1 and prop4 < 1")).execute();
-
- Assert.assertEquals(result.size(), 2);
-
- for (int i = 0; i < 2; i++) {
- final ODocument document = new ODocument();
- document.field("prop6", i);
- document.field("prop4", 0);
-
- Assert.assertEquals(containsDocument(result, document), 1);
- }
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.3"), oldCompositeIndexUsage3 + 1);
- }
-
- @Test
- public void testFullTextIndex() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop7 containstext 'Alice' ")).execute();
-
- Assert.assertEquals(result.size(), 20);
-
- final ODocument docOne = new ODocument();
- docOne.field("prop7", "Alice : What is the use of a book, without pictures or conversations?");
- Assert.assertEquals(containsDocument(result, docOne), 10);
-
- final ODocument docTwo = new ODocument();
- docTwo.field("prop7",
- "Alice : If it had grown up, it would have made a dreadfully ugly child; but it makes rather a handsome pig, I think");
- Assert.assertEquals(containsDocument(result, docTwo), 10);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- }
-
- @Test
- public void testLastFieldNotCompatibleOperator() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 + 1 = 3")).execute();
+ @Test
+ public void testSingleSearchLTWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- Assert.assertEquals(result.size(), 1);
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 2);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 < ?")).execute(10);
- @Test
- public void testEmbeddedMapByKeyIndexReuse() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ Assert.assertEquals(result.size(), 10);
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where fEmbeddedMap containskey 'key12'"))
- .execute();
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
- Assert.assertEquals(result.size(), 10);
+ @Test
+ public void testSingleSearchBetween() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 between 1 and 10")).execute();
+
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 1; i <= 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchBetweenWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 between ? and ?")).execute(1, 10);
+
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 1; i <= 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchIN() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 in [0, 5, 10]")).execute();
+
+ Assert.assertEquals(result.size(), 3);
+
+ for (int i = 0; i <= 10; i += 5) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testSingleSearchINWithArgs() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop3 in [?, ?, ?]")).execute(0, 5, 10);
+
+ Assert.assertEquals(result.size(), 3);
+
+ for (int i = 0; i <= 10; i += 5) {
+ final ODocument document = new ODocument();
+ document.field("prop3", i);
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testMostSpecificOnesProcessedFirst() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 1 and prop3 = 11"))
+ .execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop3").intValue(), 11);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testTripleSearch() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage3 = profiler.getCounter("Query.compositeIndexUsage.3");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage3 == -1) {
+ oldCompositeIndexUsage3 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 1 and prop4 >= 1"))
+ .execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop4").intValue(), 1);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.3"), oldCompositeIndexUsage3 + 1);
+ }
+
+ @Test
+ public void testTripleSearchLastFieldNotInIndexFirstCase() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 1 and prop5 >= 1"))
+ .execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop5").intValue(), 1);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testTripleSearchLastFieldNotInIndexSecondCase() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop4 >= 1")).execute();
+
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+ document.field("prop4", 1);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testTripleSearchLastFieldInIndex() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage3 = profiler.getCounter("Query.compositeIndexUsage.3");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage3 == -1) {
+ oldCompositeIndexUsage3 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop4 = 1")).execute();
+
+ Assert.assertEquals(result.size(), 10);
+
+ for (int i = 0; i < 10; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop1", 1);
+ document.field("prop2", i);
+ document.field("prop4", 1);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.3"), oldCompositeIndexUsage3 + 1);
+ }
+
+ @Test
+ public void testTripleSearchLastFieldsCanNotBeMerged() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage3 = profiler.getCounter("Query.compositeIndexUsage.3");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage3 == -1) {
+ oldCompositeIndexUsage3 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop6 <= 1 and prop4 < 1")).execute();
+
+ Assert.assertEquals(result.size(), 2);
+
+ for (int i = 0; i < 2; i++) {
+ final ODocument document = new ODocument();
+ document.field("prop6", i);
+ document.field("prop4", 0);
+
+ Assert.assertEquals(containsDocument(result, document), 1);
+ }
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.3"), oldCompositeIndexUsage3 + 1);
+ }
+
+ @Test
+ public void testFullTextIndex() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop7 containstext 'Alice' ")).execute();
+
+ Assert.assertEquals(result.size(), 20);
+
+ final ODocument docOne = new ODocument();
+ docOne.field("prop7", "Alice : What is the use of a book, without pictures or conversations?");
+ Assert.assertEquals(containsDocument(result, docOne), 10);
+
+ final ODocument docTwo = new ODocument();
+ docTwo.field("prop7",
+ "Alice : If it had grown up, it would have made a dreadfully ugly child; but it makes rather a handsome pig, I think");
+ Assert.assertEquals(containsDocument(result, docTwo), 10);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ }
+
+ @Test
+ public void testLastFieldNotCompatibleOperator() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
- final ODocument document = new ODocument();
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 + 1 = 3")).execute();
- final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+ Assert.assertEquals(result.size(), 1);
- embeddedMap.put("key11", 11);
- embeddedMap.put("key12", 12);
- embeddedMap.put("key13", 13);
- embeddedMap.put("key14", 11);
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 2);
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
- document.field("fEmbeddedMap", embeddedMap);
+ @Test
+ public void testEmbeddedMapByKeyIndexReuse() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
- Assert.assertEquals(containsDocument(result, document), 10);
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
- }
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where fEmbeddedMap containskey 'key12'"))
+ .execute();
- @Test
- public void testEmbeddedMapBySpecificKeyIndexReuse() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ Assert.assertEquals(result.size(), 10);
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ final ODocument document = new ODocument();
- final List<ODocument> result = database
- .command(
- new OSQLSynchQuery<ODocument>(
- "select * from sqlSelectIndexReuseTestClass where ( fEmbeddedMap containskey 'key12' ) and ( fEmbeddedMap['key12'] = 12 )"))
- .execute();
+ final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
- Assert.assertEquals(result.size(), 10);
+ embeddedMap.put("key11", 11);
+ embeddedMap.put("key12", 12);
+ embeddedMap.put("key13", 13);
+ embeddedMap.put("key14", 11);
- final ODocument document = new ODocument();
+ document.field("fEmbeddedMap", embeddedMap);
- final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+ Assert.assertEquals(containsDocument(result, document), 10);
- embeddedMap.put("key11", 11);
- embeddedMap.put("key12", 12);
- embeddedMap.put("key13", 13);
- embeddedMap.put("key14", 11);
-
- document.field("fEmbeddedMap", embeddedMap);
-
- Assert.assertEquals(containsDocument(result, document), 10);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
- }
-
- @Test
- public void testEmbeddedMapByValueIndexReuse() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
+ }
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
+ @Test
+ public void testEmbeddedMapBySpecificKeyIndexReuse() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where fEmbeddedMap containsvalue 11")).execute();
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
- Assert.assertEquals(result.size(), 10);
+ final List<ODocument> result = database
+ .command(
+ new OSQLSynchQuery<ODocument>(
+ "select * from sqlSelectIndexReuseTestClass where ( fEmbeddedMap containskey 'key12' ) and ( fEmbeddedMap['key12'] = 12 )"))
+ .execute();
- final ODocument document = new ODocument();
+ Assert.assertEquals(result.size(), 10);
- final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+ final ODocument document = new ODocument();
- embeddedMap.put("key11", 11);
- embeddedMap.put("key12", 12);
- embeddedMap.put("key13", 13);
- embeddedMap.put("key14", 11);
-
- document.field("fEmbeddedMap", embeddedMap);
-
- Assert.assertEquals(containsDocument(result, document), 10);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
- }
-
- @Test
- public void testEmbeddedListIndexReuse() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where fEmbeddedList contains 7")).execute();
-
- final List<Integer> embeddedList = new ArrayList<Integer>(3);
- embeddedList.add(6);
- embeddedList.add(7);
- embeddedList.add(8);
-
- final ODocument document = new ODocument();
- document.field("fEmbeddedList", embeddedList);
-
- Assert.assertEquals(containsDocument(result, document), 10);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
- }
-
- @Test
- public void testNotIndexOperatorFirstCase() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>(
- "select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 2 and ( prop4 = 3 or prop4 = 1 )")).execute();
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 2);
- Assert.assertEquals(document.<Integer>field("prop4").intValue(), 1);
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
-
- @Test
- public void testNotIndexOperatorSecondCase() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>(
- "select * from sqlSelectIndexReuseTestClass where ( prop1 = 1 and prop2 = 2 ) or ( prop4 = 1 and prop6 = 2 )"))
- .execute();
-
- Assert.assertEquals(result.size(), 1);
-
- final ODocument document = result.get(0);
- Assert.assertEquals(document.<Integer>field("prop1").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop2").intValue(), 2);
- Assert.assertEquals(document.<Integer>field("prop4").intValue(), 1);
- Assert.assertEquals(document.<Integer>field("prop6").intValue(), 2);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
- }
-
- private int containsDocument(final List<ODocument> docList, final ODocument document) {
- int count = 0;
- for (final ODocument docItem : docList) {
- boolean containsAllFields = true;
- for (final String fieldName : document.fieldNames()) {
- if (!document.<Object>field(fieldName).equals(docItem.<Object>field(fieldName))) {
- containsAllFields = false;
- break;
- }
- }
- if (containsAllFields) {
- count++;
- }
- }
- return count;
- }
-
- @Test
- public void testCompositeIndexEmptyResult() {
- long oldIndexUsage = profiler.getCounter("Query.indexUsage");
- long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
- long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
-
- if (oldIndexUsage == -1) {
- oldIndexUsage = 0;
- }
- if (oldCompositeIndexUsage == -1) {
- oldCompositeIndexUsage = 0;
- }
- if (oldCompositeIndexUsage2 == -1) {
- oldCompositeIndexUsage2 = 0;
- }
-
- final List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>(
- "select * from sqlSelectIndexReuseTestClass where prop1 = 1777 and prop2 = 2777")).execute();
-
- Assert.assertEquals(result.size(), 0);
-
- Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
- Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
- }
+ final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+
+ embeddedMap.put("key11", 11);
+ embeddedMap.put("key12", 12);
+ embeddedMap.put("key13", 13);
+ embeddedMap.put("key14", 11);
+
+ document.field("fEmbeddedMap", embeddedMap);
+
+ Assert.assertEquals(containsDocument(result, document), 10);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
+ }
+
+ @Test
+ public void testEmbeddedMapByValueIndexReuse() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where fEmbeddedMap containsvalue 11")).execute();
+
+ Assert.assertEquals(result.size(), 10);
+
+ final ODocument document = new ODocument();
+
+ final Map<String, Integer> embeddedMap = new HashMap<String, Integer>();
+
+ embeddedMap.put("key11", 11);
+ embeddedMap.put("key12", 12);
+ embeddedMap.put("key13", 13);
+ embeddedMap.put("key14", 11);
+
+ document.field("fEmbeddedMap", embeddedMap);
+
+ Assert.assertEquals(containsDocument(result, document), 10);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
+ }
+
+ @Test
+ public void testEmbeddedListIndexReuse() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where fEmbeddedList contains 7")).execute();
+
+ final List<Integer> embeddedList = new ArrayList<Integer>(3);
+ embeddedList.add(6);
+ embeddedList.add(7);
+ embeddedList.add(8);
+
+ final ODocument document = new ODocument();
+ document.field("fEmbeddedList", embeddedList);
+
+ Assert.assertEquals(containsDocument(result, document), 10);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2);
+ }
+
+ @Test
+ public void testNotIndexOperatorFirstCase() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>(
+ "select * from sqlSelectIndexReuseTestClass where prop1 = 1 and prop2 = 2 and ( prop4 = 3 or prop4 = 1 )")).execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 2);
+ Assert.assertEquals(document.<Integer> field("prop4").intValue(), 1);
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
+
+ @Test
+ public void testNotIndexOperatorSecondCase() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>(
+ "select * from sqlSelectIndexReuseTestClass where ( prop1 = 1 and prop2 = 2 ) or ( prop4 = 1 and prop6 = 2 )"))
+ .execute();
+
+ Assert.assertEquals(result.size(), 1);
+
+ final ODocument document = result.get(0);
+ Assert.assertEquals(document.<Integer> field("prop1").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop2").intValue(), 2);
+ Assert.assertEquals(document.<Integer> field("prop4").intValue(), 1);
+ Assert.assertEquals(document.<Integer> field("prop6").intValue(), 2);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage);
+ }
+
+ private int containsDocument(final List<ODocument> docList, final ODocument document) {
+ int count = 0;
+ for (final ODocument docItem : docList) {
+ boolean containsAllFields = true;
+ for (final String fieldName : document.fieldNames()) {
+ if (!document.<Object> field(fieldName).equals(docItem.<Object> field(fieldName))) {
+ containsAllFields = false;
+ break;
+ }
+ }
+ if (containsAllFields) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ @Test
+ public void testCompositeIndexEmptyResult() {
+ long oldIndexUsage = profiler.getCounter("Query.indexUsage");
+ long oldCompositeIndexUsage = profiler.getCounter("Query.compositeIndexUsage");
+ long oldCompositeIndexUsage2 = profiler.getCounter("Query.compositeIndexUsage.2");
+
+ if (oldIndexUsage == -1) {
+ oldIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage == -1) {
+ oldCompositeIndexUsage = 0;
+ }
+ if (oldCompositeIndexUsage2 == -1) {
+ oldCompositeIndexUsage2 = 0;
+ }
+
+ final List<ODocument> result = database.command(
+ new OSQLSynchQuery<ODocument>("select * from sqlSelectIndexReuseTestClass where prop1 = 1777 and prop2 = 2777")).execute();
+
+ Assert.assertEquals(result.size(), 0);
+
+ Assert.assertEquals(profiler.getCounter("Query.indexUsage"), oldIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage"), oldCompositeIndexUsage + 1);
+ Assert.assertEquals(profiler.getCounter("Query.compositeIndexUsage.2"), oldCompositeIndexUsage2 + 1);
+ }
}
|
391e4b4c4ce7d9be1c0051614b970c85cce91c9f
|
restlet-framework-java
|
- Fixed plugin descriptors for some extensions.--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/build.number b/build.number
index 7a31427663..43097911f6 100644
--- a/build.number
+++ b/build.number
@@ -1,3 +1,3 @@
#Build Number for ANT. Do not edit!
-#Sun Oct 15 18:28:20 CEST 2006
-build.number=340
+#Mon Oct 16 14:37:01 CEST 2006
+build.number=341
diff --git a/plugins/internal/com.noelios.restlet.example/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.example/META-INF/MANIFEST.MF
index 3a3d86e53f..e79eac8b14 100644
--- a/plugins/internal/com.noelios.restlet.example/META-INF/MANIFEST.MF
+++ b/plugins/internal/com.noelios.restlet.example/META-INF/MANIFEST.MF
@@ -8,8 +8,8 @@ Bundle-Localization: plugin
Require-Bundle: org.restlet,
com.noelios.restlet,
com.noelios.restlet.ext.net,
- com.noelios.restlet.ext.jetty6;resolution:=optional,
com.noelios.restlet.ext.simple;resolution:=optional,
+ com.noelios.restlet.ext.jetty6;resolution:=optional,
com.noelios.restlet.ext.asyncweb;resolution:=optional,
org.apache.mina;resolution:=optional,
org.apache.commons.logging;resolution:=optional,
diff --git a/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/misc/SimpleServer.java b/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/misc/SimpleServer.java
index 4ef292b45c..2bd921295f 100644
--- a/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/misc/SimpleServer.java
+++ b/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/misc/SimpleServer.java
@@ -23,7 +23,6 @@
package com.noelios.restlet.example.misc;
import org.restlet.Container;
-import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
@@ -43,16 +42,15 @@ public static void main(String[] args)
try
{
// Create a new Restlet container
- Container myContainer = new Container();
- Context myContext = myContainer.getContext();
+ Container container = new Container();
// Create the HTTP server connector, then add it as a server
// connector to the Restlet container. Note that the container
// is the call restlet.
- myContainer.getServers().add(Protocol.HTTP, 9876);
+ container.getServers().add(Protocol.HTTP, 9876);
// Prepare and attach a test Restlet
- Restlet testRestlet = new Restlet(myContext)
+ Restlet handler = new Restlet(container.getContext())
{
public void handlePut(Request request, Response response)
{
@@ -78,10 +76,10 @@ public void handlePut(Request request, Response response)
}
};
- myContainer.getDefaultHost().attach("/test", testRestlet);
+ container.getDefaultHost().attach("/test", handler);
// Now, start the container
- myContainer.start();
+ container.start();
}
catch(Exception e)
{
diff --git a/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/tutorial/Tutorial05.java b/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/tutorial/Tutorial05.java
index a65dec98c5..795198ccb3 100644
--- a/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/tutorial/Tutorial05.java
+++ b/plugins/internal/com.noelios.restlet.example/src/com/noelios/restlet/example/tutorial/Tutorial05.java
@@ -38,11 +38,11 @@ public class Tutorial05
public static void main(String[] args) throws Exception
{
// Create a new Restlet container and add a HTTP server connector to it
- Container myContainer = new Container();
- myContainer.getServers().add(Protocol.HTTP, 8182);
+ Container container = new Container();
+ container.getServers().add(Protocol.HTTP, 8182);
// Create a new Restlet that will display some path information.
- Restlet myRestlet = new Restlet()
+ Restlet handler = new Restlet()
{
public void handleGet(Request request, Response response)
{
@@ -56,11 +56,11 @@ public void handleGet(Request request, Response response)
};
// Then attach it to the local host
- myContainer.getDefaultHost().attach("/trace", myRestlet);
+ container.getDefaultHost().attach("/trace", handler);
// Now, let's start the container!
// Note that the HTTP server connector is also automatically started.
- myContainer.start();
+ container.start();
}
}
diff --git a/plugins/internal/com.noelios.restlet.ext.jetty_6.0/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.ext.jetty_6.0/META-INF/MANIFEST.MF
index a45210028b..a2c10fbba7 100644
--- a/plugins/internal/com.noelios.restlet.ext.jetty_6.0/META-INF/MANIFEST.MF
+++ b/plugins/internal/com.noelios.restlet.ext.jetty_6.0/META-INF/MANIFEST.MF
@@ -9,3 +9,4 @@ Require-Bundle: org.restlet,
com.noelios.restlet,
javax.servlet5,
org.mortbay.jetty6
+Export-Package: com.noelios.restlet.ext.jetty
diff --git a/plugins/internal/com.noelios.restlet.ext.net/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.ext.net/META-INF/MANIFEST.MF
index c772339c84..d896bf6f3a 100644
--- a/plugins/internal/com.noelios.restlet.ext.net/META-INF/MANIFEST.MF
+++ b/plugins/internal/com.noelios.restlet.ext.net/META-INF/MANIFEST.MF
@@ -7,3 +7,4 @@ Bundle-Vendor: Noelios Consulting
Bundle-Localization: plugin
Require-Bundle: org.restlet,
com.noelios.restlet
+Export-Package: com.noelios.restlet.ext.net
diff --git a/plugins/internal/com.noelios.restlet.ext.servlet_2.4/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.ext.servlet_2.4/META-INF/MANIFEST.MF
index f80e299ed6..fa7b7d1afe 100644
--- a/plugins/internal/com.noelios.restlet.ext.servlet_2.4/META-INF/MANIFEST.MF
+++ b/plugins/internal/com.noelios.restlet.ext.servlet_2.4/META-INF/MANIFEST.MF
@@ -8,3 +8,4 @@ Bundle-Localization: plugin
Require-Bundle: org.restlet,
com.noelios.restlet,
javax.servlet4
+Export-Package: com.noelios.restlet.ext.servlet
diff --git a/plugins/internal/com.noelios.restlet.ext.servlet_2.4/src/com/noelios/restlet/ext/servlet/ServerServlet.java b/plugins/internal/com.noelios.restlet.ext.servlet_2.4/src/com/noelios/restlet/ext/servlet/ServerServlet.java
index a3d2d56df1..b1701d3c28 100644
--- a/plugins/internal/com.noelios.restlet.ext.servlet_2.4/src/com/noelios/restlet/ext/servlet/ServerServlet.java
+++ b/plugins/internal/com.noelios.restlet.ext.servlet_2.4/src/com/noelios/restlet/ext/servlet/ServerServlet.java
@@ -43,22 +43,21 @@
* <?xml version="1.0" encoding="ISO-8859-1"?>
* <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
* <web-app>
- * <display-name>Server Servlet</display-name>
- * <description>Servlet acting as a Restlet server connector</description>
+ * <display-name>Restlet adapter</display-name>
*
- * <!-- Application class handling calls -->
+ * <!-- Your application class name -->
* <context-param>
* <param-name>org.restlet.application</param-name>
* <param-value>com.noelios.restlet.test.TraceApplication</param-value>
* </context-param>
*
- * <!-- ServerServlet class or a subclass -->
+ * <!-- Restlet adapter -->
* <servlet>
* <servlet-name>ServerServlet</servlet-name>
* <servlet-class>com.noelios.restlet.ext.servlet.ServerServlet</servlet-class>
* </servlet>
*
- * <!-- Mapping of requests to the ServerServlet -->
+ * <!-- Catch all requests -->
* <servlet-mapping>
* <servlet-name>ServerServlet</servlet-name>
* <url-pattern>/*</url-pattern>
diff --git a/plugins/internal/com.noelios.restlet.ext.simple_3.1/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.ext.simple_3.1/META-INF/MANIFEST.MF
index f8146a7664..cb9f582bcd 100644
--- a/plugins/internal/com.noelios.restlet.ext.simple_3.1/META-INF/MANIFEST.MF
+++ b/plugins/internal/com.noelios.restlet.ext.simple_3.1/META-INF/MANIFEST.MF
@@ -8,3 +8,4 @@ Bundle-Localization: plugin
Require-Bundle: org.restlet,
com.noelios.restlet,
org.simpleframework;bundle-version="3.1.0"
+Export-Package: com.noelios.restlet.ext.simple
diff --git a/plugins/internal/com.noelios.restlet.test/META-INF/MANIFEST.MF b/plugins/internal/com.noelios.restlet.test/META-INF/MANIFEST.MF
index 248ea19fa2..4a1b9b2663 100644
--- a/plugins/internal/com.noelios.restlet.test/META-INF/MANIFEST.MF
+++ b/plugins/internal/com.noelios.restlet.test/META-INF/MANIFEST.MF
@@ -13,3 +13,4 @@ Require-Bundle: org.restlet,
com.noelios.restlet.ext.simple;resolution:=optional,
com.noelios.restlet.ext.asyncweb;resolution:=optional,
com.noelios.restlet.ext.atom
+Export-Package: com.noelios.restlet.test
|
a1bf55c5541b45552708fa76b04e24419604825b
|
camel
|
Minor cleanup--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@712728 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java
index f88b5bd99ee8c..120a7d63eba3e 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultUnitOfWork.java
@@ -38,7 +38,6 @@ public class DefaultUnitOfWork implements UnitOfWork, Service {
private String id;
private List<Synchronization> synchronizations;
private List<AsyncCallback> asyncCallbacks;
- private CountDownLatch latch;
public DefaultUnitOfWork() {
}
diff --git a/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java b/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java
index db5319995fc07..2d8d5760579af 100644
--- a/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java
+++ b/camel-core/src/main/java/org/apache/camel/management/CamelNamingStrategy.java
@@ -150,8 +150,15 @@ public ObjectName getObjectName(ManagedRoute mbean) throws MalformedObjectNameEx
public ObjectName getObjectName(RouteContext routeContext, ProcessorType processor)
throws MalformedObjectNameException {
Endpoint<? extends Exchange> ep = routeContext.getEndpoint();
- String ctxid = ep != null ? getContextId(ep.getCamelContext()) : VALUE_UNKNOWN;
- String cid = ObjectName.quote(ep.getEndpointUri());
+ String ctxid;
+ String cid;
+ if (ep != null) {
+ ctxid = getContextId(ep.getCamelContext());
+ cid = ObjectName.quote(ep.getEndpointUri());
+ } else {
+ ctxid = VALUE_UNKNOWN;
+ cid = null;
+ }
//String id = VALUE_UNKNOWN.equals(cid) ? ObjectName.quote(getEndpointId(ep) : "[" + cid + "]" + ObjectName.quote(getEndpointId(ep);
String nodeId = processor.idOrCreate();
diff --git a/camel-core/src/main/java/org/apache/camel/model/RouteType.java b/camel-core/src/main/java/org/apache/camel/model/RouteType.java
index 04307bb4712a1..ec3901c1e1469 100644
--- a/camel-core/src/main/java/org/apache/camel/model/RouteType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/RouteType.java
@@ -78,11 +78,9 @@ public String toString() {
public void addRoutes(CamelContext context, Collection<Route> routes) throws Exception {
setCamelContext(context);
- if (context instanceof CamelContext) {
- ErrorHandlerBuilder handler = context.getErrorHandlerBuilder();
- if (handler != null) {
- setErrorHandlerBuilderIfNull(handler);
- }
+ ErrorHandlerBuilder handler = context.getErrorHandlerBuilder();
+ if (handler != null) {
+ setErrorHandlerBuilderIfNull(handler);
}
for (FromType fromType : inputs) {
diff --git a/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java b/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java
index 83342f78bfe44..a076b572596e8 100644
--- a/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java
+++ b/camel-core/src/main/java/org/apache/camel/processor/interceptor/TraceInterceptor.java
@@ -120,8 +120,7 @@ protected void logException(Exchange exchange, Throwable throwable) {
* Returns true if the given exchange should be logged in the trace list
*/
protected boolean shouldLogExchange(Exchange exchange) {
- return (tracer == null || tracer.isEnabled())
- && (tracer.getTraceFilter() == null || tracer.getTraceFilter().matches(exchange));
+ return tracer.isEnabled() && (tracer.getTraceFilter() == null || tracer.getTraceFilter().matches(exchange));
}
/**
|
e5cf1be77c4ef3acf89436789f96fff8c081964f
|
drools
|
BZ743283: Decision tables should support timer- column instead of deprecated duration attribute--
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java
index e4ae8fc68f1..73cb78135c8 100644
--- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java
+++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java
@@ -38,6 +38,8 @@ public enum Code {
DESCRIPTION( "DESCRIPTION", "I" ),
SALIENCE( "PRIORITY", "P", 1 ),
DURATION( "DURATION", "D", 1 ),
+ TIMER( "TIMER", "T", 1 ),
+ CALENDARS( "CALENDARS", "E", 1 ),
NOLOOP( "NO-LOOP", "U", 1 ),
LOCKONACTIVE( "LOCK-ON-ACTIVE", "L", 1 ),
AUTOFOCUS( "AUTO-FOCUS", "F", 1 ),
diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java
index 18e87a9dfd5..1b9cfa9d465 100644
--- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java
+++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java
@@ -211,6 +211,12 @@ private Package buildRuleSet() {
getProperties().getSinglePropertyCell( code.getColHeader() ) );
}
break;
+ case TIMER:
+ ruleset.setTimer( value );
+ break;
+ case CALENDARS:
+ ruleset.setCalendars( value );
+ break;
case NOLOOP:
ruleset.setNoLoop( RuleSheetParserUtil.isStringMeaningTrue( value ) );
break;
@@ -628,6 +634,12 @@ private void nextDataCell(final int row,
RuleSheetParserUtil.rc2name( row, column ) );
}
break;
+ case TIMER:
+ this._currentRule.setTimer( value );
+ break;
+ case CALENDARS:
+ this._currentRule.setCalendars( value );
+ break;
}
}
diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java
index 34afbbabd51..eed5edcee92 100644
--- a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java
+++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java
@@ -16,16 +16,16 @@
package org.drools.decisiontable;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import static org.junit.Assert.*;
-
import org.drools.decisiontable.parser.RuleMatrixSheetListener;
+import org.junit.Test;
/**
*
@@ -154,5 +154,61 @@ public void testDeclaresCSV() {
assertTrue( drl.indexOf( "declare Smurf name : String end" ) > -1 );
}
+ @Test
+ public void testAttributesXLS() {
+ final SpreadsheetCompiler converter = new SpreadsheetCompiler();
+ String drl = converter.compile( "Attributes.xls",
+ InputType.XLS );
+
+ assertNotNull( drl );
+
+ int rule1 = drl.indexOf( "rule \"N1\"" );
+ assertFalse( rule1 == -1 );
+
+ assertTrue( drl.indexOf( "no-loop true",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "duration 100",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "salience 1",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "ruleflow-group \"RFG1\"",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "agenda-group \"AG1\"",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "timer (T1)",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "lock-on-active true",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "activation-group \"g1\"",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "auto-focus true",
+ rule1 ) > -1 );
+ assertTrue( drl.indexOf( "calendars \"CAL1\"",
+ rule1 ) > -1 );
+
+ int rule2 = drl.indexOf( "rule \"N2\"" );
+ assertFalse( rule2 == -1 );
+
+ assertTrue( drl.indexOf( "no-loop false",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "duration 200",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "salience 2",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "ruleflow-group \"RFG2\"",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "agenda-group \"AG2\"",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "timer (T2)",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "lock-on-active false",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "activation-group \"g2\"",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "auto-focus false",
+ rule2 ) > -1 );
+ assertTrue( drl.indexOf( "calendars \"CAL2\"",
+ rule2 ) > -1 );
+ }
}
diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java
index 13dcf1710da..cbfc6e9644a 100644
--- a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java
+++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java
@@ -15,18 +15,117 @@ public class ActionTypeTest {
@Test
public void testChooseActionType() {
+
Map<Integer, ActionType> actionTypeMap = new HashMap<Integer, ActionType>();
ActionType.addNewActionType( actionTypeMap, "C", 0, 1 );
-
ActionType type = (ActionType) actionTypeMap.get( new Integer(0) );
assertEquals( Code.CONDITION, type.getCode() );
-
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "CONDITION", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.CONDITION, type.getCode());
actionTypeMap = new HashMap<Integer, ActionType>();
ActionType.addNewActionType( actionTypeMap, "A", 0, 1 );
type = (ActionType) actionTypeMap.get( new Integer(0) );
assertEquals(Code.ACTION, type.getCode());
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "ACTION", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.ACTION, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "N", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.NAME, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "NAME", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.NAME, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "I", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.DESCRIPTION, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "DESCRIPTION", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.DESCRIPTION, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "P", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.SALIENCE, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "PRIORITY", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.SALIENCE, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "D", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.DURATION, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "DURATION", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.DURATION, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "T", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.TIMER, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "TIMER", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.TIMER, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "E", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.CALENDARS, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "CALENDARS", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.CALENDARS, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "U", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.NOLOOP, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "NO-LOOP", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.NOLOOP, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "L", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.LOCKONACTIVE, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "LOCK-ON-ACTIVE", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.LOCKONACTIVE, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "F", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.AUTOFOCUS, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "AUTO-FOCUS", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.AUTOFOCUS, type.getCode());
+
actionTypeMap = new HashMap<Integer, ActionType>();
ActionType.addNewActionType( actionTypeMap, "X", 0, 1 );
type = (ActionType) actionTypeMap.get( new Integer(0) );
@@ -36,16 +135,37 @@ public void testChooseActionType() {
ActionType.addNewActionType( actionTypeMap, "ACTIVATION-GROUP", 0, 1 );
type = (ActionType) actionTypeMap.get( new Integer(0) );
assertEquals(Code.ACTIVATIONGROUP, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "G", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.AGENDAGROUP, type.getCode());
actionTypeMap = new HashMap<Integer, ActionType>();
- ActionType.addNewActionType( actionTypeMap, "NO-LOOP", 0, 1 );
+ ActionType.addNewActionType( actionTypeMap, "AGENDA-GROUP", 0, 1 );
type = (ActionType) actionTypeMap.get( new Integer(0) );
- assertEquals(Code.NOLOOP, type.getCode());
+ assertEquals(Code.AGENDAGROUP, type.getCode());
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "R", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.RULEFLOWGROUP, type.getCode());
+
actionTypeMap = new HashMap<Integer, ActionType>();
ActionType.addNewActionType( actionTypeMap, "RULEFLOW-GROUP", 0, 1 );
type = (ActionType) actionTypeMap.get( new Integer(0) );
assertEquals(Code.RULEFLOWGROUP, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "@", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.METADATA, type.getCode());
+
+ actionTypeMap = new HashMap<Integer, ActionType>();
+ ActionType.addNewActionType( actionTypeMap, "METADATA", 0, 1 );
+ type = (ActionType) actionTypeMap.get( new Integer(0) );
+ assertEquals(Code.METADATA, type.getCode());
+
}
}
diff --git a/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls
new file mode 100644
index 00000000000..3159e4ffeb6
Binary files /dev/null and b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls differ
diff --git a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java
index 9d7dc79663a..b46e25c7c45 100644
--- a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java
+++ b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java
@@ -53,6 +53,14 @@ protected String asStringLiteral( String value ){
return '"' + value.replaceAll( "\"", Matcher.quoteReplacement( "\\\"" ) ) + '"';
}
+ protected String asTimerLiteral( String value ){
+ // Keep the brackets if they come in the right places.
+ if( value.startsWith( "(" ) && value.endsWith( ")" ) && value.length() >= 2 ){
+ value = value.substring( 1, value.length() - 1 );
+ }
+ return "(" + value+ ")";
+ }
+
public void setSalience( final Integer value ){
this._attr2value.put( "salience", Integer.toString( value ) );
}
@@ -65,6 +73,14 @@ public void setDuration(final Long value) {
this._attr2value.put( "duration", Long.toString( value ) );
}
+ public void setTimer(final String value) {
+ this._attr2value.put( "timer", asTimerLiteral( value ) );
+ }
+
+ public void setCalendars(final String value) {
+ this._attr2value.put( "calendars", asStringLiteral( value ) );
+ }
+
public void setActivationGroup(final String value) {
this._attr2value.put( "activation-group", asStringLiteral( value ) );
}
|
ebe25c83d1f5f1202c560516e8d58294b97ddf37
|
orientdb
|
Fixed bug using SQL projection against Object- Database interface. Now returns always documents instead of POJOs when the- ODocument has no class associated.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java
index 38afe2694d8..6e3ad037ca7 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java
@@ -212,7 +212,11 @@ public <RET extends List<?>> RET query(final OQuery<?> iCommand) {
Object obj;
for (ODocument doc : result) {
// GET THE ASSOCIATED DOCUMENT
- obj = getUserObjectByRecord(doc, iCommand.getFetchPlan(), true);
+ if (doc.getClassName() == null)
+ obj = doc;
+ else
+ obj = getUserObjectByRecord(doc, iCommand.getFetchPlan(), true);
+
resultPojo.add(obj);
}
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDDocumentPhysicalTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDDocumentPhysicalTest.java
index 27699e60437..d073da7d843 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDDocumentPhysicalTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDDocumentPhysicalTest.java
@@ -30,6 +30,7 @@
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.OBase64Utils;
+import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
@Test(groups = { "crud", "record-vobject" }, sequential = true)
public class CRUDDocumentPhysicalTest {
@@ -234,4 +235,35 @@ public void testNestedEmbeddedMap() {
Assert.assertEquals(loadedMap3.size(), 0);
}
+ @Test
+ public void queryWithPositionalParameters() {
+ database = ODatabaseDocumentPool.global().acquire(url, "admin", "admin");
+ database.open("admin", "admin");
+
+ final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>("select from Profile where name = ? and surname = ?");
+ List<ODocument> result = database.command(query).execute("Barack", "Obama");
+
+ Assert.assertTrue(result.size() != 0);
+
+ database.close();
+ }
+
+ @Test
+ public void queryWithNamedParameters() {
+ database = ODatabaseDocumentPool.global().acquire(url, "admin", "admin");
+ database.open("admin", "admin");
+
+ final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(
+ "select from Profile where name = :name and surname = :surname");
+
+ HashMap<String, String> params = new HashMap<String, String>();
+ params.put("name", "Barack");
+ params.put("surname", "Obama");
+
+ List<ODocument> result = database.command(query).execute(params);
+
+ Assert.assertTrue(result.size() != 0);
+
+ database.close();
+ }
}
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDObjectPhysicalTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDObjectPhysicalTest.java
index 86d690ad36f..c898058b253 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDObjectPhysicalTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/CRUDObjectPhysicalTest.java
@@ -16,6 +16,7 @@
package com.orientechnologies.orient.test.database.auto;
import java.util.Date;
+import java.util.HashMap;
import java.util.List;
import org.testng.Assert;
@@ -276,4 +277,36 @@ public void deleteFirst() {
database.close();
}
+
+ @Test
+ public void queryWithPositionalParameters() {
+ database = ODatabaseObjectPool.global().acquire(url, "admin", "admin");
+ database.open("admin", "admin");
+
+ final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>("select from Profile where name = ? and surname = ?");
+ List<ODocument> result = database.command(query).execute("Barack", "Obama");
+
+ Assert.assertTrue(result.size() != 0);
+
+ database.close();
+ }
+
+ @Test
+ public void queryWithNamedParameters() {
+ database = ODatabaseObjectPool.global().acquire(url, "admin", "admin");
+ database.open("admin", "admin");
+
+ final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(
+ "select from Profile where name = :name and surname = :surname");
+
+ HashMap<String, String> params = new HashMap<String, String>();
+ params.put("name", "Barack");
+ params.put("surname", "Obama");
+
+ List<ODocument> result = database.command(query).execute(params);
+
+ Assert.assertTrue(result.size() != 0);
+
+ database.close();
+ }
}
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectProjectionsTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectProjectionsTest.java
index 9a2111e1fe9..203fb57e5b8 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectProjectionsTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectProjectionsTest.java
@@ -23,15 +23,18 @@
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
+import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
@Test(groups = "sql-select")
public class SQLSelectProjectionsTest {
+ private String url;
private ODatabaseDocument database;
@Parameters(value = "url")
public SQLSelectProjectionsTest(String iURL) {
+ url = iURL;
database = new ODatabaseDocumentTx(iURL);
}
@@ -52,6 +55,23 @@ public void queryProjectionOk() {
database.close();
}
+ @Test
+ public void queryProjectionObjectLevel() {
+ ODatabaseObjectTx db = new ODatabaseObjectTx(url);
+ db.open("admin", "admin");
+
+ List<ODocument> result = db.query(new OSQLSynchQuery<ODocument>(" select nick, followings, followers from Profile "));
+
+ Assert.assertTrue(result.size() != 0);
+
+ for (ODocument d : result) {
+ Assert.assertNull(d.getClassName());
+ Assert.assertEquals(d.getRecordType(), ODocument.RECORD_TYPE);
+ }
+
+ db.close();
+ }
+
@Test
public void queryProjectionLinkedAndFunction() {
database.open("admin", "admin");
@@ -141,7 +161,8 @@ public void queryProjectionAliases() {
database.open("admin", "admin");
List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select name.append('!') as 1, surname as 2 from Profile where name is not null and surname is not null")).execute();
+ new OSQLSynchQuery<ODocument>(
+ "select name.append('!') as 1, surname as 2 from Profile where name is not null and surname is not null")).execute();
Assert.assertTrue(result.size() != 0);
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectTest.java
index 719e6140bbc..d4f5e5c0261 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectTest.java
@@ -18,7 +18,6 @@
import java.text.ParseException;
import java.util.Collection;
import java.util.Date;
-import java.util.HashMap;
import java.util.List;
import org.testng.Assert;
@@ -574,34 +573,4 @@ public void queryWithPagination() {
database.close();
}
-
- @Test
- public void queryWithPositionalParameters() {
- database.open("admin", "admin");
-
- final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>("select from Profile where name = ? and surname = ?");
- List<ODocument> result = database.command(query).execute("Barack", "Obama");
-
- Assert.assertTrue(result.size() != 0);
-
- database.close();
- }
-
- @Test
- public void queryWithNamedParameters() {
- database.open("admin", "admin");
-
- final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument >(
- "select from Profile where name = :name and surname = :surname");
-
- HashMap<String, String> params = new HashMap<String, String>();
- params.put("name", "Barack");
- params.put("surname", "Obama");
-
- List<ODocument> result = database.command(query).execute(params);
-
- Assert.assertTrue(result.size() != 0);
-
- database.close();
- }
}
|
322578b7736f174b9b8e47914c87e9b77c1c1fd4
|
kotlin
|
Replaced AddReturnTypeFix with- SpecifyTypeExplicitlyAction for properties.--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java b/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java
index f10680dddf543..ae3269014cf68 100644
--- a/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java
+++ b/idea/src/org/jetbrains/jet/plugin/intentions/SpecifyTypeExplicitlyAction.java
@@ -20,17 +20,17 @@
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
-import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor;
import org.jetbrains.jet.lang.descriptors.VariableDescriptor;
+import org.jetbrains.jet.lang.diagnostics.Diagnostic;
+import org.jetbrains.jet.lang.diagnostics.Errors;
import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.psi.JetProperty;
import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.types.ErrorUtils;
import org.jetbrains.jet.lang.types.JetType;
-import org.jetbrains.jet.lexer.JetTokens;
import org.jetbrains.jet.plugin.JetBundle;
import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil;
import org.jetbrains.jet.plugin.refactoring.introduceVariable.JetChangePropertyActions;
@@ -41,6 +41,15 @@
*/
public class SpecifyTypeExplicitlyAction extends PsiElementBaseIntentionAction {
private JetType targetType;
+ private boolean disabledForError;
+
+ public SpecifyTypeExplicitlyAction() {
+ this(true);
+ }
+
+ public SpecifyTypeExplicitlyAction(boolean disabledForError) {
+ this.disabledForError = disabledForError;
+ }
@NotNull
@Override
@@ -82,6 +91,13 @@ public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull Psi
if (ErrorUtils.isErrorType(targetType)) {
return false;
}
+ if (disabledForError) {
+ for (Diagnostic diagnostic : bindingContext.getDiagnostics()) {
+ if (Errors.PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE == diagnostic.getFactory() && property == diagnostic.getPsiElement()) {
+ return false;
+ }
+ }
+ }
}
return true;
}
diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/AddReturnTypeFix.java b/idea/src/org/jetbrains/jet/plugin/quickfix/AddReturnTypeFix.java
index 6a55bbfd47118..ec9a070dedaf2 100644
--- a/idea/src/org/jetbrains/jet/plugin/quickfix/AddReturnTypeFix.java
+++ b/idea/src/org/jetbrains/jet/plugin/quickfix/AddReturnTypeFix.java
@@ -52,7 +52,7 @@ public String getFamilyName() {
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
JetType type = QuickFixUtil.getDeclarationReturnType(element);
- return super.isAvailable(project, editor, file) && type != null && !ErrorUtils.isErrorType(type);
+ return super.isAvailable(project, editor, file) && type != null && !ErrorUtils.isErrorType(type) && element instanceof JetFunction;
}
@Override
@@ -61,9 +61,6 @@ public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws
PsiElement newElement;
JetType type = QuickFixUtil.getDeclarationReturnType(element);
if (type == null) return;
- if (element instanceof JetProperty) {
- newElement = addPropertyType(project, (JetProperty) element, type);
- }
else {
assert element instanceof JetFunction;
newElement = addFunctionType(project, (JetFunction) element, type);
diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixes.java b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixes.java
index dda1344366b85..ebd50c228edf1 100644
--- a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixes.java
+++ b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixes.java
@@ -23,6 +23,7 @@
import org.jetbrains.jet.lang.diagnostics.Errors;
import org.jetbrains.jet.lang.psi.JetClass;
import org.jetbrains.jet.plugin.codeInsight.ImplementMethodsHandler;
+import org.jetbrains.jet.plugin.intentions.SpecifyTypeExplicitlyAction;
import java.util.Collection;
@@ -137,5 +138,6 @@ private QuickFixes() {}
actions.put(UNNECESSARY_SAFE_CALL, new ReplaceCallFix(false));
actions.put(UNSAFE_CALL, new ReplaceCallFix(true));
+ actions.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, new SpecifyTypeExplicitlyAction(false));
}
}
\ No newline at end of file
diff --git a/idea/testData/quickfix/typeAddition/afterPublicValWithoutReturnType.kt b/idea/testData/quickfix/typeAddition/afterPublicValWithoutReturnType.kt
index 9f66148255266..d0796a7cd7444 100644
--- a/idea/testData/quickfix/typeAddition/afterPublicValWithoutReturnType.kt
+++ b/idea/testData/quickfix/typeAddition/afterPublicValWithoutReturnType.kt
@@ -1,4 +1,4 @@
-// "Add return type declaration" "true"
+// "Specify Type Explicitly" "true"
package a
import java.util.List
diff --git a/idea/testData/quickfix/typeAddition/beforePublicValWithoutReturnType.kt b/idea/testData/quickfix/typeAddition/beforePublicValWithoutReturnType.kt
index 5fb773845c16f..6155ec718689b 100644
--- a/idea/testData/quickfix/typeAddition/beforePublicValWithoutReturnType.kt
+++ b/idea/testData/quickfix/typeAddition/beforePublicValWithoutReturnType.kt
@@ -1,4 +1,4 @@
-// "Add return type declaration" "true"
+// "Specify Type Explicitly" "true"
package a
public val <caret>l = java.util.Collections.emptyList<Int>()
\ No newline at end of file
diff --git a/idea/testData/quickfix/typeImports/afterImportFromAnotherFile.kt b/idea/testData/quickfix/typeImports/afterImportFromAnotherFile.kt
index 40d4462c1fa22..5794bf9f5738d 100644
--- a/idea/testData/quickfix/typeImports/afterImportFromAnotherFile.kt
+++ b/idea/testData/quickfix/typeImports/afterImportFromAnotherFile.kt
@@ -1,4 +1,4 @@
-// "Add return type declaration" "true"
+// "Specify Type Explicitly" "true"
package a
diff --git a/idea/testData/quickfix/typeImports/afterNoImportFromTheSameFile.kt b/idea/testData/quickfix/typeImports/afterNoImportFromTheSameFile.kt
index dbf8c11c53b72..5acd2b8b7e562 100644
--- a/idea/testData/quickfix/typeImports/afterNoImportFromTheSameFile.kt
+++ b/idea/testData/quickfix/typeImports/afterNoImportFromTheSameFile.kt
@@ -1,4 +1,4 @@
-// "Add return type declaration" "true"
+// "Specify Type Explicitly" "true"
class A() {}
diff --git a/idea/testData/quickfix/typeImports/beforeImportFromAnotherFile.Main.kt b/idea/testData/quickfix/typeImports/beforeImportFromAnotherFile.Main.kt
index 66f32cb95a825..bc5de5d7d13da 100644
--- a/idea/testData/quickfix/typeImports/beforeImportFromAnotherFile.Main.kt
+++ b/idea/testData/quickfix/typeImports/beforeImportFromAnotherFile.Main.kt
@@ -1,4 +1,4 @@
-// "Add return type declaration" "true"
+// "Specify Type Explicitly" "true"
package a
diff --git a/idea/testData/quickfix/typeImports/beforeNoImportFromTheSameFile.kt b/idea/testData/quickfix/typeImports/beforeNoImportFromTheSameFile.kt
index 2b6d8501e56ba..973d53507d706 100644
--- a/idea/testData/quickfix/typeImports/beforeNoImportFromTheSameFile.kt
+++ b/idea/testData/quickfix/typeImports/beforeNoImportFromTheSameFile.kt
@@ -1,4 +1,4 @@
-// "Add return type declaration" "true"
+// "Specify Type Explicitly" "true"
class A() {}
|
3980e032581824d7241748c7ec56a916fdce6261
|
orientdb
|
Improved memory usage and optimized general speed--
|
p
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/OMemoryWatchDog.java b/core/src/main/java/com/orientechnologies/orient/core/OMemoryWatchDog.java
index 4aeb1c5992c..20972ad28ee 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/OMemoryWatchDog.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/OMemoryWatchDog.java
@@ -73,12 +73,14 @@ public OMemoryWatchDog(final float iThreshold) {
public void handleNotification(Notification n, Object hb) {
if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
alertTimes++;
- final long maxMemory = tenuredGenPool.getUsage().getMax();
+ long maxMemory = tenuredGenPool.getUsage().getMax();
long usedMemory = tenuredGenPool.getUsage().getUsed();
long freeMemory = maxMemory - usedMemory;
- OLogManager.instance().debug(this, "Low memory %s%% (used %s of %s), calling listeners to free memory in soft way...",
- freeMemory * 100 / maxMemory, OFileUtils.getSizeAsString(usedMemory), OFileUtils.getSizeAsString(maxMemory));
+ OLogManager.instance().debug(this,
+ "Free memory is low %s %s%% (used %s of %s), calling listeners to free memory in SOFT way...",
+ OFileUtils.getSizeAsString(freeMemory), freeMemory * 100 / maxMemory, OFileUtils.getSizeAsString(usedMemory),
+ OFileUtils.getSizeAsString(maxMemory));
final long timer = OProfiler.getInstance().startChrono();
@@ -90,30 +92,44 @@ public void handleNotification(Notification n, Object hb) {
}
}
- System.gc();
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
+ long threshold;
+ do {
+ // INVOKE GC AND WAIT A BIT
+ System.gc();
+ try {
+ Thread.sleep(400);
+ } catch (InterruptedException e) {
+ }
- freeMemory = Runtime.getRuntime().freeMemory();
- usedMemory = maxMemory - freeMemory;
- final long threshold = (long) (maxMemory * (1 - OGlobalConfiguration.MEMORY_OPTIMIZE_THRESHOLD.getValueAsFloat()));
-
- if (freeMemory < threshold) {
- OLogManager.instance().info(this,
- "Low memory %s%% (used %s of %s) while the threshold is %s, calling listeners to free memory in hard way...",
- usedMemory * 100 / maxMemory, OFileUtils.getSizeAsString(usedMemory), OFileUtils.getSizeAsString(maxMemory),
- OFileUtils.getSizeAsString(threshold));
-
- for (Listener listener : listeners) {
- try {
- listener.memoryUsageCritical(TYPE.JVM, usedMemory, maxMemory);
- } catch (Exception e) {
- e.printStackTrace();
+ // RECHECK IF MEMORY IS OK NOW
+ maxMemory = tenuredGenPool.getUsage().getMax();
+ usedMemory = tenuredGenPool.getUsage().getUsed();
+ freeMemory = maxMemory - usedMemory;
+
+ threshold = (long) (maxMemory * (1 - OGlobalConfiguration.MEMORY_OPTIMIZE_THRESHOLD.getValueAsFloat()));
+
+ OLogManager.instance().debug(this, "Free memory now is %s %s%% (used %s of %s) with threshold for HARD clean is %s",
+ OFileUtils.getSizeAsString(freeMemory), freeMemory * 100 / maxMemory, OFileUtils.getSizeAsString(usedMemory),
+ OFileUtils.getSizeAsString(maxMemory), OFileUtils.getSizeAsString(threshold));
+
+ if (freeMemory < threshold) {
+ OLogManager
+ .instance()
+ .debug(
+ this,
+ "Free memory is low %s %s%% (used %s of %s) while the threshold is %s, calling listeners to free memory in HARD way...",
+ OFileUtils.getSizeAsString(freeMemory), freeMemory * 100 / maxMemory, OFileUtils.getSizeAsString(usedMemory),
+ OFileUtils.getSizeAsString(maxMemory), OFileUtils.getSizeAsString(threshold));
+
+ for (Listener listener : listeners) {
+ try {
+ listener.memoryUsageCritical(TYPE.JVM, usedMemory, maxMemory);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
}
- }
+ } while (freeMemory < threshold);
OProfiler.getInstance().stopChrono("OMemoryWatchDog.freeResources", timer);
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/cache/OAbstractRecordCache.java b/core/src/main/java/com/orientechnologies/orient/core/cache/OAbstractRecordCache.java
index 962c5f75f6d..ec68d81c627 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/cache/OAbstractRecordCache.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/cache/OAbstractRecordCache.java
@@ -156,7 +156,7 @@ public void memoryUsageLow(TYPE iType, final long usedMemory, final long maxMemo
// UNACTIVE
return;
- final int threshold = (int) (oldSize * 0.5f);
+ final int threshold = (int) (oldSize * 0.9f);
entries.removeEldestItems(threshold);
diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
index 531880f0f17..4de9330e56f 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
@@ -313,7 +313,7 @@ private static void autoConfig() {
// WINDOWS
// AVOID TO USE MMAP, SINCE COULD BE BUGGY
- //FILE_MMAP_STRATEGY.setValue(3);
+ FILE_MMAP_STRATEGY.setValue(3);
}
if (System.getProperty("os.arch").indexOf("64") > -1) {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
index 0fefb774c0f..be054f60453 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java
@@ -84,7 +84,7 @@ public void memoryUsageLow(final TYPE iType, final long usedMemory, final long m
map.setMaxUpdatesBeforeSave(maxUpdates);
- optimize();
+ optimize(false);
} finally {
releaseExclusiveLock();
}
@@ -97,14 +97,14 @@ public void memoryUsageCritical(final TYPE iType, final long usedMemory, final l
if (map != null) {
acquireExclusiveLock();
try {
- // REDUCE SOME PARAMETERS
+ // REDUCE OF 10% LAZY UPDATES
int maxUpdates = map.getMaxUpdatesBeforeSave();
if (maxUpdates > 10)
- maxUpdates *= 0.5;
+ maxUpdates *= 0.50;
map.setMaxUpdatesBeforeSave(maxUpdates);
- optimize();
+ optimize(true);
} finally {
releaseExclusiveLock();
}
@@ -112,13 +112,15 @@ public void memoryUsageCritical(final TYPE iType, final long usedMemory, final l
}
}
- private void optimize() {
+ private void optimize(final boolean iHardMode) {
OLogManager.instance().debug(this, "Forcing optimization of Index %s (%d items). Found %d entries in memory...", name,
map.size(), map.getInMemoryEntries());
+ if (iHardMode)
+ map.freeInMemoryResources();
map.optimize(true);
- OLogManager.instance().debug(this, "Completed! Now %d entries resides in memory", map.getInMemoryEntries());
+ OLogManager.instance().debug(this, "Completed! Now %d entries reside in memory", map.getInMemoryEntries());
}
};
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
index 840f4615673..02bca7f54a3 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
@@ -80,9 +80,10 @@ public void fromStream(final ODocument iSource) {
roles = new HashSet<ORole>();
final Set<ODocument> loadedRoles = iSource.field("roles");
- for (ODocument d : loadedRoles) {
- roles.add(document.getDatabase().getMetadata().getSecurity().getRole((String) d.field("name")));
- }
+ if (loadedRoles != null)
+ for (ODocument d : loadedRoles) {
+ roles.add(document.getDatabase().getMetadata().getSecurity().getRole((String) d.field("name")));
+ }
}
/**
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
index d4beb70cede..53c18eb423f 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeEntryPersistent.java
@@ -221,7 +221,7 @@ protected int disconnect(final boolean iForceDirty, final int iLevel) {
// REMOVE ME FROM THE CACHE
if (pTree.cache.remove(record.getIdentity()) == null)
- OLogManager.instance().warn(this, "Can't find current node into the cache. Is the cache invalid?");
+ OLogManager.instance().debug(this, "Can't find current node into the cache. Is the cache invalid?");
int totalDisconnected = 1;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
index e4c934c8eef..7b1d24da0dc 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreePersistent.java
@@ -69,8 +69,6 @@ public abstract class OMVRBTreePersistent<K, V> extends OMVRBTree<K, V> implemen
protected float optimizeEntryPointsFactor;
protected volatile List<OMVRBTreeEntryPersistent<K, V>> entryPoints = new ArrayList<OMVRBTreeEntryPersistent<K, V>>(
entryPointsSize);
- protected List<OMVRBTreeEntryPersistent<K, V>> newEntryPoints = new ArrayList<OMVRBTreeEntryPersistent<K, V>>(
- entryPointsSize);
protected Map<ORID, OMVRBTreeEntryPersistent<K, V>> cache = new HashMap<ORID, OMVRBTreeEntryPersistent<K, V>>();
private final OMemoryOutputStream entryRecordBuffer;
@@ -156,6 +154,13 @@ public void unload() {
}
}
+ /**
+ * Frees all the in memory objects. It's called under hard memory pressure.
+ */
+ public void freeInMemoryResources() {
+ entryPoints.clear();
+ }
+
/**
* Optimize the tree memory consumption by keeping part of nodes as entry points and clearing all the rest.
*/
@@ -222,7 +227,7 @@ public void optimize(final boolean iForce) {
else
distance = nodes / entryPointsSize + 1;
- newEntryPoints.clear();
+ final List<OMVRBTreeEntryPersistent<K, V>> newEntryPoints = new ArrayList<OMVRBTreeEntryPersistent<K, V>>(entryPointsSize + 1);
OLogManager.instance().debug(this, "Compacting nodes with distance = %d", distance);
@@ -287,9 +292,7 @@ public void optimize(final boolean iForce) {
// SWAP TMP AND REAL ENTRY POINT COLLECTIONS
entryPoints.clear();
- final List<OMVRBTreeEntryPersistent<K, V>> a = entryPoints;
entryPoints = newEntryPoints;
- newEntryPoints = a;
if (debug) {
System.out.printf("\nEntrypoints (%d): ", entryPoints.size());
|
8e36389ff951e9c3c836561d9f58dd4bc798e049
|
arrayexpress$annotare2
|
Adding change password functionality
|
p
|
https://github.com/arrayexpress/annotare2
|
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java
index 4dc9cae16..d61d4e0ba 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java
@@ -25,7 +25,6 @@
import uk.ac.ebi.fg.annotare2.web.server.login.utils.FormParams;
import uk.ac.ebi.fg.annotare2.web.server.services.AccountManager;
import uk.ac.ebi.fg.annotare2.web.server.login.utils.RequestParam;
-import uk.ac.ebi.fg.annotare2.web.server.login.utils.SessionAttribute;
import uk.ac.ebi.fg.annotare2.web.server.login.utils.ValidationErrors;
import uk.ac.ebi.fg.annotare2.web.server.services.EmailSender;
import uk.ac.ebi.fg.annotare2.web.server.transaction.Transactional;
@@ -34,6 +33,9 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
+import static com.google.common.base.Strings.nullToEmpty;
+import static uk.ac.ebi.fg.annotare2.web.server.login.SessionInformation.*;
+
/**
* @author Olga Melnichuk
*/
@@ -41,8 +43,6 @@ public class AccountServiceImpl implements AccountService {
private static final Logger log = LoggerFactory.getLogger(AccountServiceImpl.class);
- private static final SessionAttribute USER_EMAIL_ATTRIBUTE = new SessionAttribute("email");
-
private AccountManager accountManager;
private EmailSender emailer;
@@ -53,7 +53,7 @@ public AccountServiceImpl(AccountManager accountManager, EmailSender emailer) {
}
public boolean isLoggedIn(HttpServletRequest request) {
- return USER_EMAIL_ATTRIBUTE.exists(request.getSession());
+ return LOGGED_IN_SESSION_ATTRIBUTE.exists(request.getSession());
}
@Transactional
@@ -62,7 +62,7 @@ public ValidationErrors signUp(HttpServletRequest request) throws AccountService
ValidationErrors errors = params.validate();
if (errors.isEmpty()) {
if (null != accountManager.getByEmail(params.getEmail())) {
- errors.append("email", "User with this email already exists");
+ errors.append(FormParams.EMAIL_PARAM, "User with this email already exists");
} else {
User u = accountManager.createUser(params.getName(), params.getEmail(), params.getPassword());
try {
@@ -75,7 +75,7 @@ public ValidationErrors signUp(HttpServletRequest request) throws AccountService
)
);
} catch (MessagingException x) {
- //
+ log.error("There was a problem sending an email", x);
}
}
}
@@ -84,24 +84,48 @@ public ValidationErrors signUp(HttpServletRequest request) throws AccountService
@Transactional
public ValidationErrors changePassword(HttpServletRequest request) throws AccountServiceException {
- SignUpParams params = new SignUpParams(request);
+ ChangePasswordParams params = new ChangePasswordParams(request);
ValidationErrors errors = params.validate();
if (errors.isEmpty()) {
- if (null != accountManager.getByEmail(params.getEmail())) {
- errors.append("email", "User with this email already exists");
+ User u = accountManager.getByEmail(params.getEmail());
+ if (null == u) {
+ errors.append(FormParams.EMAIL_PARAM, "User with this email does not exist");
+
} else {
- User u = accountManager.createUser(params.getName(), params.getEmail(), params.getPassword());
- try {
- emailer.sendFromTemplate(
- EmailSender.NEW_USER_TEMPLATE,
- ImmutableMap.of(
- "to.name", u.getName(),
- "to.email", u.getEmail(),
- "verification.token", u.getVerificationToken()
- )
- );
- } catch (MessagingException x) {
- //
+ if ("".equals(nullToEmpty(params.getToken()))) {
+ u = accountManager.requestChangePassword(u.getEmail());
+ try {
+ emailer.sendFromTemplate(
+ EmailSender.CHANGE_PASSWORD_REQUEST_TEMPLATE,
+ ImmutableMap.of(
+ "to.name", u.getName(),
+ "to.email", u.getEmail(),
+ "verification.token", u.getVerificationToken()
+ )
+ );
+ } catch (MessagingException x) {
+ log.error("There was a problem sending an email", x);
+ }
+ } else {
+ if (!u.isPasswordChangeRequested()) {
+ errors.append("Change password request is invalid; please try a new one");
+ } else if (!u.getVerificationToken().equals(params.getToken())) {
+ errors.append("Incorrect code; please try again or request a new one");
+ } else {
+ accountManager.processChangePassword(u.getEmail(), params.getPassword());
+
+ }
+ try {
+ emailer.sendFromTemplate(
+ EmailSender.CHANGE_PASSWORD_CONFIRMATION_TEMPLATE,
+ ImmutableMap.of(
+ "to.name", u.getName(),
+ "to.email", u.getEmail()
+ )
+ );
+ } catch (MessagingException x) {
+ log.error("There was a problem sending an email", x);
+ }
}
}
}
@@ -118,7 +142,8 @@ public ValidationErrors login(HttpServletRequest request) throws AccountServiceE
throw new AccountServiceException("Sorry, the email or password you entered is not valid.");
}
log.debug("User '{}' logged in", params.getEmail());
- USER_EMAIL_ATTRIBUTE.set(request.getSession(), params.getEmail());
+ EMAIL_SESSION_ATTRIBUTE.set(request.getSession(), params.getEmail());
+ LOGGED_IN_SESSION_ATTRIBUTE.set(request.getSession(), true);
}
return errors;
}
@@ -128,9 +153,12 @@ public void logout(HttpSession session) {
}
public User getCurrentUser(HttpSession session) {
- String email = (String) USER_EMAIL_ATTRIBUTE.get(session);
- User user = accountManager.getByEmail(email);
- if (user == null) {
+ User user = null;
+ if (LOGGED_IN_SESSION_ATTRIBUTE.exists(session)) {
+ String email = (String) EMAIL_SESSION_ATTRIBUTE.get(session);
+ user = accountManager.getByEmail(email);
+ }
+ if (null == user) {
throw new UnauthorizedAccessException("Sorry, you are not logged in");
}
return user;
@@ -195,4 +223,46 @@ public String getPassword() {
return getParamValue(PASSWORD_PARAM);
}
}
+
+ static class ChangePasswordParams extends FormParams {
+
+ private ChangePasswordParams(HttpServletRequest request) {
+ addParam(RequestParam.from(request, EMAIL_PARAM), false);
+ addParam(RequestParam.from(request, PASSWORD_PARAM), false);
+ addParam(RequestParam.from(request, CONFIRM_PASSWORD_PARAM), false);
+ addParam(RequestParam.from(request, TOKEN_PARAM), false);
+ }
+
+ public ValidationErrors validate() {
+ ValidationErrors errors = validateMandatory();
+
+ if ("".equals(nullToEmpty(getToken()))) {
+ if (!isEmailGoodEnough()) {
+ errors.append(EMAIL_PARAM, "Email is not valid; should at least contain @ sign");
+ }
+ } else {
+ if (!isPasswordGoodEnough()) {
+ errors.append(PASSWORD_PARAM, "Password is too weak; should be at least 4 characters long containing at least one digit");
+ }
+
+ if (!hasPasswordConfirmed()) {
+ errors.append(CONFIRM_PASSWORD_PARAM, "Passwords do not match");
+ }
+ }
+
+ return errors;
+ }
+
+ public String getToken() {
+ return getParamValue(TOKEN_PARAM);
+ }
+
+ public String getEmail() {
+ return getParamValue(EMAIL_PARAM);
+ }
+
+ public String getPassword() {
+ return getParamValue(PASSWORD_PARAM);
+ }
+ }
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java
index 75d3dca75..dc19b7225 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java
@@ -20,6 +20,7 @@
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import uk.ac.ebi.fg.annotare2.web.server.login.utils.FormParams;
import uk.ac.ebi.fg.annotare2.web.server.login.utils.ValidationErrors;
import javax.servlet.ServletException;
@@ -28,6 +29,7 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
+import static com.google.common.base.Strings.nullToEmpty;
import static uk.ac.ebi.fg.annotare2.web.server.login.ServletNavigation.CHANGE_PASSWORD;
import static com.google.common.base.Strings.isNullOrEmpty;
@@ -45,29 +47,40 @@ public class ChangePasswordServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("Change password request received; processing");
ValidationErrors errors = new ValidationErrors();
-
- try {
- errors.append(accountService.changePassword(request));
- if (errors.isEmpty()) {
- if (!isNullOrEmpty(request.getParameter("token"))) {
- log.debug("Password successfully changed; redirect to login page");
- INFO_SESSION_ATTRIBUTE.set(request.getSession(), "You have successfully changed password; please sign in now");
- LOGIN.redirect(request, response);
- return;
+ if (null == request.getParameter(FormParams.EMAIL_PARAM)) {
+ request.setAttribute("phase", "email");
+ } else {
+ try {
+ errors.append(accountService.changePassword(request));
+ if (errors.isEmpty()) {
+ if (null == request.getParameter("token")) {
+ log.debug("Change request email has been sent; show information");
+ INFO_SESSION_ATTRIBUTE.set(request.getSession(), "Email sent to the specified address; please check your mailbox");
+ request.setAttribute("phase", "token");
+ } else if (null == request.getParameter("password")) {
+ log.debug("Token validated; enable password inputs");
+ request.setAttribute("phase", "password");
+ } else {
+ INFO_SESSION_ATTRIBUTE.set(request.getSession(), "You have successfully changed password; please sign in now");
+ LOGIN.redirect(request, response);
+ return;
+ }
+ } else {
+ request.setAttribute("phase", request.getParameter("phase"));
}
+ } catch (AccountServiceException e) {
+ log.debug("Change password request failed", e);
+ errors.append(e.getMessage());
}
- } catch (AccountServiceException e) {
- log.debug("Change password request failed", e);
- errors.append(e.getMessage());
- }
- request.setAttribute("errors", errors);
+ request.setAttribute("errors", errors);
+ }
CHANGE_PASSWORD.forward(getServletConfig().getServletContext(), request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- CHANGE_PASSWORD.forward(getServletConfig().getServletContext(), request, response);
+ doPost(request, response);
}
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SessionInformation.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SessionInformation.java
index 1e69d7e72..7eaec9bff 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SessionInformation.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SessionInformation.java
@@ -21,5 +21,6 @@
public class SessionInformation {
public static final SessionAttribute EMAIL_SESSION_ATTRIBUTE = new SessionAttribute("email");
+ public static final SessionAttribute LOGGED_IN_SESSION_ATTRIBUTE = new SessionAttribute("loggedin");
public static final SessionAttribute INFO_SESSION_ATTRIBUTE = new SessionAttribute("info");
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java
index 34c5a6263..06dffacee 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java
@@ -22,11 +22,11 @@
import static com.google.common.base.Strings.nullToEmpty;
public abstract class FormParams {
- protected static final String NAME_PARAM = "name";
- protected static final String EMAIL_PARAM = "email";
- protected static final String PASSWORD_PARAM = "password";
- protected static final String CONFIRM_PASSWORD_PARAM = "confirm-password";
- protected static final String TOKEN_PARAM = "token";
+ public static final String NAME_PARAM = "name";
+ public static final String EMAIL_PARAM = "email";
+ public static final String PASSWORD_PARAM = "password";
+ public static final String CONFIRM_PASSWORD_PARAM = "confirm-password";
+ public static final String TOKEN_PARAM = "token";
private Map<String,RequestParam> paramMap = new HashMap<String, RequestParam>();
private Set<RequestParam> mandatoryParamSet = new HashSet<RequestParam>();
@@ -71,6 +71,6 @@ protected boolean isPasswordGoodEnough() {
}
protected boolean hasPasswordConfirmed() {
- return getParamValue(PASSWORD_PARAM).equals(getParamValue(CONFIRM_PASSWORD_PARAM));
+ return nullToEmpty(getParamValue(PASSWORD_PARAM)).equals(getParamValue(CONFIRM_PASSWORD_PARAM));
}
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/AccountManager.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/AccountManager.java
index 23cfc7117..6cab7613f 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/AccountManager.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/AccountManager.java
@@ -63,6 +63,37 @@ public User createUser(final String name, final String email, final String passw
return user;
}
+ public User activateUser(final String email) {
+ User user = getByEmail(email);
+ if (null != user) {
+ user.setEmailVerified(true);
+ user.setVerificationToken(null);
+ userDao.save(user);
+ }
+ return user;
+ }
+
+ public User requestChangePassword(final String email) {
+ User user = getByEmail(email);
+ if (null != user) {
+ user.setPasswordChangeRequested(true);
+ user.setVerificationToken(generateToken());
+ userDao.save(user);
+ }
+ return user;
+ }
+
+ public User processChangePassword(final String email, final String password) {
+ User user = getByEmail(email);
+ if (null != user) {
+ user.setPasswordChangeRequested(false);
+ user.setPassword(md5Hex(password));
+ user.setVerificationToken(null);
+ userDao.save(user);
+ }
+ return user;
+ }
+
private String generateToken() {
return new BigInteger(130, random).toString(36).toLowerCase();
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/EmailSender.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/EmailSender.java
index 036d51116..da7ed2547 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/EmailSender.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/EmailSender.java
@@ -35,6 +35,8 @@ public class EmailSender
private final AnnotareProperties properties;
public static final String NEW_USER_TEMPLATE = "new-user";
+ public static final String CHANGE_PASSWORD_REQUEST_TEMPLATE = "change-password-request";
+ public static final String CHANGE_PASSWORD_CONFIRMATION_TEMPLATE = "change-password-confirmation";
public static final String INITIAL_SUBMISSION_TEMPLATE = "initial-submission";
public static final String REJECTED_SUBMISSION_TEMPLATE = "rejected-submission";
diff --git a/app/web/src/main/webapp/change-password.jsp b/app/web/src/main/webapp/change-password.jsp
index cb01a2882..916b7ac70 100644
--- a/app/web/src/main/webapp/change-password.jsp
+++ b/app/web/src/main/webapp/change-password.jsp
@@ -16,14 +16,23 @@
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="f" %>
<%@ page isELIgnored="false" %>
+<%@ page import="uk.ac.ebi.fg.annotare2.web.server.login.utils.ValidationErrors" %>
<%
- pageContext.setAttribute("errors", request.getAttribute("errors"));
+ ValidationErrors errors = (ValidationErrors) request.getAttribute("errors");
+ if (errors != null) {
+ pageContext.setAttribute("dummyErrors", errors.getErrors());
+ pageContext.setAttribute("emailErrors", errors.getErrors("email"));
+ pageContext.setAttribute("tokenErrors", errors.getErrors("token"));
+ pageContext.setAttribute("passwordErrors", errors.getErrors("password"));
+ pageContext.setAttribute("confirmPasswordErrors", errors.getErrors("confirm-password"));
+ }
String email = request.getParameter("email");
if (null == email) {
email = (String)session.getAttribute("email");
}
pageContext.setAttribute("email", email == null ? "" : email);
+ pageContext.setAttribute("phase", request.getAttribute("phase"));
%>
<!DOCTYPE html>
@@ -52,32 +61,63 @@
</tr>
<tr class="error">
<td></td>
- <td>${errors}</td>
- </tr>
- <tr class="row right">
- <td>Email</td>
- <td>
- <c:choose>
- <c:when test="${email != ''}">
- <input type="text" name="email" value="${email}" style="width:98%"/>
- </c:when>
- <c:otherwise>
- <input type="text" name="email" style="width:98%" autofocus="autofocus"/>
- </c:otherwise>
- </c:choose>
- </td>
+ <td>${dummyErrors}</td>
</tr>
+ <c:choose>
+ <c:when test="${phase == 'email'}">
+ <tr class="error">
+ <td></td>
+ <td>${emailErrors}</td>
+ </tr>
+ <tr class="row right">
+ <td>Email</td>
+ <td>
+ <input type="text" name="email" value="${email}" style="width:98%" autofocus="autofocus"/>
+ </td>
+ </tr>
+ </c:when>
+ <c:when test="${phase == 'token'}">
+ <tr class="error">
+ <td></td>
+ <td>${tokenErrors}</td>
+ </tr>
+ <tr class="row right">
+ <td>Token</td>
+ <td>
+ <input type="hidden" name="email" value="${email}"/>
+ <input type="text" name="token" style="width:98%" autofocus="autofocus"/>
+ </td>
+ </tr>
+ </c:when>
+ <c:otherwise>
+ <tr class="row right">
+ <td>Password</td>
+ <td>
+ <input type="hidden" name="email" value="${email}"/>
+ <input type="hidden" name="token" value="${token}"/>
+ <input type="password" name="password" style="width:98%" autofocus="autofocus"/>
+ </td>
+ </tr>
+ <tr class="error">
+ <td></td>
+ <td>${passwordErrors}</td>
+ </tr>
+ <tr class="row right">
+ <td>Confirm password</td>
+ <td><input type="password" name="confirm-password" style="width:98%"/></td>
+ </tr>
+ <tr class="error">
+ <td></td>
+ <td>${confirmPasswordErrors}</td>
+ </tr>
+ </c:otherwise>
+ </c:choose>
+
<tr class="row">
<td></td>
<td>
- <c:choose>
- <c:when test="${email != ''}">
- <button name="changePassword" autofocus="autofocus">Send</button>
- </c:when>
- <c:otherwise>
- <button name="changePassword">Send</button>
- </c:otherwise>
- </c:choose>
+ <button name="changePassword">Send</button>
+ <input type="hidden" name="phase" value="${phase}"/>
</td>
</tr>
</table>
diff --git a/app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/AuthenticationServiceImplTest.java b/app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/AuthenticationServiceImplTest.java
index b4fa7e101..9e227bcdd 100644
--- a/app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/AuthenticationServiceImplTest.java
+++ b/app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/AuthenticationServiceImplTest.java
@@ -108,7 +108,7 @@ private EmailSender mockEmailer() {
private HttpServletRequest mockRequest(String name, String password) {
HttpSession session = createMock(HttpSession.class);
session.setAttribute(isA(String.class), isA(Object.class));
- expectLastCall();
+ expectLastCall().times(2);
HttpServletRequest request = createMock(HttpServletRequest.class);
expect(request
|
903ee0d0a6f1254e054a8413575b059f77d3899d
|
restlet-framework-java
|
- Fixed unit test due to random Java method- introspection order--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource8TestCase.java b/modules/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource8TestCase.java
index 375d0fcc70..2a545cbe5f 100644
--- a/modules/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource8TestCase.java
+++ b/modules/org.restlet.test/src/org/restlet/test/resource/AnnotatedResource8TestCase.java
@@ -35,7 +35,6 @@
import java.io.IOException;
-import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
@@ -69,40 +68,43 @@ protected void tearDown() throws Exception {
}
public void testPost() throws IOException, ResourceException {
- Representation input = new StringRepresentation("<root/>",
+ Representation input = new StringRepresentation("root",
MediaType.APPLICATION_XML);
Representation result = clientResource.post(input,
MediaType.APPLICATION_XML);
assertNotNull(result);
- assertEquals("<root/>1", result.getText());
+ assertEquals("root1", result.getText());
assertEquals(MediaType.APPLICATION_XML, result.getMediaType());
- input = new StringRepresentation("<root/>", MediaType.APPLICATION_XML);
+ input = new StringRepresentation("root", MediaType.APPLICATION_XML);
result = clientResource.post(input, MediaType.APPLICATION_JSON);
assertNotNull(result);
- assertEquals("<root/>2", result.getText());
+ assertEquals("root1", result.getText());
assertEquals(MediaType.APPLICATION_JSON, result.getMediaType());
- input = new StringRepresentation("root=true",
- MediaType.APPLICATION_WWW_FORM);
+ input = new StringRepresentation("root", MediaType.APPLICATION_JSON);
result = clientResource.post(input, MediaType.APPLICATION_JSON);
assertNotNull(result);
- assertEquals("root=true3", result.getText());
+ assertEquals("root1", result.getText());
assertEquals(MediaType.APPLICATION_JSON, result.getMediaType());
- Form inputForm = new Form();
- inputForm.add("root", "true");
- result = clientResource.post(inputForm, MediaType.APPLICATION_JSON);
+ input = new StringRepresentation("root", MediaType.APPLICATION_JSON);
+ result = clientResource.post(input, MediaType.APPLICATION_XML);
assertNotNull(result);
- assertEquals("root=true3", result.getText());
- assertEquals(MediaType.APPLICATION_JSON, result.getMediaType());
+ assertEquals("root1", result.getText());
+ assertEquals(MediaType.APPLICATION_XML, result.getMediaType());
- input = new StringRepresentation("[root]", MediaType.APPLICATION_JSON);
- result = clientResource.post(input, MediaType.APPLICATION_JSON);
+ input = new StringRepresentation("root", MediaType.APPLICATION_WWW_FORM);
+ result = clientResource.post(input, MediaType.APPLICATION_WWW_FORM);
assertNotNull(result);
- assertEquals("[root]2", result.getText());
- assertEquals(MediaType.APPLICATION_JSON, result.getMediaType());
+ assertEquals("root2", result.getText());
+ assertEquals(MediaType.APPLICATION_WWW_FORM, result.getMediaType());
+ input = new StringRepresentation("root", MediaType.APPLICATION_WWW_FORM);
+ result = clientResource.post(input, MediaType.TEXT_HTML);
+ assertNotNull(result);
+ assertEquals("root2", result.getText());
+ assertEquals(MediaType.TEXT_HTML, result.getMediaType());
}
}
diff --git a/modules/org.restlet.test/src/org/restlet/test/resource/MyResource8.java b/modules/org.restlet.test/src/org/restlet/test/resource/MyResource8.java
index 1edfae72b7..309d1c617d 100644
--- a/modules/org.restlet.test/src/org/restlet/test/resource/MyResource8.java
+++ b/modules/org.restlet.test/src/org/restlet/test/resource/MyResource8.java
@@ -38,19 +38,14 @@
public class MyResource8 extends ServerResource {
- @Post("xml|json:xml")
- public String storeForm(String entity) {
- return entity + "1";
- }
-
- @Post("xml|json:json|html")
+ @Post("xml|json:xml|json")
public String store1(String entity) {
- return entity + "2";
+ return entity + "1";
}
- @Post("form|json:json|html")
+ @Post("form|html:form|html")
public String store2(String entity) {
- return entity + "3";
+ return entity + "2";
}
}
|
ced5a6c917416088d9def359edacf548509677f3
|
kotlin
|
Introduce RenderingContext and add as parameter- to DiagnosticParameterRenderer-render--RenderingContext holds data about the whole diagnostics allowing to adjust rendering of its parameters-
|
a
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/DefaultErrorMessagesJvm.java b/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/DefaultErrorMessagesJvm.java
index 8b059e3b5a9d7..50cd881fa597a 100644
--- a/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/DefaultErrorMessagesJvm.java
+++ b/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/DefaultErrorMessagesJvm.java
@@ -18,10 +18,7 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
-import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages;
-import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticFactoryToRendererMap;
-import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticParameterRenderer;
-import org.jetbrains.kotlin.diagnostics.rendering.Renderers;
+import org.jetbrains.kotlin.diagnostics.rendering.*;
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import java.util.ArrayList;
@@ -33,7 +30,7 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
private static final DiagnosticParameterRenderer<ConflictingJvmDeclarationsData> CONFLICTING_JVM_DECLARATIONS_DATA = new DiagnosticParameterRenderer<ConflictingJvmDeclarationsData>() {
@NotNull
@Override
- public String render(@NotNull ConflictingJvmDeclarationsData data) {
+ public String render(@NotNull ConflictingJvmDeclarationsData data, @NotNull RenderingContext context) {
List<String> renderedDescriptors = new ArrayList<String>();
for (JvmDeclarationOrigin origin : data.getSignatureOrigins()) {
DeclarationDescriptor descriptor = origin.getDescriptor();
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/checkers/CheckerTestUtil.java b/compiler/frontend/src/org/jetbrains/kotlin/checkers/CheckerTestUtil.java
index 19d39f1d56d68..81df046e67e25 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/checkers/CheckerTestUtil.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/checkers/CheckerTestUtil.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
index 32f27ead4afa9..6482a9375f565 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,6 +41,7 @@
import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.diagnostics.rendering.Renderers.*;
+import static org.jetbrains.kotlin.diagnostics.rendering.RenderingContext.*;
public class DefaultErrorMessages {
@@ -118,11 +119,13 @@ public static DiagnosticRenderer getRendererForDiagnostic(@NotNull Diagnostic di
@NotNull
@Override
public String[] render(@NotNull TypeMismatchDueToTypeProjectionsData object) {
+ RenderingContext context =
+ of(object.getExpectedType(), object.getExpressionType(), object.getReceiverType(), object.getCallableDescriptor());
return new String[] {
- RENDER_TYPE.render(object.getExpectedType()),
- RENDER_TYPE.render(object.getExpressionType()),
- RENDER_TYPE.render(object.getReceiverType()),
- DescriptorRenderer.FQ_NAMES_IN_TYPES.render(object.getCallableDescriptor())
+ RENDER_TYPE.render(object.getExpectedType(), context),
+ RENDER_TYPE.render(object.getExpressionType(), context),
+ RENDER_TYPE.render(object.getReceiverType(), context),
+ FQ_NAMES_IN_TYPES.render(object.getCallableDescriptor(), context)
};
}
});
@@ -175,7 +178,7 @@ public String[] render(@NotNull TypeMismatchDueToTypeProjectionsData object) {
MAP.put(NAMED_ARGUMENTS_NOT_ALLOWED, "Named arguments are not allowed for {0}", new DiagnosticParameterRenderer<BadNamedArgumentsTarget>() {
@NotNull
@Override
- public String render(@NotNull BadNamedArgumentsTarget target) {
+ public String render(@NotNull BadNamedArgumentsTarget target, @NotNull RenderingContext context) {
switch (target) {
case NON_KOTLIN_FUNCTION:
return "non-Kotlin functions";
@@ -391,7 +394,7 @@ public String render(@NotNull BadNamedArgumentsTarget target) {
MAP.put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expressions are allowed here", new DiagnosticParameterRenderer<KtExpression>() {
@NotNull
@Override
- public String render(@NotNull KtExpression expression) {
+ public String render(@NotNull KtExpression expression, @NotNull RenderingContext context) {
String expressionType = expression.toString();
return expressionType.substring(0, 1) +
expressionType.substring(1).toLowerCase();
@@ -487,7 +490,7 @@ public String render(@NotNull KtExpression expression) {
MAP.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", new DiagnosticParameterRenderer<KtTypeConstraint>() {
@NotNull
@Override
- public String render(@NotNull KtTypeConstraint typeConstraint) {
+ public String render(@NotNull KtTypeConstraint typeConstraint, @NotNull RenderingContext context) {
//noinspection ConstantConditions
return typeConstraint.getSubjectTypeParameterName().getReferencedName();
}
@@ -509,11 +512,13 @@ public String render(@NotNull KtTypeConstraint typeConstraint) {
@NotNull
@Override
public String[] render(@NotNull VarianceConflictDiagnosticData data) {
+ RenderingContext context =
+ of(data.getTypeParameter(), data.getTypeParameter().getVariance(), data.getOccurrencePosition(), data.getContainingType());
return new String[] {
- NAME.render(data.getTypeParameter()),
- RENDER_POSITION_VARIANCE.render(data.getTypeParameter().getVariance()),
- RENDER_POSITION_VARIANCE.render(data.getOccurrencePosition()),
- RENDER_TYPE.render(data.getContainingType())
+ NAME.render(data.getTypeParameter(), context),
+ RENDER_POSITION_VARIANCE.render(data.getTypeParameter().getVariance(), context),
+ RENDER_POSITION_VARIANCE.render(data.getOccurrencePosition(), context),
+ RENDER_TYPE.render(data.getContainingType(), context)
};
}
});
@@ -548,7 +553,7 @@ public String[] render(@NotNull VarianceConflictDiagnosticData data) {
MAP.put(EQUALITY_NOT_APPLICABLE, "Operator ''{0}'' cannot be applied to ''{1}'' and ''{2}''", new DiagnosticParameterRenderer<KtSimpleNameExpression>() {
@NotNull
@Override
- public String render(@NotNull KtSimpleNameExpression nameExpression) {
+ public String render(@NotNull KtSimpleNameExpression nameExpression, @NotNull RenderingContext context) {
//noinspection ConstantConditions
return nameExpression.getReferencedName();
}
@@ -603,15 +608,15 @@ public String render(@NotNull KtSimpleNameExpression nameExpression) {
ELEMENT_TEXT, new DiagnosticParameterRenderer<KotlinType>() {
@NotNull
@Override
- public String render(@NotNull KotlinType type) {
+ public String render(@NotNull KotlinType type, @NotNull RenderingContext context) {
if (type.isError()) return "";
- return " of type '" + RENDER_TYPE.render(type) + "'";
+ return " of type '" + RENDER_TYPE.render(type, context) + "'";
}
});
MAP.put(FUNCTION_CALL_EXPECTED, "Function invocation ''{0}({1})'' expected", ELEMENT_TEXT, new DiagnosticParameterRenderer<Boolean>() {
@NotNull
@Override
- public String render(@NotNull Boolean hasValueParameters) {
+ public String render(@NotNull Boolean hasValueParameters, @NotNull RenderingContext context) {
return hasValueParameters ? "..." : "";
}
});
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticParameterRenderer.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticParameterRenderer.kt
index 5efb23fcc284b..1d445f643ca9e 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticParameterRenderer.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticParameterRenderer.kt
@@ -17,9 +17,13 @@
package org.jetbrains.kotlin.diagnostics.rendering
interface DiagnosticParameterRenderer<in O> {
- fun render(obj: O): String
+ fun render(obj: O, renderingContext: RenderingContext): String
}
fun <O> Renderer(block: (O) -> String) = object : DiagnosticParameterRenderer<O> {
- override fun render(obj: O) = block(obj)
+ override fun render(obj: O, renderingContext: RenderingContext): String = block(obj)
+}
+
+fun <O> ContextDependentRenderer(block: (O, RenderingContext) -> String) = object : DiagnosticParameterRenderer<O> {
+ override fun render(obj: O, renderingContext: RenderingContext): String = block(obj, renderingContext)
}
\ No newline at end of file
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRendererUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRendererUtil.kt
index 644df659948e5..34a20f8d8ebc0 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRendererUtil.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRendererUtil.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,8 @@ package org.jetbrains.kotlin.diagnostics.rendering
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.renderer.DescriptorRenderer
-fun <P : Any> renderParameter(parameter: P, renderer: DiagnosticParameterRenderer<P>?): Any = renderer?.render(parameter) ?: parameter
+fun <P : Any> renderParameter(parameter: P, renderer: DiagnosticParameterRenderer<P>?, context: RenderingContext): Any
+ = renderer?.render(parameter, context) ?: parameter
fun ClassDescriptor.renderKindWithName(): String = DescriptorRenderer.getClassKindPrefix(this) + " '" + name + "'"
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt
index 1703a62e53737..8bfd10ad4e0a1 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -122,19 +122,20 @@ object Renderers {
@JvmField val AMBIGUOUS_CALLS = Renderer {
calls: Collection<ResolvedCall<*>> ->
- calls
- .map { it.resultingDescriptor }
+ val descriptors = calls.map { it.resultingDescriptor }
+ val context = RenderingContext.Impl(descriptors)
+ descriptors
.sortedWith(MemberComparator.INSTANCE)
- .joinToString(separator = "\n", prefix = "\n") { DescriptorRenderer.FQ_NAMES_IN_TYPES.render(it) }
+ .joinToString(separator = "\n", prefix = "\n") { FQ_NAMES_IN_TYPES.render(it, context) }
}
- @JvmStatic fun <T> commaSeparated(itemRenderer: DiagnosticParameterRenderer<T>) = Renderer<Collection<T>> {
- collection ->
+ @JvmStatic fun <T> commaSeparated(itemRenderer: DiagnosticParameterRenderer<T>) = ContextDependentRenderer<Collection<T>> {
+ collection, context ->
buildString {
val iterator = collection.iterator()
while (iterator.hasNext()) {
val next = iterator.next()
- append(itemRenderer.render(next))
+ append(itemRenderer.render(next, context))
if (iterator.hasNext()) {
append(", ")
}
@@ -166,7 +167,7 @@ object Renderers {
inferenceErrorData: InferenceErrorData, result: TabledDescriptorRenderer
): TabledDescriptorRenderer {
LOG.assertTrue(inferenceErrorData.constraintSystem.status.hasConflictingConstraints(),
- renderDebugMessage("Conflicting substitutions inference error renderer is applied for incorrect status", inferenceErrorData))
+ debugMessage("Conflicting substitutions inference error renderer is applied for incorrect status", inferenceErrorData))
val substitutedDescriptors = Lists.newArrayList<CallableDescriptor>()
val substitutors = ConstraintsUtil.getSubstitutorsForConflictingParameters(inferenceErrorData.constraintSystem)
@@ -177,7 +178,7 @@ object Renderers {
val firstConflictingVariable = ConstraintsUtil.getFirstConflictingVariable(inferenceErrorData.constraintSystem)
if (firstConflictingVariable == null) {
- LOG.error(renderDebugMessage("There is no conflicting parameter for 'conflicting constraints' error.", inferenceErrorData))
+ LOG.error(debugMessage("There is no conflicting parameter for 'conflicting constraints' error.", inferenceErrorData))
return result
}
@@ -238,7 +239,7 @@ object Renderers {
val firstUnknownVariable = inferenceErrorData.constraintSystem.typeVariables.firstOrNull { variable ->
inferenceErrorData.constraintSystem.getTypeBounds(variable).values.isEmpty()
} ?: return result.apply {
- LOG.error(renderDebugMessage("There is no unknown parameter for 'no information for parameter error'.", inferenceErrorData))
+ LOG.error(debugMessage("There is no unknown parameter for 'no information for parameter error'.", inferenceErrorData))
}
return result
@@ -256,7 +257,7 @@ object Renderers {
val constraintSystem = inferenceErrorData.constraintSystem
val status = constraintSystem.status
LOG.assertTrue(status.hasViolatedUpperBound(),
- renderDebugMessage("Upper bound violated renderer is applied for incorrect status", inferenceErrorData))
+ debugMessage("Upper bound violated renderer is applied for incorrect status", inferenceErrorData))
val systemWithoutWeakConstraints = constraintSystem.filterConstraintsOut(ConstraintPositionKind.TYPE_BOUND_POSITION)
val typeParameterDescriptor = inferenceErrorData.descriptor.typeParameters.firstOrNull {
@@ -266,15 +267,15 @@ object Renderers {
return renderConflictingSubstitutionsInferenceError(inferenceErrorData, result)
}
if (typeParameterDescriptor == null) {
- LOG.error(renderDebugMessage("There is no type parameter with violated upper bound for 'upper bound violated' error", inferenceErrorData))
+ LOG.error(debugMessage("There is no type parameter with violated upper bound for 'upper bound violated' error", inferenceErrorData))
return result
}
val typeVariable = systemWithoutWeakConstraints.descriptorToVariable(inferenceErrorData.call.toHandle(), typeParameterDescriptor)
val inferredValueForTypeParameter = systemWithoutWeakConstraints.getTypeBounds(typeVariable).value
if (inferredValueForTypeParameter == null) {
- LOG.error(renderDebugMessage("System without weak constraints is not successful, there is no value for type parameter " +
- typeParameterDescriptor.name + "\n: " + systemWithoutWeakConstraints, inferenceErrorData))
+ LOG.error(debugMessage("System without weak constraints is not successful, there is no value for type parameter " +
+ typeParameterDescriptor.name + "\n: " + systemWithoutWeakConstraints, inferenceErrorData))
return result
}
@@ -295,17 +296,19 @@ object Renderers {
}
}
if (violatedUpperBound == null) {
- LOG.error(renderDebugMessage("Type parameter (chosen as violating its upper bound)" +
- typeParameterDescriptor.name + " violates no bounds after substitution", inferenceErrorData))
+ LOG.error(debugMessage("Type parameter (chosen as violating its upper bound)" +
+ typeParameterDescriptor.name + " violates no bounds after substitution", inferenceErrorData))
return result
}
+ // TODO: context should be in fact shared for the table and these two types
+ val context = RenderingContext.of(inferredValueForTypeParameter, violatedUpperBound)
val typeRenderer = result.typeRenderer
result.text(newText()
.normal(" is not satisfied: inferred type ")
- .error(typeRenderer.render(inferredValueForTypeParameter))
+ .error(typeRenderer.render(inferredValueForTypeParameter, context))
.normal(" is not a subtype of ")
- .strong(typeRenderer.render(violatedUpperBound)))
+ .strong(typeRenderer.render(violatedUpperBound, context)))
return result
}
@@ -316,7 +319,7 @@ object Renderers {
val errors = system.status.constraintErrors
val typeVariableWithCapturedConstraint = errors.firstIsInstanceOrNull<CannotCapture>()?.typeVariable
if (typeVariableWithCapturedConstraint == null) {
- LOG.error(renderDebugMessage("An error 'cannot capture type parameter' is not found in errors", inferenceErrorData))
+ LOG.error(debugMessage("An error 'cannot capture type parameter' is not found in errors", inferenceErrorData))
return result
}
@@ -324,7 +327,7 @@ object Renderers {
val boundWithCapturedType = typeBounds.bounds.firstOrNull { it.constrainingType.isCaptured() }
val capturedTypeConstructor = boundWithCapturedType?.constrainingType?.constructor as? CapturedTypeConstructor
if (capturedTypeConstructor == null) {
- LOG.error(renderDebugMessage("There is no captured type in bounds, but there is an error 'cannot capture type parameter'", inferenceErrorData))
+ LOG.error(debugMessage("There is no captured type in bounds, but there is an error 'cannot capture type parameter'", inferenceErrorData))
return result
}
@@ -333,7 +336,7 @@ object Renderers {
val explanation: String
val upperBound = TypeIntersector.getUpperBoundsAsType(typeParameter)
if (!KotlinBuiltIns.isNullableAny(upperBound) && capturedTypeConstructor.typeProjection.projectionKind == Variance.IN_VARIANCE) {
- explanation = "Type parameter has an upper bound '" + result.typeRenderer.render(upperBound) + "'" +
+ explanation = "Type parameter has an upper bound '" + result.typeRenderer.render(upperBound, RenderingContext.of(upperBound)) + "'" +
" that cannot be satisfied capturing 'in' projection"
}
else {
@@ -365,24 +368,20 @@ object Renderers {
}
}
- private fun renderTypes(types: Collection<KotlinType>) = StringUtil.join(types, { RENDER_TYPE.render(it) }, ", ")
+ private fun renderTypes(types: Collection<KotlinType>, context: RenderingContext) = StringUtil.join(types, { RENDER_TYPE.render(it, context) }, ", ")
- @JvmField val RENDER_COLLECTION_OF_TYPES = Renderer<Collection<KotlinType>> { renderTypes(it) }
+ @JvmField val RENDER_COLLECTION_OF_TYPES = ContextDependentRenderer<Collection<KotlinType>> { types, context -> renderTypes(types, context) }
- private fun renderConstraintSystem(constraintSystem: ConstraintSystem, renderTypeBounds: DiagnosticParameterRenderer<TypeBounds>): String {
+ fun renderConstraintSystem(constraintSystem: ConstraintSystem, shortTypeBounds: Boolean): String {
val typeBounds = linkedSetOf<TypeBounds>()
for (variable in constraintSystem.typeVariables) {
typeBounds.add(constraintSystem.getTypeBounds(variable))
}
return "type parameter bounds:\n" +
- StringUtil.join(typeBounds, { renderTypeBounds.render(it) }, "\n") + "\n\n" + "status:\n" +
+ StringUtil.join(typeBounds, { renderTypeBounds(it, short = shortTypeBounds) }, "\n") + "\n\n" + "status:\n" +
ConstraintsUtil.getDebugMessageForStatus(constraintSystem.status)
}
- @JvmField val RENDER_CONSTRAINT_SYSTEM = Renderer<ConstraintSystem> { renderConstraintSystem(it, RENDER_TYPE_BOUNDS) }
-
- @JvmField val RENDER_CONSTRAINT_SYSTEM_SHORT = Renderer<ConstraintSystem> { renderConstraintSystem(it, RENDER_TYPE_BOUNDS_SHORT) }
-
private fun renderTypeBounds(typeBounds: TypeBounds, short: Boolean): String {
val renderBound = { bound: Bound ->
val arrow = if (bound.kind == LOWER_BOUND) ">: " else if (bound.kind == UPPER_BOUND) "<: " else ":= "
@@ -398,28 +397,25 @@ object Renderers {
"$typeVariableName ${StringUtil.join(typeBounds.bounds, renderBound, ", ")}"
}
- @JvmField val RENDER_TYPE_BOUNDS = Renderer<TypeBounds> { renderTypeBounds(it, short = false) }
-
- @JvmField val RENDER_TYPE_BOUNDS_SHORT = Renderer<TypeBounds> { renderTypeBounds(it, short = true) }
-
- private fun renderDebugMessage(message: String, inferenceErrorData: InferenceErrorData) = buildString {
+ private fun debugMessage(message: String, inferenceErrorData: InferenceErrorData) = buildString {
append(message)
append("\nConstraint system: \n")
- append(RENDER_CONSTRAINT_SYSTEM.render(inferenceErrorData.constraintSystem))
+ append(renderConstraintSystem(inferenceErrorData.constraintSystem, false))
append("\nDescriptor:\n")
append(inferenceErrorData.descriptor)
append("\nExpected type:\n")
+ val context = RenderingContext.Empty
if (TypeUtils.noExpectedType(inferenceErrorData.expectedType)) {
append(inferenceErrorData.expectedType)
}
else {
- append(RENDER_TYPE.render(inferenceErrorData.expectedType))
+ append(RENDER_TYPE.render(inferenceErrorData.expectedType, context))
}
append("\nArgument types:\n")
if (inferenceErrorData.receiverArgumentType != null) {
- append(RENDER_TYPE.render(inferenceErrorData.receiverArgumentType)).append(".")
+ append(RENDER_TYPE.render(inferenceErrorData.receiverArgumentType, context)).append(".")
}
- append("(").append(renderTypes(inferenceErrorData.valueArgumentsTypes)).append(")")
+ append("(").append(renderTypes(inferenceErrorData.valueArgumentsTypes, context)).append(")")
}
private val WHEN_MISSING_LIMIT = 7
@@ -448,4 +444,4 @@ object Renderers {
fun DescriptorRenderer.asRenderer() = Renderer<DeclarationDescriptor> {
render(it)
-}
\ No newline at end of file
+}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt
new file mode 100644
index 0000000000000..0c2c56b5e2587
--- /dev/null
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2010-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jetbrains.kotlin.diagnostics.rendering
+
+import org.jetbrains.kotlin.diagnostics.*
+
+// holds data about the parameters of the diagnostic we're about to render
+sealed class RenderingContext {
+ abstract operator fun <T> get(key: Key<T>): T
+
+ abstract class Key<T>(val name: String) {
+ abstract fun compute(objectsToRender: Collection<Any?>): T
+ }
+
+ class Impl(private val objectsToRender: Collection<Any?>) : RenderingContext() {
+ private val data = linkedMapOf<Key<*>, Any?>()
+
+ override fun <T> get(key: Key<T>): T {
+ if (!data.containsKey(key)) {
+ val result = key.compute(objectsToRender)
+ data[key] = result
+ return result
+ }
+ return data[key] as T
+ }
+ }
+
+
+ object Empty : RenderingContext() {
+ override fun <T> get(key: Key<T>): T {
+ return key.compute(emptyList())
+ }
+ }
+
+ companion object {
+ @JvmStatic
+ fun of(vararg objectsToRender: Any?): RenderingContext {
+ return Impl(objectsToRender.toList())
+ }
+
+ @JvmStatic
+ fun fromDiagnostic(d: Diagnostic): RenderingContext {
+ val parameters = when (d) {
+ is SimpleDiagnostic<*> -> listOf()
+ is DiagnosticWithParameters1<*, *> -> listOf(d.a)
+ is DiagnosticWithParameters2<*, *, *> -> listOf(d.a, d.b)
+ is DiagnosticWithParameters3<*, *, *, *> -> listOf(d.a, d.b, d.c)
+ is ParametrizedDiagnostic<*> -> error("Unexpected diagnostic: ${d.javaClass}")
+ else -> listOf()
+ }
+ return Impl(parameters)
+ }
+ }
+}
\ No newline at end of file
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/TabledDescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/TabledDescriptorRenderer.java
index f9677583991b4..05e5c1eb89639 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/TabledDescriptorRenderer.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/TabledDescriptorRenderer.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,10 +26,10 @@
import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TableRenderer.FunctionArgumentsRow;
import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TableRenderer.TableRow;
import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TextRenderer.TextElement;
-import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.ConstraintPosition;
import org.jetbrains.kotlin.types.KotlinType;
+import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -167,26 +167,33 @@ protected void renderText(TextRenderer textRenderer, StringBuilder result) {
protected void renderTable(TableRenderer table, StringBuilder result) {
if (table.rows.isEmpty()) return;
+
+ RenderingContext context = computeRenderingContext(table);
for (TableRow row : table.rows) {
if (row instanceof TextRenderer) {
renderText((TextRenderer) row, result);
}
if (row instanceof DescriptorRow) {
- result.append(DescriptorRenderer.COMPACT.render(((DescriptorRow) row).descriptor));
+ result.append(Renderers.COMPACT.render(((DescriptorRow) row).descriptor, context));
}
if (row instanceof FunctionArgumentsRow) {
FunctionArgumentsRow functionArgumentsRow = (FunctionArgumentsRow) row;
- renderFunctionArguments(functionArgumentsRow.receiverType, functionArgumentsRow.argumentTypes, result);
+ renderFunctionArguments(functionArgumentsRow.receiverType, functionArgumentsRow.argumentTypes, result, context);
}
result.append("\n");
}
}
- private void renderFunctionArguments(@Nullable KotlinType receiverType, @NotNull List<KotlinType> argumentTypes, StringBuilder result) {
+ private void renderFunctionArguments(
+ @Nullable KotlinType receiverType,
+ @NotNull List<KotlinType> argumentTypes,
+ StringBuilder result,
+ @NotNull RenderingContext context
+ ) {
boolean hasReceiver = receiverType != null;
if (hasReceiver) {
result.append("receiver: ");
- result.append(getTypeRenderer().render(receiverType));
+ result.append(getTypeRenderer().render(receiverType, context));
result.append(" arguments: ");
}
if (argumentTypes.isEmpty()) {
@@ -197,7 +204,7 @@ private void renderFunctionArguments(@Nullable KotlinType receiverType, @NotNull
result.append("(");
for (Iterator<KotlinType> iterator = argumentTypes.iterator(); iterator.hasNext(); ) {
KotlinType argumentType = iterator.next();
- String renderedArgument = getTypeRenderer().render(argumentType);
+ String renderedArgument = getTypeRenderer().render(argumentType, context);
result.append(renderedArgument);
if (iterator.hasNext()) {
@@ -212,4 +219,25 @@ public static TabledDescriptorRenderer create() {
}
public static enum TextElementType { STRONG, ERROR, DEFAULT }
+
+ @NotNull
+ protected static RenderingContext computeRenderingContext(@NotNull TableRenderer table) {
+ ArrayList<Object> toRender = new ArrayList<Object>();
+ for (TableRow row : table.rows) {
+ if (row instanceof DescriptorRow) {
+ toRender.add(((DescriptorRow) row).descriptor);
+ }
+ else if (row instanceof FunctionArgumentsRow) {
+ toRender.add(((FunctionArgumentsRow) row).receiverType);
+ toRender.addAll(((FunctionArgumentsRow) row).argumentTypes);
+ }
+ else if (row instanceof TextRenderer) {
+
+ }
+ else {
+ throw new AssertionError("Unknown row of type " + row.getClass());
+ }
+ }
+ return new RenderingContext.Impl(toRender);
+ }
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt
index 42b567ed62c05..7aeccb372812d 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt
@@ -42,10 +42,9 @@ class DiagnosticWithParameters1Renderer<A : Any>(
) : AbstractDiagnosticWithParametersRenderer<DiagnosticWithParameters1<*, A>>(message) {
override fun renderParameters(diagnostic: DiagnosticWithParameters1<*, A>): Array<out Any> {
- return arrayOf(renderParameter(diagnostic.a, rendererForA))
+ val context = RenderingContext.of(diagnostic.a)
+ return arrayOf(renderParameter(diagnostic.a, rendererForA, context))
}
-
-
}
class DiagnosticWithParameters2Renderer<A : Any, B : Any>(
@@ -55,9 +54,10 @@ class DiagnosticWithParameters2Renderer<A : Any, B : Any>(
) : AbstractDiagnosticWithParametersRenderer<DiagnosticWithParameters2<*, A, B>>(message) {
override fun renderParameters(diagnostic: DiagnosticWithParameters2<*, A, B>): Array<out Any> {
+ val context = RenderingContext.of(diagnostic.a, diagnostic.b)
return arrayOf(
- renderParameter(diagnostic.a, rendererForA),
- renderParameter(diagnostic.b, rendererForB)
+ renderParameter(diagnostic.a, rendererForA, context),
+ renderParameter(diagnostic.b, rendererForB, context)
)
}
}
@@ -70,10 +70,11 @@ class DiagnosticWithParameters3Renderer<A : Any, B : Any, C : Any>(
) : AbstractDiagnosticWithParametersRenderer<DiagnosticWithParameters3<*, A, B, C>>(message) {
override fun renderParameters(diagnostic: DiagnosticWithParameters3<*, A, B, C>): Array<out Any> {
+ val context = RenderingContext.of(diagnostic.a, diagnostic.b, diagnostic.c)
return arrayOf(
- renderParameter(diagnostic.a, rendererForA),
- renderParameter(diagnostic.b, rendererForB),
- renderParameter(diagnostic.c, rendererForC)
+ renderParameter(diagnostic.a, rendererForA, context),
+ renderParameter(diagnostic.b, rendererForB, context),
+ renderParameter(diagnostic.c, rendererForC, context)
)
}
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.java
index b297cd15d34a0..5e8c2620c996c 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,15 +17,17 @@
package org.jetbrains.kotlin.resolve;
import com.google.common.collect.Lists;
+import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
+import com.intellij.util.Function;
import kotlin.Pair;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.*;
-import org.jetbrains.kotlin.diagnostics.rendering.Renderers;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;
+import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilKt;
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystem;
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemCompleter;
@@ -34,8 +36,8 @@
import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults;
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo;
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfoFactory;
-import org.jetbrains.kotlin.resolve.scopes.ScopeUtils;
import org.jetbrains.kotlin.resolve.scopes.LexicalScope;
+import org.jetbrains.kotlin.resolve.scopes.ScopeUtils;
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver;
import org.jetbrains.kotlin.resolve.validation.OperatorValidator;
import org.jetbrains.kotlin.resolve.validation.SymbolUsageValidator;
@@ -308,7 +310,13 @@ private static String renderCall(@NotNull Call call, @NotNull BindingContext con
argumentTypes.add(context.getType(argument.getArgumentExpression()));
}
- builder.append(Renderers.RENDER_COLLECTION_OF_TYPES.render(argumentTypes));
+ String arguments = StringUtil.join(argumentTypes, new Function<KotlinType, String>() {
+ @Override
+ public String fun(KotlinType type) {
+ return DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type);
+ }
+ }, ", ");
+ builder.append(arguments);
builder.append(")");
return builder.toString();
}
diff --git a/compiler/tests/org/jetbrains/kotlin/resolve/constraintSystem/AbstractConstraintSystemTest.kt b/compiler/tests/org/jetbrains/kotlin/resolve/constraintSystem/AbstractConstraintSystemTest.kt
index 53f7dcdac837a..245a6245b83d0 100644
--- a/compiler/tests/org/jetbrains/kotlin/resolve/constraintSystem/AbstractConstraintSystemTest.kt
+++ b/compiler/tests/org/jetbrains/kotlin/resolve/constraintSystem/AbstractConstraintSystemTest.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -110,7 +110,7 @@ abstract class AbstractConstraintSystemTest() : KotlinLiteFixture() {
val system = builder.build()
- val resultingStatus = Renderers.RENDER_CONSTRAINT_SYSTEM_SHORT.render(system)
+ val resultingStatus = Renderers.renderConstraintSystem(system, shortTypeBounds = true)
val resultingSubstitutor = system.resultingSubstitutor
val result = typeParameterDescriptors.map {
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HtmlTabledDescriptorRenderer.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HtmlTabledDescriptorRenderer.java
index 1681670d7e11c..737fb172390ec 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HtmlTabledDescriptorRenderer.java
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HtmlTabledDescriptorRenderer.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor;
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticParameterRenderer;
+import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext;
import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer;
import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TableRenderer.DescriptorRow;
import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TableRenderer.FunctionArgumentsRow;
@@ -94,9 +95,10 @@ else if (row instanceof FunctionArgumentsRow) {
@Override
protected void renderTable(TableRenderer table, StringBuilder result) {
if (table.rows.isEmpty()) return;
- int rowsNumber = countColumnNumber(table);
+ RenderingContext context = computeRenderingContext(table);
+ int rowsNumber = countColumnNumber(table);
result.append("<table>");
for (TableRow row : table.rows) {
result.append("<tr>");
@@ -111,7 +113,7 @@ protected void renderTable(TableRenderer table, StringBuilder result) {
}
if (row instanceof FunctionArgumentsRow) {
FunctionArgumentsRow functionArgumentsRow = (FunctionArgumentsRow) row;
- renderFunctionArguments(functionArgumentsRow.receiverType, functionArgumentsRow.argumentTypes, functionArgumentsRow.isErrorPosition, result);
+ renderFunctionArguments(functionArgumentsRow.receiverType, functionArgumentsRow.argumentTypes, functionArgumentsRow.isErrorPosition, result, context);
}
result.append("</tr>");
}
@@ -124,7 +126,8 @@ private void renderFunctionArguments(
@Nullable KotlinType receiverType,
@NotNull List<KotlinType> argumentTypes,
Predicate<ConstraintPosition> isErrorPosition,
- StringBuilder result
+ StringBuilder result,
+ @NotNull RenderingContext context
) {
boolean hasReceiver = receiverType != null;
tdSpace(result);
@@ -134,7 +137,7 @@ private void renderFunctionArguments(
if (isErrorPosition.apply(RECEIVER_POSITION.position())) {
error = true;
}
- receiver = "receiver: " + RenderersUtilKt.renderStrong(getTypeRenderer().render(receiverType), error);
+ receiver = "receiver: " + RenderersUtilKt.renderStrong(getTypeRenderer().render(receiverType, context), error);
}
td(result, receiver);
td(result, hasReceiver ? "arguments: " : "");
@@ -151,7 +154,7 @@ private void renderFunctionArguments(
if (isErrorPosition.apply(VALUE_PARAMETER_POSITION.position(i))) {
error = true;
}
- String renderedArgument = getTypeRenderer().render(argumentType);
+ String renderedArgument = getTypeRenderer().render(argumentType, context);
tdRight(result, RenderersUtilKt.renderStrong(renderedArgument, error) + (iterator.hasNext() ? RenderersUtilKt.renderStrong(",") : ""));
i++;
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeErrorMessages.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeErrorMessages.java
index 941e062eba6c5..dc856c556b7c7 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeErrorMessages.java
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeErrorMessages.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -71,11 +71,13 @@ public static boolean hasIdeSpecificMessage(@NotNull Diagnostic diagnostic) {
@NotNull
@Override
public String[] render(@NotNull TypeMismatchDueToTypeProjectionsData object) {
+ RenderingContext context = RenderingContext
+ .of(object.getExpectedType(), object.getExpressionType(), object.getReceiverType(), object.getCallableDescriptor());
return new String[] {
- HTML_RENDER_TYPE.render(object.getExpectedType()),
- HTML_RENDER_TYPE.render(object.getExpressionType()),
- HTML_RENDER_TYPE.render(object.getReceiverType()),
- HTML.render(object.getCallableDescriptor())
+ HTML_RENDER_TYPE.render(object.getExpectedType(), context),
+ HTML_RENDER_TYPE.render(object.getExpressionType(), context),
+ HTML_RENDER_TYPE.render(object.getReceiverType(), context),
+ HTML.render(object.getCallableDescriptor(), context)
};
}
});
diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt
index b21f0747335d3..38d14e749071c 100644
--- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt
+++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.idea.highlighter
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
+import org.jetbrains.kotlin.diagnostics.rendering.ContextDependentRenderer
import org.jetbrains.kotlin.diagnostics.rendering.Renderer
import org.jetbrains.kotlin.diagnostics.rendering.Renderers
import org.jetbrains.kotlin.diagnostics.rendering.asRenderer
@@ -67,28 +68,29 @@ object IdeRenderers {
Renderers.renderUpperBoundViolatedInferenceError(it, HtmlTabledDescriptorRenderer.create()).toString()
}
- @JvmField val HTML_RENDER_RETURN_TYPE = Renderer<CallableMemberDescriptor> {
- val returnType = it.returnType!!
- DescriptorRenderer.HTML.renderType(returnType)
+ @JvmField val HTML_RENDER_RETURN_TYPE = ContextDependentRenderer<CallableMemberDescriptor> {
+ member, context ->
+ HTML_RENDER_TYPE.render(member.returnType!!, context)
}
@JvmField val HTML_COMPACT_WITH_MODIFIERS = DescriptorRenderer.HTML.withOptions {
withDefinedIn = false
}.asRenderer()
- @JvmField val HTML_CONFLICTING_JVM_DECLARATIONS_DATA = Renderer {
- data: ConflictingJvmDeclarationsData ->
+ @JvmField val HTML_CONFLICTING_JVM_DECLARATIONS_DATA = ContextDependentRenderer {
+ data: ConflictingJvmDeclarationsData, renderingContext ->
val conflicts = data.signatureOrigins
- .mapNotNull { it.descriptor }
- .sortedWith(MemberComparator.INSTANCE)
- .joinToString("") { "<li>" + HTML_COMPACT_WITH_MODIFIERS.render(it) + "</li>\n" }
+ .mapNotNull { it.descriptor }
+ .sortedWith(MemberComparator.INSTANCE)
+ .joinToString("") { "<li>" + HTML_COMPACT_WITH_MODIFIERS.render(it, renderingContext) + "</li>\n" }
"The following declarations have the same JVM signature (<code>${data.signature.name}${data.signature.desc}</code>):<br/>\n<ul>\n$conflicts</ul>"
}
- @JvmField val HTML_THROWABLE = Renderer<Throwable> {
- Renderers.THROWABLE.render(it).replace("\n", "<br/>")
+ @JvmField val HTML_THROWABLE = ContextDependentRenderer<Throwable> {
+ throwable, context ->
+ Renderers.THROWABLE.render(throwable, context).replace("\n", "<br/>")
}
@JvmField val HTML = DescriptorRenderer.HTML.asRenderer()
diff --git a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/jsRenderers.kt b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/jsRenderers.kt
index 66a5984a21b68..edf40981acc28 100644
--- a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/jsRenderers.kt
+++ b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/jsRenderers.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2015 JetBrains s.r.o.
+ * Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,9 +19,10 @@ package org.jetbrains.kotlin.js.resolve.diagnostics
import com.google.gwt.dev.js.rhino.Utils.isEndOfLine
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticParameterRenderer
+import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext
object RenderFirstLineOfElementText : DiagnosticParameterRenderer<PsiElement> {
- override fun render(element: PsiElement): String {
+ override fun render(element: PsiElement, context: RenderingContext): String {
val text = element.text
val index = text.indexOf('\n')
return if (index == -1) text else text.substring(0, index) + "..."
@@ -31,7 +32,7 @@ object RenderFirstLineOfElementText : DiagnosticParameterRenderer<PsiElement> {
abstract class JsCallDataRenderer : DiagnosticParameterRenderer<JsCallData> {
protected abstract fun format(data: JsCallDataWithCode): String
- override fun render(data: JsCallData): String =
+ override fun render(data: JsCallData, context: RenderingContext): String =
when (data) {
is JsCallDataWithCode -> format(data)
is JsCallData -> data.message
|
079039e5531a152388776c637884c891974008e5
|
restlet-framework-java
|
Fixed generation of cache directives in the- cache-control header.--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet/src/org/restlet/data/CacheDirective.java b/modules/org.restlet/src/org/restlet/data/CacheDirective.java
index ea761871b3..d76af1d136 100644
--- a/modules/org.restlet/src/org/restlet/data/CacheDirective.java
+++ b/modules/org.restlet/src/org/restlet/data/CacheDirective.java
@@ -65,7 +65,7 @@ public final class CacheDirective extends Parameter {
*/
public static CacheDirective maxAge(int maxAge) {
return new CacheDirective(HttpConstants.CACHE_MAX_AGE, Integer
- .toString(maxAge));
+ .toString(maxAge), true);
}
/**
@@ -100,7 +100,7 @@ public static CacheDirective maxStale() {
*/
public static CacheDirective maxStale(int maxStale) {
return new CacheDirective(HttpConstants.CACHE_MAX_STALE, Integer
- .toString(maxStale));
+ .toString(maxStale), true);
}
/**
@@ -121,7 +121,7 @@ public static CacheDirective maxStale(int maxStale) {
*/
public static CacheDirective minFresh(int minFresh) {
return new CacheDirective(HttpConstants.CACHE_MIN_FRESH, Integer
- .toString(minFresh));
+ .toString(minFresh), true);
}
/**
@@ -366,9 +366,12 @@ public static CacheDirective publicInfo() {
*/
public static CacheDirective sharedMaxAge(int sharedMaxAge) {
return new CacheDirective(HttpConstants.CACHE_SHARED_MAX_AGE, Integer
- .toString(sharedMaxAge));
+ .toString(sharedMaxAge), true);
}
+ /** Indicates if the directive is a digit value. */
+ private boolean digit;
+
/**
* Constructor for directives with no value.
*
@@ -388,7 +391,40 @@ public CacheDirective(String name) {
* The directive value.
*/
public CacheDirective(String name, String value) {
+ this(name, value, false);
+ }
+
+ /**
+ * Constructor for directives with a value.
+ *
+ * @param name
+ * The directive name.
+ * @param value
+ * The directive value.
+ * @param digit
+ * The kind of value (true for a digit value, false otherwise).
+ */
+ public CacheDirective(String name, String value, boolean digit) {
super(name, value);
+ this.digit = digit;
+ }
+
+ /**
+ * Returns true if the directive contains a digit value.
+ *
+ * @return True if the directive contains a digit value.
+ */
+ public boolean isDigit() {
+ return digit;
}
+ /**
+ * Indicates if the directive is a digit value.
+ *
+ * @param digit
+ * True if the directive contains a digit value.
+ */
+ public void setDigit(boolean digit) {
+ this.digit = digit;
+ }
}
\ No newline at end of file
diff --git a/modules/org.restlet/src/org/restlet/engine/http/CacheControlUtils.java b/modules/org.restlet/src/org/restlet/engine/http/CacheControlUtils.java
index 2cb24cb23c..fa03ab607a 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/CacheControlUtils.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/CacheControlUtils.java
@@ -84,7 +84,12 @@ public static void format(CacheDirective directive, Appendable destination)
destination.append(directive.getName());
if ((directive.getValue() != null)
&& (directive.getValue().length() > 0)) {
- destination.append("=\"").append(directive.getValue()).append('\"');
+ if (directive.isDigit()) {
+ destination.append("=").append(directive.getValue());
+ } else {
+ destination.append("=\"").append(directive.getValue()).append(
+ '\"');
+ }
}
}
}
|
50e3ca62e5b5cceb13ead212f50aaae57e8990f5
|
orientdb
|
Working to fix corrupted data in sockets--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OBinaryNetworkProtocolAbstract.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OBinaryNetworkProtocolAbstract.java
index 7b3c2430ba3..4d2373a9126 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OBinaryNetworkProtocolAbstract.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OBinaryNetworkProtocolAbstract.java
@@ -154,6 +154,12 @@ protected void sendOk(final int iClientTxId) throws IOException {
}
protected void sendError(final int iClientTxId, final Throwable t) throws IOException {
+ if (t instanceof SocketException) {
+ // DON'T SEND TO THE CLIENT BECAUSE THE SOCKET HAS PROBLEMS
+ shutdown();
+ return;
+ }
+
channel.acquireExclusiveLock();
try {
|
319e34aa1743781b453df5df51f03183b123560a
|
restlet-framework-java
|
- Continued SIP transaction support--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.example/src/org/restlet/example/ext/sip/UacClientResource.java b/modules/org.restlet.example/src/org/restlet/example/ext/sip/UacClientResource.java
index b5ef0cb714..2c1372424b 100644
--- a/modules/org.restlet.example/src/org/restlet/example/ext/sip/UacClientResource.java
+++ b/modules/org.restlet.example/src/org/restlet/example/ext/sip/UacClientResource.java
@@ -30,11 +30,14 @@
package org.restlet.example.ext.sip;
+import java.util.logging.Level;
+
import org.restlet.Client;
import org.restlet.Context;
import org.restlet.data.Protocol;
+import org.restlet.engine.Engine;
+import org.restlet.ext.sip.Address;
import org.restlet.ext.sip.SipClientResource;
-import org.restlet.resource.ClientResource;
/**
* Example SIP client resource for the UAC test scenario.
@@ -44,6 +47,7 @@
public class UacClientResource implements UacResource {
public static void main(String[] args) {
+ Engine.setLogLevel(Level.FINE);
UacClientResource cr = new UacClientResource("sip:bob@locahost");
cr.start();
cr.acknowledge();
@@ -54,7 +58,7 @@ public static void main(String[] args) {
private UacResource proxy;
/** The internal client resource. */
- private ClientResource clientResource;
+ private SipClientResource clientResource;
/**
* Constructor.
@@ -64,6 +68,12 @@ public static void main(String[] args) {
*/
public UacClientResource(String uri) {
this.clientResource = new SipClientResource(uri);
+ this.clientResource.setCallId("[email protected]");
+ this.clientResource.setCommandSequence("314159");
+ this.clientResource.setFrom(new Address("sip:[email protected]",
+ "Alice"));
+ this.clientResource.setTo(new Address("sip:[email protected]", "Bob"));
+
Client client = new Client(new Context(), Protocol.SIP);
client.getContext().getParameters().add("minThreads", "1");
client.getContext().getParameters().add("tracing", "true");
diff --git a/modules/org.restlet.example/src/org/restlet/example/ext/sip/UacServerResource.java b/modules/org.restlet.example/src/org/restlet/example/ext/sip/UacServerResource.java
index f16df34f69..e9be46b75e 100644
--- a/modules/org.restlet.example/src/org/restlet/example/ext/sip/UacServerResource.java
+++ b/modules/org.restlet.example/src/org/restlet/example/ext/sip/UacServerResource.java
@@ -34,10 +34,12 @@
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.logging.Level;
import org.restlet.Context;
import org.restlet.Server;
import org.restlet.data.Protocol;
+import org.restlet.engine.Engine;
import org.restlet.ext.sip.SipResponse;
import org.restlet.ext.sip.SipServerResource;
import org.restlet.ext.sip.SipStatus;
@@ -54,6 +56,7 @@ public class UacServerResource extends SipServerResource implements UacResource
private static boolean TRACE;
public static void main(String[] args) throws Exception {
+ Engine.setLogLevel(Level.FINE);
Server server = null;
if (args.length == 1) {
@@ -161,8 +164,8 @@ private void trace() {
if (TRACE) {
System.out.println("--------------start trace--------------------");
System.out.println("Method: " + getMethod());
- System.out.println("Call ID: " + getRequestCallId());
- System.out.println("Call Sequence: " + getCallSequence());
+ System.out.println("Call ID: " + getCallId());
+ System.out.println("Call Sequence: " + getCommandSequence());
System.out.println("To: " + getTo());
System.out.println("From: " + getFrom());
System.out.println("Max Forwards: " + getMaxForwards());
diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/Address.java b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/Address.java
index b0facd0872..78c371d6ab 100644
--- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/Address.java
+++ b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/Address.java
@@ -33,6 +33,7 @@
import org.restlet.data.Form;
import org.restlet.data.Parameter;
import org.restlet.data.Reference;
+import org.restlet.ext.sip.internal.AddressWriter;
import org.restlet.util.Series;
/**
@@ -41,7 +42,7 @@
*
* @author Thierry Boileau
*/
-public class Address {
+public class Address implements Cloneable {
/** The optional name displayed. */
private String displayName;
@@ -83,6 +84,34 @@ public Address(Reference reference, String displayName) {
this.displayName = displayName;
}
+ /**
+ * Constructor.
+ *
+ * @param reference
+ * The address reference.
+ * @param displayName
+ * The name displayed.
+ */
+ public Address(String reference, String displayName) {
+ this(new Reference(reference), displayName);
+ }
+
+ @Override
+ protected Object clone() throws CloneNotSupportedException {
+ Address result = (Address) super.clone();
+ result.reference = reference.clone();
+
+ if (parameters != null) {
+ result.parameters = new Form();
+
+ for (Parameter param : parameters) {
+ result.parameters.add(param.getName(), param.getValue());
+ }
+ }
+
+ return result;
+ }
+
/**
* Returns the optional name displayed.
*
@@ -143,4 +172,9 @@ public void setReference(Reference reference) {
this.reference = reference;
}
+ @Override
+ public String toString() {
+ return AddressWriter.write(this);
+ }
+
}
diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/SipClientResource.java b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/SipClientResource.java
index 9db8b21c57..6347ee1fbf 100644
--- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/SipClientResource.java
+++ b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/SipClientResource.java
@@ -565,6 +565,36 @@ public void register(Address to) throws ResourceException {
handle(SipMethod.REGISTER);
}
+ /**
+ * Sets the identifier of the call.
+ *
+ * @param callId
+ * The identifier of the call.
+ */
+ public void setCallId(String callId) {
+ getRequest().setCallId(callId);
+ }
+
+ /**
+ * Sets the identifier of the command.
+ *
+ * @param commandSequence
+ * The identifier of the command.
+ */
+ public void setCommandSequence(String commandSequence) {
+ getRequest().setCommandSequence(commandSequence);
+ }
+
+ /**
+ * Sets the description of the request's initiator.
+ *
+ * @param from
+ * The description of the request's initiator.
+ */
+ public void setFrom(Address from) {
+ getRequest().setFrom(from);
+ }
+
@Override
public void setRequest(Request request) {
if (request instanceof SipRequest) {
@@ -595,6 +625,16 @@ public void setResponse(Response response) {
}
}
+ /**
+ * Sets the logical recipient of the request.
+ *
+ * @param to
+ * The logical recipient of the request.
+ */
+ public void setTo(Address to) {
+ getRequest().setTo(to);
+ }
+
/**
* Requests current state and state updates from a remote node.
*
diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/SipServerResource.java b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/SipServerResource.java
index cb73dec934..97d72459de 100644
--- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/SipServerResource.java
+++ b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/SipServerResource.java
@@ -30,8 +30,9 @@
package org.restlet.ext.sip;
-import java.util.List;
-
+import org.restlet.Context;
+import org.restlet.Request;
+import org.restlet.Response;
import org.restlet.resource.ServerResource;
/**
@@ -42,11 +43,20 @@
public class SipServerResource extends ServerResource {
/**
- * Returns the request's call sequence.
+ * Returns the request's call ID.
*
- * @return The request's call sequence.
+ * @return The request's call ID.
*/
- public String getCallSequence() {
+ public String getCallId() {
+ return getRequest().getCallId();
+ }
+
+ /**
+ * Returns the request's command sequence.
+ *
+ * @return The request's command sequence.
+ */
+ public String getCommandSequence() {
return getRequest().getCommandSequence();
}
@@ -64,47 +74,11 @@ public SipRequest getRequest() {
return (SipRequest) super.getRequest();
}
- /**
- * Returns the request's call ID.
- *
- * @return The request's call ID.
- */
- public String getRequestCallId() {
- return getRequest().getCallId();
- }
-
@Override
public SipResponse getResponse() {
return (SipResponse) super.getResponse();
}
- /**
- * Returns the response's call ID.
- *
- * @return The response's call ID.
- */
- public String getResponseCallId() {
- return getResponse().getCallId();
- }
-
- /**
- * Returns the request's list of Via entries.
- *
- * @return The request's list of Via entries.
- */
- public List<SipRecipientInfo> getSipRequestRecipientsInfo() {
- return getRequest().getSipRecipientsInfo();
- }
-
- /**
- * Returns the response's list of Via entries.
- *
- * @return The response's list of Via entries.
- */
- public List<SipRecipientInfo> getSipResponseRecipientsInfo() {
- return getResponse().getSipRecipientsInfo();
- }
-
/**
* Returns the request recipient's address.
*
@@ -114,13 +88,27 @@ public Address getTo() {
return getRequest().getTo();
}
- /**
- * Sets the response's call ID.
- *
- * @param callId
- * The call ID.
- */
- public void setResponseCallId(String callId) {
- getResponse().setCallId(callId);
+ @Override
+ public void init(Context context, Request request, Response response) {
+ try {
+ SipResponse sipResponse = (SipResponse) response;
+ SipRequest sipRequest = (SipRequest) request;
+
+ sipResponse.setCallId(sipRequest.getCallId());
+ sipResponse.setCommandSequence(sipRequest.getCommandSequence());
+
+ if (sipRequest.getFrom() != null) {
+ sipResponse.setFrom((Address) sipRequest.getFrom().clone());
+ }
+
+ if (sipRequest.getTo() != null) {
+ sipResponse.setTo((Address) sipRequest.getTo().clone());
+ }
+ } catch (CloneNotSupportedException e) {
+ doCatch(e);
+ }
+
+ super.init(context, request, response);
}
+
}
diff --git a/modules/org.restlet/src/org/restlet/engine/connector/OutboundWay.java b/modules/org.restlet/src/org/restlet/engine/connector/OutboundWay.java
index ee14894ad7..f6da80d9a8 100644
--- a/modules/org.restlet/src/org/restlet/engine/connector/OutboundWay.java
+++ b/modules/org.restlet/src/org/restlet/engine/connector/OutboundWay.java
@@ -470,7 +470,7 @@ protected void writeLine() throws IOException {
case START:
if (getHelper().getLogger().isLoggable(Level.FINE)) {
getHelper().getLogger().fine(
- "Writing message from "
+ "Writing message to "
+ getConnection().getSocketAddress());
}
diff --git a/modules/org.restlet/src/org/restlet/engine/connector/ServerConnectionController.java b/modules/org.restlet/src/org/restlet/engine/connector/ServerConnectionController.java
index 269c2eabaa..e0d7e94ff2 100644
--- a/modules/org.restlet/src/org/restlet/engine/connector/ServerConnectionController.java
+++ b/modules/org.restlet/src/org/restlet/engine/connector/ServerConnectionController.java
@@ -129,7 +129,7 @@ protected void onSelected(SelectionKey key)
if (getHelper().getLogger().isLoggable(Level.FINE)) {
getHelper().getLogger().fine(
- "Connection with \""
+ "Connection from \""
+ connection.getSocketAddress()
+ "\" accepted. New count: "
+ getHelper().getConnections()
diff --git a/modules/org.restlet/src/org/restlet/engine/io/IoBuffer.java b/modules/org.restlet/src/org/restlet/engine/io/IoBuffer.java
index 9d767d1791..a9e9f660b0 100644
--- a/modules/org.restlet/src/org/restlet/engine/io/IoBuffer.java
+++ b/modules/org.restlet/src/org/restlet/engine/io/IoBuffer.java
@@ -255,7 +255,7 @@ public int refill(ReadableByteChannel sourceChannel) throws IOException {
if (result > 0) {
getBytes().flip();
setState(BufferState.DRAINING);
- Context.getCurrentLogger().fine(
+ Context.getCurrentLogger().finer(
"Refilled buffer with " + result + " byte(s)");
}
}
diff --git a/modules/org.restlet/src/org/restlet/resource/UniformResource.java b/modules/org.restlet/src/org/restlet/resource/UniformResource.java
index 6a05bc85d2..20ce81b96a 100644
--- a/modules/org.restlet/src/org/restlet/resource/UniformResource.java
+++ b/modules/org.restlet/src/org/restlet/resource/UniformResource.java
@@ -605,7 +605,7 @@ public StatusService getStatusService() {
* @param response
* The handled response.
*/
- public final void init(Context context, Request request, Response response) {
+ public void init(Context context, Request request, Response response) {
this.context = context;
this.request = request;
this.response = response;
|
f091f6e436fcef1f083c8f61de8dcdde67b11780
|
qos-ch$logback
|
* made AbstrackSocketAppender not lose events when socket connections gets lost (now uses LinkedBlockingDeque)
* extracted aspects of deque creation and output stream creation to factories in order to improve testability
* ecapsulated automatic flushing of output stream into a separate class in order to make this functionality testable
* slightly refactored internal structure of AbstrackSocketAppender to improve maintainability
|
p
|
https://github.com/qos-ch/logback
|
diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java b/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java
index 319fce0854..2940f473f1 100755
--- a/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java
+++ b/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java
@@ -15,25 +15,20 @@
package ch.qos.logback.core.net;
import java.io.IOException;
-import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
-
import javax.net.SocketFactory;
import ch.qos.logback.core.AppenderBase;
-import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.spi.PreSerializationTransformer;
import ch.qos.logback.core.util.CloseUtil;
import ch.qos.logback.core.util.Duration;
@@ -45,10 +40,11 @@
* @author Ceki Gülcü
* @author Sébastien Pennec
* @author Carl Harris
+ * @author Sebastian Gröbler
*/
public abstract class AbstractSocketAppender<E> extends AppenderBase<E>
- implements Runnable, SocketConnector.ExceptionHandler {
+ implements SocketConnector.ExceptionHandler {
/**
* The default port number of remote logging server (4560).
@@ -61,7 +57,7 @@ public abstract class AbstractSocketAppender<E> extends AppenderBase<E>
public static final int DEFAULT_RECONNECTION_DELAY = 30000;
/**
- * Default size of the queue used to hold logging events that are destined
+ * Default size of the deque used to hold logging events that are destined
* for the remote peer.
*/
public static final int DEFAULT_QUEUE_SIZE = 128;
@@ -78,6 +74,9 @@ public abstract class AbstractSocketAppender<E> extends AppenderBase<E>
*/
private static final int DEFAULT_EVENT_DELAY_TIMEOUT = 100;
+ private final ObjectWriterFactory objectWriterFactory;
+ private final QueueFactory queueFactory;
+
private String remoteHost;
private int port = DEFAULT_PORT;
private InetAddress address;
@@ -86,7 +85,7 @@ public abstract class AbstractSocketAppender<E> extends AppenderBase<E>
private int acceptConnectionTimeout = DEFAULT_ACCEPT_CONNECTION_DELAY;
private Duration eventDelayLimit = new Duration(DEFAULT_EVENT_DELAY_TIMEOUT);
- private BlockingQueue<E> queue;
+ private BlockingDeque<E> deque;
private String peerId;
private Future<?> task;
private Future<Socket> connectorTask;
@@ -97,8 +96,17 @@ public abstract class AbstractSocketAppender<E> extends AppenderBase<E>
* Constructs a new appender.
*/
protected AbstractSocketAppender() {
+ this(new QueueFactory(), new ObjectWriterFactory());
}
+ /**
+ * Constructs a new appender using the given {@link QueueFactory} and {@link ObjectWriterFactory}.
+ */
+ AbstractSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) {
+ this.objectWriterFactory = objectWriterFactory;
+ this.queueFactory = queueFactory;
+ }
+
/**
* {@inheritDoc}
*/
@@ -119,9 +127,13 @@ public void start() {
+ " For more information, please visit http://logback.qos.ch/codes.html#socket_no_host");
}
+ if (queueSize == 0) {
+ addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing");
+ }
+
if (queueSize < 0) {
errorCount++;
- addError("Queue size must be non-negative");
+ addError("Queue size must be greater than zero");
}
if (errorCount == 0) {
@@ -134,9 +146,14 @@ public void start() {
}
if (errorCount == 0) {
- queue = newBlockingQueue(queueSize);
+ deque = queueFactory.newLinkedBlockingDeque(queueSize);
peerId = "remote peer " + remoteHost + ":" + port + ": ";
- task = getContext().getExecutorService().submit(this);
+ task = getContext().getExecutorService().submit(new Runnable() {
+ @Override
+ public void run() {
+ connectSocketAndDispatchEvents();
+ }
+ });
super.start();
}
}
@@ -162,21 +179,16 @@ protected void append(E event) {
if (event == null || !isStarted()) return;
try {
- final boolean inserted = queue.offer(event, eventDelayLimit.getMilliseconds(), TimeUnit.MILLISECONDS);
+ final boolean inserted = deque.offer(event, eventDelayLimit.getMilliseconds(), TimeUnit.MILLISECONDS);
if (!inserted) {
- addInfo("Dropping event due to timeout limit of [" + eventDelayLimit +
- "] milliseconds being exceeded");
+ addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + "] being exceeded");
}
} catch (InterruptedException e) {
addError("Interrupted while appending event to SocketAppender", e);
}
}
- /**
- * {@inheritDoc}
- */
- public final void run() {
- signalEntryInRunMethod();
+ private void connectSocketAndDispatchEvents() {
try {
while (!Thread.currentThread().isInterrupted()) {
SocketConnector connector = createConnector(address, port, 0,
@@ -186,22 +198,37 @@ public final void run() {
if(connectorTask == null)
break;
- socket = waitForConnectorToReturnASocket();
+ socket = waitForConnectorToReturnSocket();
if(socket == null)
break;
- dispatchEvents();
+
+ try {
+ ObjectWriter objectWriter = createObjectWriterForSocket();
+ addInfo(peerId + "connection established");
+ dispatchEvents(objectWriter);
+ } catch (IOException ex) {
+ addInfo(peerId + "connection failed: " + ex);
+ } finally {
+ CloseUtil.closeQuietly(socket);
+ socket = null;
+ addInfo(peerId + "connection closed");
+ }
}
} catch (InterruptedException ex) {
assert true; // ok... we'll exit now
}
+ // TODO I guess the appender should also be stopped at this point
addInfo("shutting down");
}
- protected void signalEntryInRunMethod() {
- // do nothing by default
- }
+ private ObjectWriter createObjectWriterForSocket() throws IOException {
+ socket.setSoTimeout(acceptConnectionTimeout);
+ ObjectWriter objectWriter = objectWriterFactory.newAutoFlushingObjectWriter(socket.getOutputStream());
+ socket.setSoTimeout(0);
+ return objectWriter;
+ }
- private SocketConnector createConnector(InetAddress address, int port,
+ private SocketConnector createConnector(InetAddress address, int port,
int initialDelay, long retryDelay) {
SocketConnector connector = newConnector(address, port, initialDelay,
retryDelay);
@@ -218,9 +245,9 @@ private Future<Socket> activateConnector(SocketConnector connector) {
}
}
- private Socket waitForConnectorToReturnASocket() throws InterruptedException {
+ private Socket waitForConnectorToReturnSocket() throws InterruptedException {
try {
- Socket s = connectorTask.get();
+ Socket s = connectorTask.get();
connectorTask = null;
return s;
} catch (ExecutionException e) {
@@ -228,35 +255,27 @@ private Socket waitForConnectorToReturnASocket() throws InterruptedException {
}
}
- private void dispatchEvents() throws InterruptedException {
- try {
- socket.setSoTimeout(acceptConnectionTimeout);
- ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
- socket.setSoTimeout(0);
- addInfo(peerId + "connection established");
- int counter = 0;
- while (true) {
- E event = queue.take();
- postProcessEvent(event);
- Serializable serEvent = getPST().transform(event);
- oos.writeObject(serEvent);
- oos.flush();
- if (++counter >= CoreConstants.OOS_RESET_FREQUENCY) {
- // Failing to reset the object output stream every now and
- // then creates a serious memory leak.
- oos.reset();
- counter = 0;
- }
+ private void dispatchEvents(ObjectWriter objectWriter) throws InterruptedException, IOException {
+ while (true) {
+ E event = deque.takeFirst();
+ postProcessEvent(event);
+ Serializable serializableEvent = getPST().transform(event);
+ try {
+ objectWriter.write(serializableEvent);
+ } catch (IOException e) {
+ tryReAddingEventToFrontOfQueue(event);
+ throw e;
}
- } catch (IOException ex) {
- addInfo(peerId + "connection failed: " + ex);
- } finally {
- CloseUtil.closeQuietly(socket);
- socket = null;
- addInfo(peerId + "connection closed");
}
- }
-
+ }
+
+ private void tryReAddingEventToFrontOfQueue(E event) {
+ final boolean wasInserted = deque.offerFirst(event);
+ if (!wasInserted) {
+ addInfo("Dropping event due to socket connection error and maxed out deque capacity");
+ }
+ }
+
/**
* {@inheritDoc}
*/
@@ -270,8 +289,6 @@ public void connectionFailed(SocketConnector connector, Exception ex) {
}
}
-
-
/**
* Creates a new {@link SocketConnector}.
* <p>
@@ -299,24 +316,6 @@ protected SocketFactory getSocketFactory() {
return SocketFactory.getDefault();
}
- /**
- * Creates a blocking queue that will be used to hold logging events until
- * they can be delivered to the remote receiver.
- * <p>
- * The default implementation creates a (bounded) {@link ArrayBlockingQueue}
- * for positive queue sizes. Otherwise it creates a {@link SynchronousQueue}.
- * <p>
- * This method is exposed primarily to support instrumentation for unit
- * testing.
- *
- * @param queueSize size of the queue
- * @return
- */
- BlockingQueue<E> newBlockingQueue(int queueSize) {
- return queueSize <= 0 ?
- new SynchronousQueue<E>() : new ArrayBlockingQueue<E>(queueSize);
- }
-
/**
* Post-processes an event before it is serialized for delivery to the
* remote receiver.
@@ -332,20 +331,6 @@ BlockingQueue<E> newBlockingQueue(int queueSize) {
*/
protected abstract PreSerializationTransformer<E> getPST();
- /*
- * This method is used by logback modules only in the now deprecated
- * convenience constructors for SocketAppender
- */
- @Deprecated
- protected static InetAddress getAddressByName(String host) {
- try {
- return InetAddress.getByName(host);
- } catch (Exception e) {
- // addError("Could not find address of [" + host + "].", e);
- return null;
- }
- }
-
/**
* The <b>RemoteHost</b> property takes the name of of the host where a corresponding server is running.
*/
@@ -397,14 +382,14 @@ public Duration getReconnectionDelay() {
/**
* The <b>queueSize</b> property takes a non-negative integer representing
* the number of logging events to retain for delivery to the remote receiver.
- * When the queue size is zero, event delivery to the remote receiver is
- * synchronous. When the queue size is greater than zero, the
+ * When the deque size is zero, event delivery to the remote receiver is
+ * synchronous. When the deque size is greater than zero, the
* {@link #append(Object)} method returns immediately after enqueing the
- * event, assuming that there is space available in the queue. Using a
- * non-zero queue length can improve performance by eliminating delays
+ * event, assuming that there is space available in the deque. Using a
+ * non-zero deque length can improve performance by eliminating delays
* caused by transient network delays.
*
- * @param queueSize the queue size to set.
+ * @param queueSize the deque size to set.
*/
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java b/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java
new file mode 100644
index 0000000000..6a5c07ca37
--- /dev/null
+++ b/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java
@@ -0,0 +1,61 @@
+/**
+ * Logback: the reliable, generic, fast and flexible logging framework.
+ * Copyright (C) 1999-2013, QOS.ch. All rights reserved.
+ *
+ * This program and the accompanying materials are dual-licensed under
+ * either the terms of the Eclipse Public License v1.0 as published by
+ * the Eclipse Foundation
+ *
+ * or (per the licensee's choosing)
+ *
+ * under the terms of the GNU Lesser General Public License version 2.1
+ * as published by the Free Software Foundation.
+ */
+
+package ch.qos.logback.core.net;
+
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+
+/**
+ * Automatically flushes the underlying {@link java.io.ObjectOutputStream} immediately after calling
+ * it's {@link java.io.ObjectOutputStream#writeObject(Object)} method.
+ *
+ * @author Sebastian Gröbler
+ */
+public class AutoFlushingObjectWriter implements ObjectWriter {
+
+ private final ObjectOutputStream objectOutputStream;
+ private final int resetFrequency;
+ private int writeCounter = 0;
+
+ /**
+ * Creates a new instance for the given {@link java.io.ObjectOutputStream}.
+ *
+ * @param objectOutputStream the stream to write to
+ * @param resetFrequency the frequency with which the given stream will be
+ * automatically reset to prevent a memory leak
+ */
+ public AutoFlushingObjectWriter(ObjectOutputStream objectOutputStream, int resetFrequency) {
+ this.objectOutputStream = objectOutputStream;
+ this.resetFrequency = resetFrequency;
+ }
+
+ @Override
+ public void write(Object object) throws IOException {
+ objectOutputStream.writeObject(object);
+ objectOutputStream.flush();
+ preventMemoryLeak();
+ }
+
+ /**
+ * Failing to reset the object output stream every now and then creates a serious memory leak which
+ * is why the underlying stream will be reset according to the {@code resetFrequency}.
+ */
+ private void preventMemoryLeak() throws IOException {
+ if (++writeCounter >= resetFrequency) {
+ objectOutputStream.reset();
+ writeCounter = 0;
+ }
+ }
+}
diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java
new file mode 100644
index 0000000000..dbd528b158
--- /dev/null
+++ b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java
@@ -0,0 +1,33 @@
+/**
+ * Logback: the reliable, generic, fast and flexible logging framework.
+ * Copyright (C) 1999-2013, QOS.ch. All rights reserved.
+ *
+ * This program and the accompanying materials are dual-licensed under
+ * either the terms of the Eclipse Public License v1.0 as published by
+ * the Eclipse Foundation
+ *
+ * or (per the licensee's choosing)
+ *
+ * under the terms of the GNU Lesser General Public License version 2.1
+ * as published by the Free Software Foundation.
+ */
+package ch.qos.logback.core.net;
+
+import java.io.IOException;
+
+/**
+ * Writes objects to an output.
+ *
+ * @author Sebastian Gröbler
+ */
+public interface ObjectWriter {
+
+ /**
+ * Writes an object to an output.
+ *
+ * @param object the {@link Object} to write
+ * @throws IOException in case input/output fails, details are defined by the implementation
+ */
+ void write(Object object) throws IOException;
+
+}
diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java
new file mode 100644
index 0000000000..eca1405131
--- /dev/null
+++ b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java
@@ -0,0 +1,39 @@
+/**
+ * Logback: the reliable, generic, fast and flexible logging framework.
+ * Copyright (C) 1999-2013, QOS.ch. All rights reserved.
+ *
+ * This program and the accompanying materials are dual-licensed under
+ * either the terms of the Eclipse Public License v1.0 as published by
+ * the Eclipse Foundation
+ *
+ * or (per the licensee's choosing)
+ *
+ * under the terms of the GNU Lesser General Public License version 2.1
+ * as published by the Free Software Foundation.
+ */
+package ch.qos.logback.core.net;
+
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+
+import ch.qos.logback.core.CoreConstants;
+
+/**
+ * Factory for {@link ch.qos.logback.core.net.ObjectWriter} instances.
+ *
+ * @author Sebastian Gröbler
+ */
+public class ObjectWriterFactory {
+
+ /**
+ * Creates a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance.
+ *
+ * @param outputStream the underlying {@link java.io.OutputStream} to write to
+ * @return a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance
+ * @throws IOException if an I/O error occurs while writing stream header
+ */
+ public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException {
+ return new AutoFlushingObjectWriter(new ObjectOutputStream(outputStream), CoreConstants.OOS_RESET_FREQUENCY);
+ }
+}
diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java b/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java
new file mode 100644
index 0000000000..d9f17ff3a3
--- /dev/null
+++ b/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java
@@ -0,0 +1,39 @@
+/**
+ * Logback: the reliable, generic, fast and flexible logging framework.
+ * Copyright (C) 1999-2013, QOS.ch. All rights reserved.
+ *
+ * This program and the accompanying materials are dual-licensed under
+ * either the terms of the Eclipse Public License v1.0 as published by
+ * the Eclipse Foundation
+ *
+ * or (per the licensee's choosing)
+ *
+ * under the terms of the GNU Lesser General Public License version 2.1
+ * as published by the Free Software Foundation.
+ */
+package ch.qos.logback.core.net;
+
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.LinkedBlockingDeque;
+
+/**
+ * Factory for {@link java.util.Queue} instances.
+ *
+ * @author Sebastian Gröbler
+ */
+public class QueueFactory {
+
+ /**
+ * Creates a new {@link LinkedBlockingDeque} with the given {@code capacity}.
+ * In case the given capacity is smaller than one it will automatically be
+ * converted to one.
+ *
+ * @param capacity the capacity to use for the queue
+ * @param <E> the type of elements held in the queue
+ * @return a new instance of {@link ArrayBlockingQueue}
+ */
+ public <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) {
+ final int actualCapacity = capacity < 1 ? 1 : capacity;
+ return new LinkedBlockingDeque<E>(actualCapacity);
+ }
+}
diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java
new file mode 100755
index 0000000000..7d16ed5a2e
--- /dev/null
+++ b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java
@@ -0,0 +1,129 @@
+/**
+ * Logback: the reliable, generic, fast and flexible logging framework.
+ * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
+ *
+ * This program and the accompanying materials are dual-licensed under
+ * either the terms of the Eclipse Public License v1.0 as published by
+ * the Eclipse Foundation
+ *
+ * or (per the licensee's choosing)
+ *
+ * under the terms of the GNU Lesser General Public License version 2.1
+ * as published by the Free Software Foundation.
+ */
+
+package ch.qos.logback.core.net;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import ch.qos.logback.core.net.mock.MockContext;
+import ch.qos.logback.core.net.server.ServerSocketUtil;
+import ch.qos.logback.core.spi.PreSerializationTransformer;
+import org.junit.After;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import org.junit.Before;
+import org.junit.Test;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Integration tests for {@link ch.qos.logback.core.net.AbstractSocketAppender}.
+ *
+ * @author Carl Harris
+ * @author Sebastian Gröbler
+ */
+public class AbstractSocketAppenderIntegrationTest {
+
+ private static final int TIMEOUT = 2000;
+
+ private ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newCachedThreadPool();
+ private MockContext mockContext = new MockContext(executorService);
+ private AutoFlushingObjectWriter objectWriter;
+ private ObjectWriterFactory objectWriterFactory = new SpyProducingObjectWriterFactory();
+ private LinkedBlockingDeque<String> deque = spy(new LinkedBlockingDeque<String>(1));
+ private QueueFactory queueFactory = mock(QueueFactory.class);
+ private InstrumentedSocketAppender instrumentedAppender = new InstrumentedSocketAppender(queueFactory, objectWriterFactory);
+
+ @Before
+ public void setUp() throws Exception {
+ when(queueFactory.<String>newLinkedBlockingDeque(anyInt())).thenReturn(deque);
+ instrumentedAppender.setContext(mockContext);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ instrumentedAppender.stop();
+ assertFalse(instrumentedAppender.isStarted());
+ executorService.shutdownNow();
+ assertTrue(executorService.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS));
+ }
+
+ @Test
+ public void dispatchesEvents() throws Exception {
+
+ // given
+ ServerSocket serverSocket = ServerSocketUtil.createServerSocket();
+ instrumentedAppender.setRemoteHost(serverSocket.getInetAddress().getHostAddress());
+ instrumentedAppender.setPort(serverSocket.getLocalPort());
+ instrumentedAppender.start();
+
+ Socket appenderSocket = serverSocket.accept();
+ serverSocket.close();
+
+ // when
+ instrumentedAppender.append("some event");
+
+ // wait for event to be taken from deque and being written into the stream
+ verify(deque, timeout(TIMEOUT)).takeFirst();
+ verify(objectWriter, timeout(TIMEOUT)).write("some event");
+
+ // then
+ ObjectInputStream ois = new ObjectInputStream(appenderSocket.getInputStream());
+ assertEquals("some event", ois.readObject());
+ appenderSocket.close();
+ }
+
+ private static class InstrumentedSocketAppender extends AbstractSocketAppender<String> {
+
+ public InstrumentedSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) {
+ super(queueFactory, objectWriterFactory);
+ }
+
+ @Override
+ protected void postProcessEvent(String event) {
+ }
+
+ @Override
+ protected PreSerializationTransformer<String> getPST() {
+ return new PreSerializationTransformer<String>() {
+ public Serializable transform(String event) {
+ return event;
+ }
+ };
+ }
+ }
+
+ private class SpyProducingObjectWriterFactory extends ObjectWriterFactory {
+
+ @Override
+ public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException {
+ objectWriter = spy(super.newAutoFlushingObjectWriter(outputStream));
+ return objectWriter;
+ }
+ }
+}
diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java
index 8efd80c5c2..371981afa0 100755
--- a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java
+++ b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java
@@ -14,242 +14,467 @@
package ch.qos.logback.core.net;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.ObjectInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
import java.io.Serializable;
-import java.net.ServerSocket;
+import java.net.InetAddress;
import java.net.Socket;
-import java.util.List;
-import java.util.concurrent.*;
-
-import ch.qos.logback.core.BasicStatusManager;
-import ch.qos.logback.core.status.Status;
-import ch.qos.logback.core.status.StatusListener;
-import ch.qos.logback.core.status.StatusManager;
-import ch.qos.logback.core.util.StatusPrinter;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
import ch.qos.logback.core.net.mock.MockContext;
-import ch.qos.logback.core.net.server.ServerSocketUtil;
import ch.qos.logback.core.spi.PreSerializationTransformer;
+import ch.qos.logback.core.util.Duration;
+import org.junit.After;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InOrder;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.contains;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
/**
* Unit tests for {@link AbstractSocketAppender}.
*
* @author Carl Harris
+ * @author Sebastian Gröbler
*/
public class AbstractSocketAppenderTest {
- private static final int DELAY = 10000;
+ /**
+ * Timeout used for all blocking operations in multi-threading contexts.
+ */
+ private static final int TIMEOUT = 1000;
- private ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newCachedThreadPool();
+ private ThreadPoolExecutor executorService = spy((ThreadPoolExecutor) Executors.newCachedThreadPool());
private MockContext mockContext = new MockContext(executorService);
- private InstrumentedSocketAppender instrumentedAppender = new InstrumentedSocketAppender();
+ private PreSerializationTransformer<String> preSerializationTransformer = spy(new StringPreSerializationTransformer());
+ private Socket socket = mock(Socket.class);
+ private SocketConnector socketConnector = mock(SocketConnector.class);
+ private AutoFlushingObjectWriter objectWriter = mock(AutoFlushingObjectWriter.class);
+ private ObjectWriterFactory objectWriterFactory = mock(ObjectWriterFactory.class);
+ private LinkedBlockingDeque<String> deque = spy(new LinkedBlockingDeque<String>(1));
+ private QueueFactory queueFactory = mock(QueueFactory.class);
+ private InstrumentedSocketAppender appender = spy(new InstrumentedSocketAppender(preSerializationTransformer, queueFactory, objectWriterFactory, socketConnector));
@Before
public void setUp() throws Exception {
- instrumentedAppender.setContext(mockContext);
+ // setup valid appender with mock dependencies
+ when(socketConnector.call()).thenReturn(socket);
+ when(objectWriterFactory.newAutoFlushingObjectWriter(any(OutputStream.class))).thenReturn(objectWriter);
+ when(queueFactory.<String>newLinkedBlockingDeque(anyInt())).thenReturn(deque);
+
+ appender.setContext(mockContext);
+ appender.setRemoteHost("localhost");
}
@After
public void tearDown() throws Exception {
- instrumentedAppender.stop();
- assertFalse(instrumentedAppender.isStarted());
+ appender.stop();
+ assertFalse(appender.isStarted());
executorService.shutdownNow();
- assertTrue(executorService.awaitTermination(DELAY, TimeUnit.MILLISECONDS));
+ assertTrue(executorService.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS));
}
@Test
- public void appenderShouldFailToStartWithoutValidPort() throws Exception {
- instrumentedAppender.setPort(-1);
- instrumentedAppender.setRemoteHost("localhost");
- instrumentedAppender.setQueueSize(0);
- instrumentedAppender.start();
- assertFalse(instrumentedAppender.isStarted());
- assertTrue(mockContext.getLastStatus().getMessage().contains("port"));
+ public void failsToStartWithoutValidPort() throws Exception {
+
+ // given
+ appender.setPort(-1);
+
+ // when
+ appender.start();
+
+ // then
+ assertFalse(appender.isStarted());
+ verify(appender).addError(contains("port"));
}
@Test
- public void appenderShouldFailToStartWithoutValidRemoteHost() throws Exception {
- instrumentedAppender.setPort(1);
- instrumentedAppender.setRemoteHost(null);
- instrumentedAppender.setQueueSize(0);
- instrumentedAppender.start();
- assertFalse(instrumentedAppender.isStarted());
- assertTrue(mockContext.getLastStatus().getMessage().contains("remote host"));
+ public void failsToStartWithoutValidRemoteHost() throws Exception {
+
+ // given
+ appender.setRemoteHost(null);
+
+ // when
+ appender.start();
+
+ // then
+ assertFalse(appender.isStarted());
+ verify(appender).addError(contains("remote host"));
}
@Test
- public void appenderShouldFailToStartWithNegativeQueueSize() throws Exception {
- instrumentedAppender.setPort(1);
- instrumentedAppender.setRemoteHost("localhost");
- instrumentedAppender.setQueueSize(-1);
- instrumentedAppender.start();
- assertFalse(instrumentedAppender.isStarted());
- assertTrue(mockContext.getLastStatus().getMessage().contains("Queue"));
+ public void failsToStartWithNegativeQueueSize() throws Exception {
+
+ // given
+ appender.setQueueSize(-1);
+
+ // when
+ appender.start();
+
+ // then
+ assertFalse(appender.isStarted());
+ verify(appender).addError(contains("Queue size must be greater than zero"));
}
@Test
- public void appenderShouldFailToStartWithUnresolvableRemoteHost() throws Exception {
- instrumentedAppender.setPort(1);
- instrumentedAppender.setRemoteHost("NOT.A.VALID.REMOTE.HOST.NAME");
- instrumentedAppender.setQueueSize(0);
- instrumentedAppender.start();
- assertFalse(instrumentedAppender.isStarted());
- assertTrue(mockContext.getLastStatus().getMessage().contains("unknown host"));
+ public void failsToStartWithUnresolvableRemoteHost() throws Exception {
+
+ // given
+ appender.setRemoteHost("NOT.A.VALID.REMOTE.HOST.NAME");
+
+ // when
+ appender.start();
+
+ // then
+ assertFalse(appender.isStarted());
+ verify(appender).addError(contains("unknown host"));
}
@Test
- public void appenderShouldFailToStartWithZeroQueueLength() throws Exception {
- instrumentedAppender.setPort(1);
- instrumentedAppender.setRemoteHost("localhost");
- instrumentedAppender.setQueueSize(0);
- instrumentedAppender.start();
- assertTrue(instrumentedAppender.isStarted());
- assertTrue(instrumentedAppender.lastQueue instanceof SynchronousQueue);
+ public void startsButOutputsWarningWhenQueueSizeIsZero() throws Exception {
+
+ // given
+ appender.setQueueSize(0);
+
+ // when
+ appender.start();
+
+ // then
+ assertTrue(appender.isStarted());
+ verify(appender).addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing");
}
@Test
- public void appenderShouldStartWithValidParameters() throws Exception {
- instrumentedAppender.setPort(1);
- instrumentedAppender.setRemoteHost("localhost");
- instrumentedAppender.setQueueSize(1);
- instrumentedAppender.start();
- assertTrue(instrumentedAppender.isStarted());
- assertTrue(instrumentedAppender.lastQueue instanceof ArrayBlockingQueue);
- assertEquals(1, instrumentedAppender.lastQueue.remainingCapacity());
+ public void startsWithValidParameters() throws Exception {
+
+ // when
+ appender.start();
+
+ // then
+ assertTrue(appender.isStarted());
}
- // this test takes 1 second and is deemed too long
- @Ignore
- @Test(timeout = 2000)
- public void appenderShouldCleanupTasksWhenStopped() throws Exception {
- mockContext.setStatusManager(new BasicStatusManager());
- instrumentedAppender.setPort(1);
- instrumentedAppender.setRemoteHost("localhost");
- instrumentedAppender.setQueueSize(1);
- instrumentedAppender.start();
- assertTrue(instrumentedAppender.isStarted());
+ @Test
+ public void createsSocketConnectorWithConfiguredParameters() throws Exception {
+
+ // given
+ appender.setReconnectionDelay(new Duration(42));
+ appender.setRemoteHost("localhost");
+ appender.setPort(21);
- waitForActiveCountToEqual(executorService, 2);
- instrumentedAppender.stop();
- waitForActiveCountToEqual(executorService, 0);
- StatusPrinter.print(mockContext);
- assertEquals(0, executorService.getActiveCount());
+ // when
+ appender.start();
+ // then
+ verify(appender, timeout(TIMEOUT)).newConnector(InetAddress.getByName("localhost"), 21, 0, 42);
}
- private void waitForActiveCountToEqual(ThreadPoolExecutor executorService, int i) {
- while (executorService.getActiveCount() != i) {
- try {
- Thread.yield();
- Thread.sleep(1);
- System.out.print(".");
- } catch (InterruptedException e) {
- }
- }
+ @Test
+ public void addsInfoMessageWhenSocketConnectionWasEstablished() {
+
+ // when
+ appender.start();
+
+ // then
+ verify(appender, timeout(TIMEOUT)).addInfo(contains("connection established"));
}
+ @Test
+ public void addsInfoMessageWhenSocketConnectionFailed() throws Exception {
+
+ // given
+ doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class));
+ appender.start();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(appender, timeout(TIMEOUT).atLeastOnce()).addInfo(contains("connection failed"));
+ }
@Test
- public void testAppendWhenNotStarted() throws Exception {
- instrumentedAppender.setRemoteHost("localhost");
- instrumentedAppender.start();
- instrumentedAppender.stop();
+ public void closesSocketOnException() throws Exception {
- // make sure the appender task has stopped
- executorService.shutdownNow();
- assertTrue(executorService.awaitTermination(DELAY, TimeUnit.MILLISECONDS));
+ // given
+ doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class));
+ appender.start();
- instrumentedAppender.append("some event");
- assertTrue(instrumentedAppender.lastQueue.isEmpty());
+ // when
+ appender.append("some event");
+
+ // then
+ verify(socket, timeout(TIMEOUT).atLeastOnce()).close();
}
- @Test(timeout = 1000)
- public void testAppendSingleEvent() throws Exception {
- instrumentedAppender.setRemoteHost("localhost");
- instrumentedAppender.start();
+ @Test
+ public void addsInfoMessageWhenSocketConnectionClosed() throws Exception {
- instrumentedAppender.latch.await();
- instrumentedAppender.append("some event");
- assertTrue(instrumentedAppender.lastQueue.size() == 1);
+ // given
+ doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class));
+ appender.start();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(appender, timeout(TIMEOUT).atLeastOnce()).addInfo(contains("connection closed"));
}
@Test
- public void testAppendEvent() throws Exception {
- instrumentedAppender.setRemoteHost("localhost");
- instrumentedAppender.setQueueSize(1);
- instrumentedAppender.start();
+ public void shutsDownWhenConnectorTaskCouldNotBeActivated() {
- // stop the appender task, but don't stop the appender
- executorService.shutdownNow();
- assertTrue(executorService.awaitTermination(DELAY, TimeUnit.MILLISECONDS));
+ // given
+ doThrow(new RejectedExecutionException()).when(executorService).submit(socketConnector);
- instrumentedAppender.append("some event");
- assertEquals("some event", instrumentedAppender.lastQueue.poll());
+ // when
+ appender.start();
+
+ // then
+ verify(appender, timeout(TIMEOUT)).addInfo("shutting down");
}
@Test
- public void testDispatchEvent() throws Exception {
- ServerSocket serverSocket = ServerSocketUtil.createServerSocket();
- instrumentedAppender.setRemoteHost(serverSocket.getInetAddress().getHostAddress());
- instrumentedAppender.setPort(serverSocket.getLocalPort());
- instrumentedAppender.setQueueSize(1);
- instrumentedAppender.start();
+ public void shutsDownWhenConnectorTaskThrewAnException() throws Exception {
- Socket appenderSocket = serverSocket.accept();
- serverSocket.close();
+ // given
+ doThrow(new IllegalStateException()).when(socketConnector).call();
- instrumentedAppender.append("some event");
+ // when
+ appender.start();
- final int shortDelay = 100;
- for (int i = 0, retries = DELAY / shortDelay;
- !instrumentedAppender.lastQueue.isEmpty() && i < retries;
- i++) {
- Thread.sleep(shortDelay);
- }
- assertTrue(instrumentedAppender.lastQueue.isEmpty());
+ // then
+ verify(appender, timeout(TIMEOUT)).addInfo("shutting down");
+ }
+
+ @Test
+ public void offersEventsToTheEndOfTheDeque() throws Exception {
+
+ // given
+ appender.start();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(deque).offer(eq("some event"), anyLong(), any(TimeUnit.class));
+ }
+
+ @Test
+ public void doesNotQueueAnyEventsWhenStopped() throws Exception {
+
+ // given
+ appender.start();
+ appender.stop();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verifyZeroInteractions(deque);
+ }
- ObjectInputStream ois = new ObjectInputStream(appenderSocket.getInputStream());
- assertEquals("some event", ois.readObject());
- appenderSocket.close();
+ @Test
+ public void addsInfoMessageWhenEventCouldNotBeQueuedInConfiguredTimeoutDueToQueueSizeLimitation() throws Exception {
+
+ // given
+ long eventDelayLimit = 42;
+ doReturn(false).when(deque).offer("some event", eventDelayLimit, TimeUnit.MILLISECONDS);
+ appender.setEventDelayLimit(new Duration(eventDelayLimit));
+ appender.start();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(appender).addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + " milliseconds] being exceeded");
+ }
+
+ @Test
+ public void takesEventsFromTheFrontOfTheDeque() throws Exception {
+
+ // given
+ appender.start();
+ awaitStartOfEventDispatching();
+ // when
+ appender.append("some event");
+
+ // then
+ verify(deque, timeout(TIMEOUT).atLeastOnce()).takeFirst();
+ }
+
+ @Test
+ public void reAddsEventAtTheFrontOfTheDequeWhenTransmissionFails() throws Exception {
+
+ // given
+ doThrow(new IOException()).when(objectWriter).write(anyObject());
+ appender.start();
+ awaitStartOfEventDispatching();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(deque, timeout(TIMEOUT).atLeastOnce()).offerFirst("some event");
+ }
+
+ @Test
+ public void addsErrorMessageWhenAppendingIsInterruptedWhileWaitingForTheQueueToAcceptTheEvent() throws Exception {
+
+ // given
+ final InterruptedException interruptedException = new InterruptedException();
+ doThrow(interruptedException).when(deque).offer(eq("some event"), anyLong(), any(TimeUnit.class));
+ appender.start();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(appender).addError("Interrupted while appending event to SocketAppender", interruptedException);
+ }
+
+ @Test
+ public void postProcessesEventsBeforeTransformingItToASerializable() throws Exception {
+
+ // given
+ appender.start();
+ awaitStartOfEventDispatching();
+
+ // when
+ appender.append("some event");
+ awaitAtLeastOneEventToBeDispatched();
+
+ // then
+ InOrder inOrder = inOrder(appender, preSerializationTransformer);
+ inOrder.verify(appender).postProcessEvent("some event");
+ inOrder.verify(preSerializationTransformer).transform("some event");
+ }
+
+ @Test
+ public void writesSerializedEventToStream() throws Exception {
+
+ // given
+ when(preSerializationTransformer.transform("some event")).thenReturn("some serialized event");
+ appender.start();
+ awaitStartOfEventDispatching();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(objectWriter, timeout(TIMEOUT)).write("some serialized event");
+ }
+
+ @Test
+ public void addsInfoMessageWhenEventIsBeingDroppedBecauseOfConnectionProblemAndDequeCapacityLimitReached() throws Exception {
+
+ // given
+ doThrow(new IOException()).when(objectWriter).write(anyObject());
+ doThrow(new IllegalStateException()).when(deque).offerFirst("some event");
+ appender.start();
+ awaitStartOfEventDispatching();
+ reset(appender);
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(appender, timeout(TIMEOUT)).addInfo("Dropping event due to socket connection error and maxed out deque capacity");
+ }
+
+ @Test
+ public void reEstablishesSocketConnectionOnConnectionDrop() throws Exception {
+
+ // given
+ doThrow(new IOException()).when(objectWriter).write(anyObject());
+ appender.start();
+ awaitStartOfEventDispatching();
+
+ // when
+ appender.append("some event");
+
+ // then
+ verify(objectWriterFactory, timeout(TIMEOUT).atLeast(2)).newAutoFlushingObjectWriter(any(OutputStream.class));
+ }
+
+ @Test
+ public void usesConfiguredAcceptConnectionTimeoutAndResetsSocketTimeoutAfterSuccessfulConnection() throws Exception {
+
+ // when
+ appender.setAcceptConnectionTimeout(42);
+ appender.start();
+ awaitStartOfEventDispatching();
+
+ // then
+ InOrder inOrder = inOrder(socket);
+ inOrder.verify(socket).setSoTimeout(42);
+ inOrder.verify(socket).setSoTimeout(0);
+ }
+
+ private void awaitAtLeastOneEventToBeDispatched() throws IOException {
+ verify(objectWriter, timeout(TIMEOUT)).write(anyString());
+ }
+
+ private void awaitStartOfEventDispatching() throws InterruptedException {
+ verify(deque, timeout(TIMEOUT)).takeFirst();
}
private static class InstrumentedSocketAppender extends AbstractSocketAppender<String> {
- private BlockingQueue<String> lastQueue;
- CountDownLatch latch = new CountDownLatch(1);
+ private PreSerializationTransformer<String> preSerializationTransformer;
+ private SocketConnector socketConnector;
+
+ public InstrumentedSocketAppender(PreSerializationTransformer<String> preSerializationTransformer,
+ QueueFactory queueFactory,
+ ObjectWriterFactory objectWriterFactory,
+ SocketConnector socketConnector) {
+ super(queueFactory, objectWriterFactory);
+ this.preSerializationTransformer = preSerializationTransformer;
+ this.socketConnector = socketConnector;
+ }
+
@Override
protected void postProcessEvent(String event) {
}
@Override
protected PreSerializationTransformer<String> getPST() {
- return new PreSerializationTransformer<String>() {
- public Serializable transform(String event) {
- return event;
- }
- };
+ return preSerializationTransformer;
}
@Override
- protected void signalEntryInRunMethod() {
- latch.countDown();
+ protected SocketConnector newConnector(InetAddress address, int port, long initialDelay, long retryDelay) {
+ return socketConnector;
}
+ }
+
+ private static class StringPreSerializationTransformer implements PreSerializationTransformer<String> {
@Override
- BlockingQueue<String> newBlockingQueue(int queueSize) {
- lastQueue = super.newBlockingQueue(queueSize);
- return lastQueue;
+ public Serializable transform(String event) {
+ return event;
}
-
}
-
}
diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java
new file mode 100644
index 0000000000..1a4672703a
--- /dev/null
+++ b/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java
@@ -0,0 +1,114 @@
+/**
+ * Logback: the reliable, generic, fast and flexible logging framework.
+ * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
+ *
+ * This program and the accompanying materials are dual-licensed under
+ * either the terms of the Eclipse Public License v1.0 as published by
+ * the Eclipse Foundation
+ *
+ * or (per the licensee's choosing)
+ *
+ * under the terms of the GNU Lesser General Public License version 2.1
+ * as published by the Free Software Foundation.
+ */
+
+package ch.qos.logback.core.net;
+
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InOrder;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+
+/**
+ * Unit tests for {@link ch.qos.logback.core.net.AutoFlushingObjectWriter}.
+ *
+ * @author Sebastian Gröbler
+ */
+public class AutoFlushingObjectWriterTest {
+
+ private InstrumentedObjectOutputStream objectOutputStream;
+
+ @Before
+ public void beforeEachTest() throws IOException {
+ objectOutputStream = spy(new InstrumentedObjectOutputStream());
+ }
+
+ @Test
+ public void writesToUnderlyingObjectOutputStream() throws IOException {
+
+ // given
+ ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2);
+ String object = "foo";
+
+ // when
+ objectWriter.write(object);
+
+ // then
+ verify(objectOutputStream).writeObjectOverride(object);
+ }
+
+ @Test
+ public void flushesAfterWrite() throws IOException {
+
+ // given
+ ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2);
+ String object = "foo";
+
+ // when
+ objectWriter.write(object);
+
+ // then
+ InOrder inOrder = inOrder(objectOutputStream);
+ inOrder.verify(objectOutputStream).writeObjectOverride(object);
+ inOrder.verify(objectOutputStream).flush();
+ }
+
+ @Test
+ public void resetsObjectOutputStreamAccordingToGivenResetFrequency() throws IOException {
+
+ // given
+ ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2);
+ String object = "foo";
+
+ // when
+ objectWriter.write(object);
+ objectWriter.write(object);
+ objectWriter.write(object);
+ objectWriter.write(object);
+
+ // then
+ InOrder inOrder = inOrder(objectOutputStream);
+ inOrder.verify(objectOutputStream).writeObjectOverride(object);
+ inOrder.verify(objectOutputStream).writeObjectOverride(object);
+ inOrder.verify(objectOutputStream).reset();
+ inOrder.verify(objectOutputStream).writeObjectOverride(object);
+ inOrder.verify(objectOutputStream).writeObjectOverride(object);
+ inOrder.verify(objectOutputStream).reset();
+ }
+
+ private static class InstrumentedObjectOutputStream extends ObjectOutputStream {
+
+ protected InstrumentedObjectOutputStream() throws IOException, SecurityException {
+ }
+
+ @Override
+ protected void writeObjectOverride(final Object obj) throws IOException {
+ // nop
+ }
+
+ @Override
+ public void flush() throws IOException {
+ // nop
+ }
+
+ @Override
+ public void reset() throws IOException {
+ // nop
+ }
+ }
+}
|
e3d1a1dda22723fc896bfc96c6db57c500faf208
|
spring-framework
|
@Resource injection points support @Lazy as well--Issue: SPR-
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java
index 592af8ef932f..ffb9b55320b6 100644
--- a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java
+++ b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2014 the original author or authors.
+ * Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,6 +44,8 @@
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceRef;
+import org.springframework.aop.TargetSource;
+import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
@@ -414,6 +416,44 @@ else if (bridgedMethod.isAnnotationPresent(Resource.class)) {
return new InjectionMetadata(clazz, elements);
}
+ /**
+ * Obtain a lazily resolving resource proxy for the given name and type,
+ * delegating to {@link #getResource} on demand once a method call comes in.
+ * @param element the descriptor for the annotated field/method
+ * @param requestingBeanName the name of the requesting bean
+ * @return the resource object (never {@code null})
+ * @since 4.2
+ * @see #getResource
+ * @see Lazy
+ */
+ protected Object buildLazyResourceProxy(final LookupElement element, final String requestingBeanName) {
+ TargetSource ts = new TargetSource() {
+ @Override
+ public Class<?> getTargetClass() {
+ return element.lookupType;
+ }
+ @Override
+ public boolean isStatic() {
+ return false;
+ }
+ @Override
+ public Object getTarget() {
+ return getResource(element, requestingBeanName);
+ }
+ @Override
+ public void releaseTarget(Object target) {
+ }
+ };
+ ProxyFactory pf = new ProxyFactory();
+ pf.setTargetSource(ts);
+ if (element.lookupType.isInterface()) {
+ pf.addInterface(element.lookupType);
+ }
+ ClassLoader classLoader = (this.beanFactory instanceof ConfigurableBeanFactory ?
+ ((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader() : null);
+ return pf.getProxy(classLoader);
+ }
+
/**
* Obtain the resource object for the given name and type.
* @param element the descriptor for the annotated field/method
@@ -527,6 +567,8 @@ public final DependencyDescriptor getDependencyDescriptor() {
*/
private class ResourceElement extends LookupElement {
+ private final boolean lazyLookup;
+
public ResourceElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) {
super(member, pd);
Resource resource = ae.getAnnotation(Resource.class);
@@ -552,11 +594,14 @@ else if (beanFactory instanceof ConfigurableBeanFactory){
this.name = resourceName;
this.lookupType = resourceType;
this.mappedName = resource.mappedName();
+ Lazy lazy = ae.getAnnotation(Lazy.class);
+ this.lazyLookup = (lazy != null && lazy.value());
}
@Override
protected Object getResourceToInject(Object target, String requestingBeanName) {
- return getResource(this, requestingBeanName);
+ return (this.lazyLookup ? buildLazyResourceProxy(this, requestingBeanName) :
+ getResource(this, requestingBeanName));
}
}
diff --git a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java
index c44662b418a9..92c684543feb 100644
--- a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java
+++ b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2014 the original author or authors.
+ * Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -437,6 +437,60 @@ public void testExtendedEjbInjection() {
assertTrue(bean.destroy2Called);
}
+ @Test
+ public void testLazyResolutionWithResourceField() {
+ DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
+ CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
+ bpp.setBeanFactory(bf);
+ bf.addBeanPostProcessor(bpp);
+
+ bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(LazyResourceFieldInjectionBean.class));
+ bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
+
+ LazyResourceFieldInjectionBean bean = (LazyResourceFieldInjectionBean) bf.getBean("annotatedBean");
+ assertFalse(bf.containsSingleton("testBean"));
+ bean.testBean.setName("notLazyAnymore");
+ assertTrue(bf.containsSingleton("testBean"));
+ TestBean tb = (TestBean) bf.getBean("testBean");
+ assertEquals("notLazyAnymore", tb.getName());
+ }
+
+ @Test
+ public void testLazyResolutionWithResourceMethod() {
+ DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
+ CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
+ bpp.setBeanFactory(bf);
+ bf.addBeanPostProcessor(bpp);
+
+ bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(LazyResourceMethodInjectionBean.class));
+ bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
+
+ LazyResourceMethodInjectionBean bean = (LazyResourceMethodInjectionBean) bf.getBean("annotatedBean");
+ assertFalse(bf.containsSingleton("testBean"));
+ bean.testBean.setName("notLazyAnymore");
+ assertTrue(bf.containsSingleton("testBean"));
+ TestBean tb = (TestBean) bf.getBean("testBean");
+ assertEquals("notLazyAnymore", tb.getName());
+ }
+
+ @Test
+ public void testLazyResolutionWithCglibProxy() {
+ DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
+ CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
+ bpp.setBeanFactory(bf);
+ bf.addBeanPostProcessor(bpp);
+
+ bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(LazyResourceCglibInjectionBean.class));
+ bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class));
+
+ LazyResourceCglibInjectionBean bean = (LazyResourceCglibInjectionBean) bf.getBean("annotatedBean");
+ assertFalse(bf.containsSingleton("testBean"));
+ bean.testBean.setName("notLazyAnymore");
+ assertTrue(bf.containsSingleton("testBean"));
+ TestBean tb = (TestBean) bf.getBean("testBean");
+ assertEquals("notLazyAnymore", tb.getName());
+ }
+
public static class AnnotatedInitDestroyBean {
@@ -716,6 +770,35 @@ private static class ConvertedResourceInjectionBean {
}
+ private static class LazyResourceFieldInjectionBean {
+
+ @Resource @Lazy
+ private ITestBean testBean;
+ }
+
+
+ private static class LazyResourceMethodInjectionBean {
+
+ private ITestBean testBean;
+
+ @Resource @Lazy
+ public void setTestBean(ITestBean testBean) {
+ this.testBean = testBean;
+ }
+ }
+
+
+ private static class LazyResourceCglibInjectionBean {
+
+ private TestBean testBean;
+
+ @Resource @Lazy
+ public void setTestBean(TestBean testBean) {
+ this.testBean = testBean;
+ }
+ }
+
+
@SuppressWarnings("unused")
private static class NullFactory {
|
527370f8c142d373c4543d0eb26cb2f0912ed9f0
|
camel
|
CAMEL-1320: Created gzip data format--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@756039 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java b/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
index e2eba66852b99..24892a459aa40 100644
--- a/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
+++ b/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
@@ -18,13 +18,12 @@
import java.util.zip.Deflater;
-import org.w3c.dom.Node;
-
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.dataformat.ArtixDSContentType;
import org.apache.camel.model.dataformat.ArtixDSDataFormat;
import org.apache.camel.model.dataformat.CsvDataFormat;
import org.apache.camel.model.dataformat.DataFormatDefinition;
+import org.apache.camel.model.dataformat.GzipDataFormat;
import org.apache.camel.model.dataformat.HL7DataFormat;
import org.apache.camel.model.dataformat.JaxbDataFormat;
import org.apache.camel.model.dataformat.JsonDataFormat;
@@ -36,6 +35,7 @@
import org.apache.camel.model.dataformat.XMLSecurityDataFormat;
import org.apache.camel.model.dataformat.XStreamDataFormat;
import org.apache.camel.model.dataformat.ZipDataFormat;
+import org.w3c.dom.Node;
/**
* An expression for constructing the different possible {@link org.apache.camel.spi.DataFormat}
@@ -242,6 +242,14 @@ public T zip(int compressionLevel) {
ZipDataFormat zdf = new ZipDataFormat(compressionLevel);
return dataFormat(zdf);
}
+
+ /**
+ * Uses the GZIP deflater data format
+ */
+ public T gzip() {
+ GzipDataFormat gzdf = new GzipDataFormat();
+ return dataFormat(gzdf);
+ }
@SuppressWarnings("unchecked")
private T dataFormat(DataFormatDefinition dataFormatType) {
diff --git a/camel-core/src/main/java/org/apache/camel/impl/GzipDataFormat.java b/camel-core/src/main/java/org/apache/camel/impl/GzipDataFormat.java
new file mode 100644
index 0000000000000..57cc53e148529
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/impl/GzipDataFormat.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.spi.DataFormat;
+import org.apache.camel.util.ExchangeHelper;
+import org.apache.camel.util.IOHelper;
+
+public class GzipDataFormat implements DataFormat {
+
+ public void marshal(Exchange exchange, Object graph, OutputStream stream)
+ throws Exception {
+ InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, graph);
+ if (is == null) {
+ throw new IllegalArgumentException("Cannot get the inputstream for GzipDataFormat mashalling");
+ }
+
+ GZIPOutputStream zipOutput = new GZIPOutputStream(stream);
+ try {
+ IOHelper.copy(is, zipOutput);
+ } finally {
+ zipOutput.close();
+ }
+
+ }
+
+ public Object unmarshal(Exchange exchange, InputStream stream)
+ throws Exception {
+ InputStream is = ExchangeHelper.getMandatoryInBody(exchange, InputStream.class);
+ GZIPInputStream unzipInput = new GZIPInputStream(is);
+
+ // Create an expandable byte array to hold the inflated data
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ IOHelper.copy(unzipInput, bos);
+ return bos.toByteArray();
+ }
+
+}
diff --git a/camel-core/src/main/java/org/apache/camel/model/dataformat/GzipDataFormat.java b/camel-core/src/main/java/org/apache/camel/model/dataformat/GzipDataFormat.java
new file mode 100644
index 0000000000000..864c347a9eac4
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/model/dataformat/GzipDataFormat.java
@@ -0,0 +1,35 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.model.dataformat;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.camel.spi.DataFormat;
+import org.apache.camel.spi.RouteContext;
+
+/**
+ * Represents the GZip {@link DataFormat}
+ *
+ * @version $Revision: 750806 $
+ */
+@XmlRootElement(name = "gzip")
+public class GzipDataFormat extends DataFormatDefinition {
+ @Override
+ protected DataFormat createDataFormat(RouteContext routeContext) {
+ return new org.apache.camel.impl.GzipDataFormat();
+ }
+}
diff --git a/camel-core/src/test/java/org/apache/camel/impl/GzipDataFormatTest.java b/camel-core/src/test/java/org/apache/camel/impl/GzipDataFormatTest.java
new file mode 100644
index 0000000000000..16b1b8393669e
--- /dev/null
+++ b/camel-core/src/test/java/org/apache/camel/impl/GzipDataFormatTest.java
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.impl;
+
+import java.io.ByteArrayInputStream;
+import java.util.zip.GZIPInputStream;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.converter.IOConverter;
+
+/**
+ * Unit test of the gzip data format.
+ */
+public class GzipDataFormatTest extends ContextTestSupport {
+ private static final String TEXT = "Hamlet by William Shakespeare\n" +
+ "To be, or not to be: that is the question:\n" +
+ "Whether 'tis nobler in the mind to suffer\n" +
+ "The slings and arrows of outrageous fortune,\n" +
+ "Or to take arms against a sea of troubles,\n" +
+ "And by opposing end them? To die: to sleep;";;
+
+ @Override
+ public boolean isUseRouteBuilder() {
+ return false;
+ }
+
+ private byte[] sendText() throws Exception {
+ return (byte[]) template.sendBody("direct:start", TEXT.getBytes("UTF-8"));
+ }
+
+ public void testMarshalTextToGZip() throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ public void configure() {
+ from("direct:start").marshal().gzip();
+ }
+ });
+ context.start();
+
+ byte[] output = sendText();
+
+ GZIPInputStream stream = new GZIPInputStream(new ByteArrayInputStream(output));
+ String result = IOConverter.toString(stream);
+ assertEquals("Uncompressed something different than compressed", TEXT, result);
+ }
+
+ public void testUnMarshalTextToGzip() throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ public void configure() {
+ from("direct:start").marshal().gzip().unmarshal().gzip().to("mock:result");
+ }
+ });
+ context.start();
+
+ MockEndpoint result = (MockEndpoint)context.getEndpoint("mock:result");
+ result.expectedBodiesReceived(TEXT.getBytes("UTF-8"));
+ sendText();
+ result.assertIsSatisfied();
+ }
+}
|
9e843df27fc2dd53c12327e9601206a7c677bd1f
|
orientdb
|
Improved auto-recognize of type in JSON reader--
|
p
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
index 7876b46308a..1122716eb39 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
@@ -62,6 +62,8 @@ public class ORecordSerializerJSON extends ORecordSerializerStringAbstract {
public static final char[] PARAMETER_SEPARATOR = new char[] { ':', ',' };
private static final Long MAX_INT = new Long(Integer.MAX_VALUE);
private static final Long MIN_INT = new Long(Integer.MIN_VALUE);
+ private static final Double MAX_FLOAT = new Double(Float.MAX_VALUE);
+ private static final Double MIN_FLOAT = new Double(Float.MIN_VALUE);
private SimpleDateFormat dateFormat = new SimpleDateFormat(DEF_DATE_FORMAT);
@@ -306,10 +308,21 @@ else if (iType == OType.LINKLIST)
// TRY TO AUTODETERMINE THE BEST TYPE
if (iFieldValue.charAt(0) == ORID.PREFIX && iFieldValue.contains(":"))
iType = OType.LINK;
- else if (OStringSerializerHelper.contains(iFieldValue, '.'))
- iType = OType.FLOAT;
- else {
+ else if (OStringSerializerHelper.contains(iFieldValue, '.')) {
+ // DECIMAL FORMAT: DETERMINE IF DOUBLE OR FLOAT
+ final Double v = new Double(OStringSerializerHelper.getStringContent(iFieldValue));
+ if (v.doubleValue() > 0) {
+ // POSITIVE NUMBER
+ if (v.compareTo(MAX_FLOAT) <= 0)
+ return v.floatValue();
+ } else if (v.compareTo(MIN_FLOAT) >= 0)
+ // NEGATIVE NUMBER
+ return v.floatValue();
+
+ return v;
+ } else {
final Long v = new Long(OStringSerializerHelper.getStringContent(iFieldValue));
+ // INTEGER FORMAT: DETERMINE IF DOUBLE OR FLOAT
if (v.longValue() > 0) {
// POSITIVE NUMBER
if (v.compareTo(MAX_INT) <= 0)
|
9cd153c55aa071528a013ecd28014734346d4127
|
drools
|
Changes to resolve issues discovered in integration- tests--git-svn-id: https://svn.jboss.org/repos/labs/trunk/labs/jbossrules@3441 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java
index 4d01a0107dc..163b8d19d8e 100644
--- a/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java
+++ b/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java
@@ -1,6 +1,7 @@
package org.drools.integrationtests;
import java.io.InputStreamReader;
+import java.util.ArrayList;
import java.util.List;
import org.drools.Cheese;
@@ -16,53 +17,150 @@ protected RuleBase getRuleBase() throws Exception {
return new org.drools.leaps.RuleBaseImpl();
}
- /**
- * Leaps query requires fireAll run before any probing can be done. this
- * test mirrors one in IntegrationCases.java with addition of call to
- * workingMemory.fireAll to facilitate query execution
- */
+ /**
+ * Leaps query requires fireAll run before any probing can be done. this
+ * test mirrors one in IntegrationCases.java with addition of call to
+ * workingMemory.fireAll to facilitate query execution
+ */
public void testQuery() throws Exception {
PackageBuilder builder = new PackageBuilder();
- builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "simple_query_test.drl" ) ) );
+ builder.addPackageFromDrl(new InputStreamReader(getClass()
+ .getResourceAsStream("simple_query_test.drl")));
Package pkg = builder.getPackage();
-
+
RuleBase ruleBase = getRuleBase();
- ruleBase.addPackage( pkg );
+ ruleBase.addPackage(pkg);
WorkingMemory workingMemory = ruleBase.newWorkingMemory();
-
+
Cheese stilton = new Cheese("stinky", 5);
- workingMemory.assertObject( stilton );
- workingMemory.fireAllRules();
- List results = workingMemory.getQueryResults( "simple query" );
- assertEquals(1, results.size());
+ workingMemory.assertObject(stilton);
+ workingMemory.fireAllRules();// <=== the only difference from the base test case
+ List results = workingMemory.getQueryResults("simple query");
+ assertEquals(1, results.size());
}
-
+
+ /**
+ * leaps does not create activations upfront hence its inability to apply
+ * auto-focus predicate in the same way as reteoo does. activations in
+ * reteoo sense created in the order rules would fire based what used to be
+ * called conflict resolution.
+ *
+ * So, while agenda groups feature works it mirrors reteoo behaviour up to
+ * the point where auto-focus comes into play. At this point leaps and
+ * reteoo are different at which point auto-focus should "fire".
+ *
+ * the other problem that relates to the lack of activations before rules
+ * start firing is that agenda group is removed from focus stack when agenda
+ * group is empty. This also affects module / focus behaviour
+ */
public void testAgendaGroups() throws Exception {
- //not implemented yet
+ PackageBuilder builder = new PackageBuilder();
+ builder.addPackageFromDrl(new InputStreamReader(getClass()
+ .getResourceAsStream("test_AgendaGroups.drl")));
+ Package pkg = builder.getPackage();
+
+ RuleBase ruleBase = getRuleBase();
+ ruleBase.addPackage(pkg);
+ WorkingMemory workingMemory = ruleBase.newWorkingMemory();
+
+ List list = new ArrayList();
+ workingMemory.setGlobal("list", list);
+
+ Cheese brie = new Cheese("brie", 12);
+ workingMemory.assertObject(brie);
+
+ workingMemory.fireAllRules();
+
+ assertEquals(3, list.size());
+
+ assertEquals("MAIN", list.get(0)); // salience 10
+ assertEquals("group3", list.get(1)); // salience 5. set auto focus to
+ // group 3
+ // no group 3 activations at this point, pop it, next activation that
+ // can fire is MAIN
+ assertEquals("MAIN", list.get(2));
+ // assertEquals( "group2", list.get( 3 ) );
+ // assertEquals( "group4", list.get( 4 ) );
+ // assertEquals( "group1", list.get( 5 ) );
+ // assertEquals( "group3", list.get( 6 ) );
+ // assertEquals( "group1", list.get( 7 ) );
+
+ workingMemory.setFocus("group2");
+ workingMemory.fireAllRules();
+
+ assertEquals(4, list.size());
+ assertEquals("group2", list.get(3));
}
+ /**
+ * exception test are leaps specific due to the fact that left hand side of
+ * the rule is not being evaluated until fireAllRules is called. Otherwise
+ * the test cases are exactly the same
+ */
public void testEvalException() throws Exception {
- //not implemented yet
+ PackageBuilder builder = new PackageBuilder();
+ builder.addPackageFromDrl(new InputStreamReader(getClass()
+ .getResourceAsStream("test_EvalException.drl")));
+ Package pkg = builder.getPackage();
+
+ RuleBase ruleBase = getRuleBase();
+ ruleBase.addPackage(pkg);
+ WorkingMemory workingMemory = ruleBase.newWorkingMemory();
+
+ Cheese brie = new Cheese("brie", 12);
+
+ try {
+ workingMemory.assertObject(brie);
+ workingMemory.fireAllRules(); // <=== the only difference from the base test case
+ fail("Should throw an Exception from the Eval");
+ } catch (Exception e) {
+ assertEquals("this should throw an exception", e.getCause()
+ .getMessage());
+ }
}
public void testPredicateException() throws Exception {
- //not implemented yet
+ PackageBuilder builder = new PackageBuilder();
+ builder.addPackageFromDrl(new InputStreamReader(getClass()
+ .getResourceAsStream("test_PredicateException.drl")));
+ Package pkg = builder.getPackage();
+
+ RuleBase ruleBase = getRuleBase();
+ ruleBase.addPackage(pkg);
+ WorkingMemory workingMemory = ruleBase.newWorkingMemory();
+
+ Cheese brie = new Cheese("brie", 12);
+
+ try {
+ workingMemory.assertObject(brie);
+ workingMemory.fireAllRules(); // <=== the only difference from the base test case
+ fail("Should throw an Exception from the Predicate");
+ } catch (Exception e) {
+ assertEquals("this should throw an exception", e.getCause()
+ .getMessage());
+ }
}
public void testReturnValueException() throws Exception {
- //not implemented yet
- }
+ PackageBuilder builder = new PackageBuilder();
+ builder.addPackageFromDrl(new InputStreamReader(getClass()
+ .getResourceAsStream("test_ReturnValueException.drl")));
+ Package pkg = builder.getPackage();
- public void testDurationWithNoLoop() {
- //not implemented yet
- }
+ RuleBase ruleBase = getRuleBase();
+ ruleBase.addPackage(pkg);
+ WorkingMemory workingMemory = ruleBase.newWorkingMemory();
- public void testNoLoop() throws Exception {
- //not implemented yet
- }
-
- public void testDynamicFunction() {
- //ERRROR HERE !
+ Cheese brie = new Cheese("brie", 12);
+
+ try {
+ workingMemory.assertObject(brie);
+ workingMemory.fireAllRules(); // <=== the only difference from the base test case
+ fail("Should throw an Exception from the ReturnValue");
+ } catch (Exception e) {
+ assertEquals("this should throw an exception", e.getCause()
+ .getMessage());
+ }
}
}
diff --git a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
index 002eca68fb7..c75f8edb6b6 100644
--- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
+++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
@@ -78,13 +78,11 @@ abstract public class AbstractWorkingMemory
/** The actual memory for the <code>JoinNode</code>s. */
private final PrimitiveLongMap nodeMemories = new PrimitiveLongMap( 32,
8 );
-
- /** Application data which is associated with this memory. */
- protected final Map applicationData = new HashMap();
-
/** Handle-to-object mapping. */
protected final PrimitiveLongMap objects = new PrimitiveLongMap( 32,
8 );
+ /** Global values which are associated with this memory. */
+ private final Map globals = new HashMap();
/** Object-to-handle mapping. */
protected final Map identityMap = new IdentityMap();
@@ -164,14 +162,14 @@ FactHandle newFactHandle() {
* @see WorkingMemory
*/
public Map getGlobals() {
- return this.applicationData;
+ return this.globals;
}
/**
* @see WorkingMemory
*/
public Object getGlobal(String name) {
- return this.applicationData.get( name );
+ return this.globals.get( name );
}
/**
diff --git a/drools-core/src/main/java/org/drools/leaps/FactTable.java b/drools-core/src/main/java/org/drools/leaps/FactTable.java
index 4be84e10208..83c0468c27e 100644
--- a/drools-core/src/main/java/org/drools/leaps/FactTable.java
+++ b/drools-core/src/main/java/org/drools/leaps/FactTable.java
@@ -20,8 +20,9 @@
import java.util.Iterator;
import java.util.Set;
+import org.drools.common.PropagationContextImpl;
import org.drools.leaps.util.Table;
-import org.drools.leaps.util.TableOutOfBoundException;
+import org.drools.spi.PropagationContext;
/**
* Implementation of a container to store data elements used throughout the
@@ -41,14 +42,13 @@ class FactTable extends Table {
* dynamic rule management support. used to push facts on stack again after
* fireAllRules by working memory and adding of a new rule after that
*/
- private boolean reseededStack = false;
+ private boolean reseededStack = false;
/**
- * Tuples that are either already on agenda or are very close (missing exists or
- * have not facts matching)
+ * Tuples that are either already on agenda or are very close (missing
+ * exists or have not facts matching)
*/
-
- private final Set tuples;
+ private final Set tuples;
/**
* initializes base LeapsTable with appropriate Comparator and positive and
@@ -58,8 +58,8 @@ class FactTable extends Table {
* @param ruleConflictResolver
*/
public FactTable(ConflictResolver conflictResolver) {
- super( conflictResolver.getFactConflictResolver() );
- this.rules = new RuleTable( conflictResolver.getRuleConflictResolver() );
+ super(conflictResolver.getFactConflictResolver());
+ this.rules = new RuleTable(conflictResolver.getRuleConflictResolver());
this.tuples = new HashSet();
}
@@ -69,11 +69,10 @@ public FactTable(ConflictResolver conflictResolver) {
* @param workingMemory
* @param ruleHandle
*/
- public void addRule(WorkingMemoryImpl workingMemory,
- RuleHandle ruleHandle) {
- this.rules.add( ruleHandle );
+ public void addRule(WorkingMemoryImpl workingMemory, RuleHandle ruleHandle) {
+ this.rules.add(ruleHandle);
// push facts back to stack if needed
- this.checkAndAddFactsToStack( workingMemory );
+ this.checkAndAddFactsToStack(workingMemory);
}
/**
@@ -82,7 +81,7 @@ public void addRule(WorkingMemoryImpl workingMemory,
* @param ruleHandle
*/
public void removeRule(RuleHandle ruleHandle) {
- this.rules.remove( ruleHandle );
+ this.rules.remove(ruleHandle);
}
/**
@@ -95,20 +94,21 @@ public void removeRule(RuleHandle ruleHandle) {
*
*/
private void checkAndAddFactsToStack(WorkingMemoryImpl workingMemory) {
- if ( this.reseededStack ) {
- this.setReseededStack( false );
+ if (this.reseededStack) {
+ this.setReseededStack(false);
+
+ PropagationContextImpl context = new PropagationContextImpl(
+ workingMemory.nextPropagationIdCounter(),
+ PropagationContext.ASSERTION, null, null);
+
// let's only add facts below waterline - added before rule is added
// rest would be added to stack automatically
- Handle factHandle = new FactHandleImpl( workingMemory.getIdLastFireAllAt(),
- null );
- try {
- for ( Iterator it = this.tailIterator( factHandle,
- factHandle ); it.hasNext(); ) {
- workingMemory.pushTokenOnStack( new Token( workingMemory,
- (FactHandleImpl) it.next() ) );
- }
- } catch ( TableOutOfBoundException e ) {
- // should never get here
+ Handle factHandle = new FactHandleImpl(workingMemory
+ .getIdLastFireAllAt(), null);
+ for (Iterator it = this.tailIterator(factHandle, factHandle); it
+ .hasNext();) {
+ workingMemory.pushTokenOnStack(new Token(workingMemory,
+ (FactHandleImpl) it.next(), context));
}
}
}
@@ -139,22 +139,23 @@ public Iterator getRulesIterator() {
public String toString() {
StringBuffer ret = new StringBuffer();
- for ( Iterator it = this.iterator(); it.hasNext(); ) {
+ for (Iterator it = this.iterator(); it.hasNext();) {
FactHandleImpl handle = (FactHandleImpl) it.next();
- ret.append( "\n" + handle + "[" + handle.getObject() + "]" );
+ ret.append("\n" + handle + "[" + handle.getObject() + "]");
}
- ret.append( "\nTuples :" );
+ ret.append("\nTuples :");
- for ( Iterator it = this.tuples.iterator(); it.hasNext(); ) {
- ret.append( "\n" + it.next() );
+ for (Iterator it = this.tuples.iterator(); it.hasNext();) {
+ ret.append("\n" + it.next());
}
- ret.append( "\nRules :" );
+ ret.append("\nRules :");
- for ( Iterator it = this.rules.iterator(); it.hasNext(); ) {
+ for (Iterator it = this.rules.iterator(); it.hasNext();) {
RuleHandle handle = (RuleHandle) it.next();
- ret.append( "\n\t" + handle.getLeapsRule().getRule().getName() + "[dominant - " + handle.getDominantPosition() + "]" );
+ ret.append("\n\t" + handle.getLeapsRule().getRule().getName()
+ + "[dominant - " + handle.getDominantPosition() + "]");
}
return ret.toString();
@@ -165,10 +166,10 @@ Iterator getTuplesIterator() {
}
boolean addTuple(LeapsTuple tuple) {
- return this.tuples.add( tuple );
+ return this.tuples.add(tuple);
}
void removeTuple(LeapsTuple tuple) {
- this.tuples.remove( tuple );
+ this.tuples.remove(tuple);
}
}
diff --git a/drools-core/src/main/java/org/drools/leaps/LeapsRule.java b/drools-core/src/main/java/org/drools/leaps/LeapsRule.java
index 5748b92ce5a..6179ced1b48 100644
--- a/drools-core/src/main/java/org/drools/leaps/LeapsRule.java
+++ b/drools-core/src/main/java/org/drools/leaps/LeapsRule.java
@@ -18,6 +18,8 @@
import java.util.ArrayList;
+import org.drools.common.ActivationQueue;
+import org.drools.common.AgendaGroupImpl;
import org.drools.rule.EvalCondition;
import org.drools.rule.Rule;
@@ -29,7 +31,7 @@
*
*/
class LeapsRule {
- Rule rule;
+ Rule rule;
final ColumnConstraints[] columnConstraints;
@@ -37,43 +39,45 @@ class LeapsRule {
final ColumnConstraints[] existsColumnConstraints;
- final EvalCondition[] evalConditions;
+ final EvalCondition[] evalConditions;
- boolean notColumnsPresent;
+ boolean notColumnsPresent;
- boolean existsColumnsPresent;
+ boolean existsColumnsPresent;
- boolean evalCoditionsPresent;
+ boolean evalCoditionsPresent;
- final Class[] existsNotsClasses;
+ final Class[] existsNotsClasses;
- public LeapsRule(Rule rule,
- ArrayList columns,
- ArrayList notColumns,
- ArrayList existsColumns,
- ArrayList evalConditions) {
+ public LeapsRule(Rule rule, ArrayList columns, ArrayList notColumns,
+ ArrayList existsColumns, ArrayList evalConditions) {
this.rule = rule;
- this.columnConstraints = (ColumnConstraints[]) columns.toArray( new ColumnConstraints[0] );
- this.notColumnConstraints = (ColumnConstraints[]) notColumns.toArray( new ColumnConstraints[0] );
- this.existsColumnConstraints = (ColumnConstraints[]) existsColumns.toArray( new ColumnConstraints[0] );
- this.evalConditions = (EvalCondition[]) evalConditions.toArray( new EvalCondition[0] );
+ this.columnConstraints = (ColumnConstraints[]) columns
+ .toArray(new ColumnConstraints[0]);
+ this.notColumnConstraints = (ColumnConstraints[]) notColumns
+ .toArray(new ColumnConstraints[0]);
+ this.existsColumnConstraints = (ColumnConstraints[]) existsColumns
+ .toArray(new ColumnConstraints[0]);
+ this.evalConditions = (EvalCondition[]) evalConditions
+ .toArray(new EvalCondition[0]);
this.notColumnsPresent = (this.notColumnConstraints.length != 0);
this.existsColumnsPresent = (this.existsColumnConstraints.length != 0);
this.evalCoditionsPresent = (this.evalConditions.length != 0);
ArrayList classes = new ArrayList();
- for ( int i = 0; i < this.notColumnConstraints.length; i++ ) {
- if ( classes.contains( this.notColumnConstraints[i].getClassType() ) ) {
- classes.add( this.notColumnConstraints[i].getClassType() );
+ for (int i = 0; i < this.notColumnConstraints.length; i++) {
+ if (classes.contains(this.notColumnConstraints[i].getClassType())) {
+ classes.add(this.notColumnConstraints[i].getClassType());
}
}
- for ( int i = 0; i < this.existsColumnConstraints.length; i++ ) {
- if ( !classes.contains( this.existsColumnConstraints[i].getClassType() ) ) {
- classes.add( this.existsColumnConstraints[i].getClassType() );
+ for (int i = 0; i < this.existsColumnConstraints.length; i++) {
+ if (!classes.contains(this.existsColumnConstraints[i]
+ .getClassType())) {
+ classes.add(this.existsColumnConstraints[i].getClassType());
}
}
- this.existsNotsClasses = (Class[]) classes.toArray( new Class[0] );
+ this.existsNotsClasses = (Class[]) classes.toArray(new Class[0]);
}
Rule getRule() {
@@ -139,4 +143,30 @@ public boolean equals(Object that) {
Class[] getExistsNotColumnsClasses() {
return this.existsNotsClasses;
}
+
+ /**
+ * to simulate terminal node memory we introduce
+ * TerminalNodeMemory type attributes here
+ *
+ */
+ private AgendaGroupImpl agendaGroup;
+
+ private ActivationQueue lifo;
+
+ public ActivationQueue getLifo() {
+ return this.lifo;
+ }
+
+ public void setLifo(ActivationQueue lifo) {
+ this.lifo = lifo;
+ }
+
+ public AgendaGroupImpl getAgendaGroup() {
+ return this.agendaGroup;
+ }
+
+ public void setAgendaGroup(AgendaGroupImpl agendaGroup) {
+ this.agendaGroup = agendaGroup;
+ }
+
}
diff --git a/drools-core/src/main/java/org/drools/leaps/LeapsTuple.java b/drools-core/src/main/java/org/drools/leaps/LeapsTuple.java
index dcbbf1ea3da..1db7fa6032f 100644
--- a/drools-core/src/main/java/org/drools/leaps/LeapsTuple.java
+++ b/drools-core/src/main/java/org/drools/leaps/LeapsTuple.java
@@ -32,52 +32,51 @@
*
* @author Alexander Bagerman
*/
-class LeapsTuple
- implements
- Tuple,
- Serializable {
- private static final long serialVersionUID = 1L;
+class LeapsTuple implements Tuple, Serializable {
+ private static final long serialVersionUID = 1L;
private final PropagationContext context;
- private boolean readyForActivation;
+ private boolean readyForActivation;
- private final FactHandleImpl[] factHandles;
+ private final FactHandleImpl[] factHandles;
- private Set[] notFactHandles;
+ private Set[] notFactHandles;
- private Set[] existsFactHandles;
+ private Set[] existsFactHandles;
- private Set logicalDependencies;
+ private Set logicalDependencies;
- private Activation activation;
+ private Activation activation;
- private final LeapsRule leapsRule;
+ private final LeapsRule leapsRule;
/**
* agendaItem parts
*/
- LeapsTuple(FactHandleImpl factHandles[],
- LeapsRule leapsRule,
- PropagationContext context) {
+ LeapsTuple(FactHandleImpl factHandles[], LeapsRule leapsRule,
+ PropagationContext context) {
this.factHandles = factHandles;
this.leapsRule = leapsRule;
this.context = context;
- if ( this.leapsRule != null && this.leapsRule.containsNotColumns() ) {
- this.notFactHandles = new HashSet[this.leapsRule.getNotColumnConstraints().length];
+ if (this.leapsRule != null && this.leapsRule.containsNotColumns()) {
+ this.notFactHandles = new HashSet[this.leapsRule
+ .getNotColumnConstraints().length];
}
- if ( this.leapsRule != null && this.leapsRule.containsExistsColumns() ) {
- this.existsFactHandles = new HashSet[this.leapsRule.getExistsColumnConstraints().length];
+ if (this.leapsRule != null && this.leapsRule.containsExistsColumns()) {
+ this.existsFactHandles = new HashSet[this.leapsRule
+ .getExistsColumnConstraints().length];
}
- this.readyForActivation = (this.leapsRule == null || !this.leapsRule.containsExistsColumns());
+ this.readyForActivation = (this.leapsRule == null || !this.leapsRule
+ .containsExistsColumns());
}
/**
* get rule that caused this tuple to be generated
*
- * @return rule
+ * @return rule
*/
LeapsRule getLeapsRule() {
return this.leapsRule;
@@ -95,8 +94,8 @@ LeapsRule getLeapsRule() {
* @see org.drools.spi.Tuple
*/
public boolean dependsOn(FactHandle handle) {
- for ( int i = 0, length = this.factHandles.length; i < length; i++ ) {
- if ( handle.equals( this.factHandles[i] ) ) {
+ for (int i = 0, length = this.factHandles.length; i < length; i++) {
+ if (handle.equals(this.factHandles[i])) {
return true;
}
}
@@ -114,7 +113,7 @@ public FactHandle get(int col) {
* @see org.drools.spi.Tuple
*/
public FactHandle get(Declaration declaration) {
- return this.get( declaration.getColumn() );
+ return this.get(declaration.getColumn());
}
/**
@@ -149,21 +148,21 @@ Activation getActivation() {
* @see java.lang.Object
*/
public boolean equals(Object object) {
- if ( this == object ) {
+ if (this == object) {
return true;
}
- if ( object == null || !(object instanceof LeapsTuple) ) {
+ if (object == null || !(object instanceof LeapsTuple)) {
return false;
}
FactHandle[] thatFactHandles = ((LeapsTuple) object).getFactHandles();
- if ( thatFactHandles.length != this.factHandles.length ) {
+ if (thatFactHandles.length != this.factHandles.length) {
return false;
}
- for ( int i = 0, length = this.factHandles.length; i < length; i++ ) {
- if ( !this.factHandles[i].equals( thatFactHandles[i] ) ) {
+ for (int i = 0, length = this.factHandles.length; i < length; i++) {
+ if (!this.factHandles[i].equals(thatFactHandles[i])) {
return false;
}
@@ -184,67 +183,66 @@ boolean isReadyForActivation() {
* @see java.lang.Object
*/
public String toString() {
- StringBuffer buffer = new StringBuffer( "LeapsTuple [" + this.context.getRuleOrigin().getName() + "] " );
+ StringBuffer buffer = new StringBuffer("LeapsTuple ["
+ + this.leapsRule.getRule().getName() + "] ");
- for ( int i = 0, length = this.factHandles.length; i < length; i++ ) {
- buffer.append( ((i == 0) ? "" : ", ") + this.factHandles[i] );
+ for (int i = 0, length = this.factHandles.length; i < length; i++) {
+ buffer.append(((i == 0) ? "" : ", ") + this.factHandles[i]);
}
- if ( this.existsFactHandles != null ) {
- buffer.append( "\nExists fact handles by position" );
- for ( int i = 0, length = this.existsFactHandles.length; i < length; i++ ) {
- buffer.append( "\nposition " + i );
- for ( Iterator it = this.existsFactHandles[i].iterator(); it.hasNext(); ) {
- buffer.append( "\n\t" + it.next() );
+ if (this.existsFactHandles != null) {
+ buffer.append("\nExists fact handles by position");
+ for (int i = 0, length = this.existsFactHandles.length; i < length; i++) {
+ buffer.append("\nposition " + i);
+ for (Iterator it = this.existsFactHandles[i].iterator(); it
+ .hasNext();) {
+ buffer.append("\n\t" + it.next());
}
}
}
- if ( this.notFactHandles != null ) {
- buffer.append( "\nNot fact handles by position" );
- for ( int i = 0, length = this.notFactHandles.length; i < length; i++ ) {
- buffer.append( "\nposition " + i );
- for ( Iterator it = this.notFactHandles[i].iterator(); it.hasNext(); ) {
- buffer.append( "\n\t" + it.next() );
+ if (this.notFactHandles != null) {
+ buffer.append("\nNot fact handles by position");
+ for (int i = 0, length = this.notFactHandles.length; i < length; i++) {
+ buffer.append("\nposition " + i);
+ for (Iterator it = this.notFactHandles[i].iterator(); it
+ .hasNext();) {
+ buffer.append("\n\t" + it.next());
}
}
}
return buffer.toString();
}
- void addNotFactHandle(FactHandle factHandle,
- int index) {
+ void addNotFactHandle(FactHandle factHandle, int index) {
this.readyForActivation = false;
Set facts = this.notFactHandles[index];
- if ( facts == null ) {
+ if (facts == null) {
facts = new HashSet();
this.notFactHandles[index] = facts;
}
- facts.add( factHandle );
+ facts.add(factHandle);
}
- void removeNotFactHandle(FactHandle factHandle,
- int index) {
- if ( this.notFactHandles[index] != null ) {
- this.notFactHandles[index].remove( factHandle );
+ void removeNotFactHandle(FactHandle factHandle, int index) {
+ if (this.notFactHandles[index] != null) {
+ this.notFactHandles[index].remove(factHandle);
}
this.setReadyForActivation();
}
- void addExistsFactHandle(FactHandle factHandle,
- int index) {
+ void addExistsFactHandle(FactHandle factHandle, int index) {
Set facts = this.existsFactHandles[index];
- if ( facts == null ) {
+ if (facts == null) {
facts = new HashSet();
this.existsFactHandles[index] = facts;
}
- facts.add( factHandle );
+ facts.add(factHandle);
this.setReadyForActivation();
}
- void removeExistsFactHandle(FactHandle factHandle,
- int index) {
- if ( this.existsFactHandles[index] != null ) {
- this.existsFactHandles[index].remove( factHandle );
+ void removeExistsFactHandle(FactHandle factHandle, int index) {
+ if (this.existsFactHandles[index] != null) {
+ this.existsFactHandles[index].remove(factHandle);
}
this.setReadyForActivation();
}
@@ -252,16 +250,18 @@ void removeExistsFactHandle(FactHandle factHandle,
private void setReadyForActivation() {
this.readyForActivation = true;
- if ( this.notFactHandles != null ) {
- for ( int i = 0, length = this.notFactHandles.length; i < length && this.readyForActivation; i++ ) {
- if ( this.notFactHandles[i].size() > 0 ) {
+ if (this.notFactHandles != null) {
+ for (int i = 0, length = this.notFactHandles.length; i < length
+ && this.readyForActivation; i++) {
+ if (this.notFactHandles[i].size() > 0) {
this.readyForActivation = false;
}
}
}
- if ( this.existsFactHandles != null ) {
- for ( int i = 0, length = this.existsFactHandles.length; i < length && this.readyForActivation; i++ ) {
- if ( this.existsFactHandles[i].size() == 0 ) {
+ if (this.existsFactHandles != null) {
+ for (int i = 0, length = this.existsFactHandles.length; i < length
+ && this.readyForActivation; i++) {
+ if (this.existsFactHandles[i].size() == 0) {
this.readyForActivation = false;
}
}
@@ -273,14 +273,14 @@ PropagationContext getContext() {
}
void addLogicalDependency(FactHandle handle) {
- if ( this.logicalDependencies == null ) {
+ if (this.logicalDependencies == null) {
this.logicalDependencies = new HashSet();
}
- this.logicalDependencies.add( handle );
+ this.logicalDependencies.add(handle);
}
Iterator getLogicalDependencies() {
- if ( this.logicalDependencies != null ) {
+ if (this.logicalDependencies != null) {
return this.logicalDependencies.iterator();
}
return null;
diff --git a/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java b/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
index 2784906ebef..b5d0e71c94e 100644
--- a/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
+++ b/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
@@ -17,7 +17,6 @@
*/
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -30,6 +29,7 @@
import org.drools.WorkingMemory;
import org.drools.rule.InvalidPatternException;
import org.drools.rule.Package;
+import org.drools.rule.PackageCompilationData;
import org.drools.rule.Rule;
import org.drools.spi.FactHandleFactory;
@@ -40,23 +40,20 @@
* @author Alexander Bagerman
*
*/
-public class RuleBaseImpl
- implements
- RuleBase {
- private static final long serialVersionUID = 1487738104393155409L;
+public class RuleBaseImpl implements RuleBase {
+ private static final long serialVersionUID = 1487738104393155409L;
- private HashMap leapsRules = new HashMap();
+ private HashMap leapsRules = new HashMap();
/**
* The fact handle factory.
*/
- private final HandleFactory factHandleFactory;
+ private final FactHandleFactory factHandleFactory;
- private Set rulesPackages;
+ private Map globalDeclarations;
- private Map applicationData;
+ private Map rulesPackages;
- // @todo: replace this with a weak HashSet
/**
* WeakHashMap to keep references of WorkingMemories but allow them to be
* garbage collected
@@ -64,20 +61,17 @@ public class RuleBaseImpl
private final transient Map workingMemories;
/** Special value when adding to the underlying map. */
- private static final Object PRESENT = new Object();
+ private static final Object PRESENT = new Object();
/**
* Construct.
*
* @param rete
* The rete network.
- * @throws PackageIntegrationException
+ * @throws PackageIntegrationException
*/
public RuleBaseImpl() throws PackageIntegrationException {
- this( new HandleFactory(),
- new HashSet(),
- new HashMap() );
-
+ this(new HandleFactory());
}
/**
@@ -91,50 +85,43 @@ public RuleBaseImpl() throws PackageIntegrationException {
* The fact handle factory.
* @param pkgs
* @param applicationData
- * @throws PackageIntegrationException
- * @throws Exception
+ * @throws PackageIntegrationException
+ * @throws Exception
*/
- public RuleBaseImpl(FactHandleFactory factHandleFactory,
- Set pkgs,
- Map applicationData) throws PackageIntegrationException {
- // because we can deal only with leaps fact handle factory
+ public RuleBaseImpl(FactHandleFactory factHandleFactory) {
+ // casting to make sure that it's leaps handle factory
this.factHandleFactory = (HandleFactory) factHandleFactory;
- this.rulesPackages = pkgs;
- this.applicationData = applicationData;
+ this.globalDeclarations = new HashMap();
this.workingMemories = new WeakHashMap();
- this.rulesPackages = new HashSet();
- for ( Iterator it = pkgs.iterator(); it.hasNext(); ) {
- this.addPackage( (Package) it.next() );
- }
+ this.rulesPackages = new HashMap();
}
/**
* @see RuleBase
*/
public WorkingMemory newWorkingMemory() {
- return newWorkingMemory( true );
+ return newWorkingMemory(true);
}
/**
* @see RuleBase
*/
public WorkingMemory newWorkingMemory(boolean keepReference) {
- WorkingMemoryImpl workingMemory = new WorkingMemoryImpl( this );
+ WorkingMemoryImpl workingMemory = new WorkingMemoryImpl(this);
// add all rules added so far
- for ( Iterator it = this.leapsRules.values().iterator(); it.hasNext(); ) {
- workingMemory.addLeapsRules( (List) it.next() );
+ for (Iterator it = this.leapsRules.values().iterator(); it.hasNext();) {
+ workingMemory.addLeapsRules((List) it.next());
}
//
- if ( keepReference ) {
- this.workingMemories.put( workingMemory,
- RuleBaseImpl.PRESENT );
+ if (keepReference) {
+ this.workingMemories.put(workingMemory, RuleBaseImpl.PRESENT);
}
return workingMemory;
}
void disposeWorkingMemory(WorkingMemory workingMemory) {
- this.workingMemories.remove( workingMemory );
+ this.workingMemories.remove(workingMemory);
}
/**
@@ -157,12 +144,14 @@ public FactHandleFactory newFactHandleFactory() {
/**
* @see RuleBase
*/
+
public Package[] getPackages() {
- return (Package[]) this.rulesPackages.toArray( new Package[this.rulesPackages.size()] );
+ return (Package[]) this.rulesPackages.values().toArray(
+ new Package[this.rulesPackages.size()]);
}
- public Map getApplicationData() {
- return this.applicationData;
+ public Map getGlobalDeclarations() {
+ return this.globalDeclarations;
}
/**
@@ -172,32 +161,74 @@ public Map getApplicationData() {
*
* @param rulesPackage
* The rule-set to add.
- * @throws PackageIntegrationException
+ * @throws PackageIntegrationException
*
* @throws FactException
* @throws InvalidPatternException
*/
- public void addPackage(Package rulesPackage) throws PackageIntegrationException {
- rulesPackage.checkValidity();
- Map newApplicationData = rulesPackage.getGlobals();
+ public void addPackage(Package newPackage)
+ throws PackageIntegrationException {
+ newPackage.checkValidity();
+ Package pkg = (Package) this.rulesPackages.get(newPackage.getName());
+ if (pkg != null) {
+ mergePackage(pkg, newPackage);
+ } else {
+ this.rulesPackages.put(newPackage.getName(), newPackage);
+ }
- // Check that the application data is valid, we cannot change the type
- // of an already declared application data variable
- for ( Iterator it = newApplicationData.keySet().iterator(); it.hasNext(); ) {
+ Map newGlobals = newPackage.getGlobals();
+
+ // Check that the global data is valid, we cannot change the type
+ // of an already declared global variable
+ for (Iterator it = newGlobals.keySet().iterator(); it.hasNext();) {
String identifier = (String) it.next();
- Class type = (Class) newApplicationData.get( identifier );
- if ( this.applicationData.containsKey( identifier ) && !this.applicationData.get( identifier ).equals( type ) ) {
- throw new PackageIntegrationException( rulesPackage );
+ Class type = (Class) newGlobals.get(identifier);
+ if (this.globalDeclarations.containsKey(identifier)
+ && !this.globalDeclarations.get(identifier).equals(type)) {
+ throw new PackageIntegrationException(pkg);
}
}
- this.applicationData.putAll( newApplicationData );
+ this.globalDeclarations.putAll(newGlobals);
+
+ Rule[] rules = newPackage.getRules();
+
+ for (int i = 0; i < rules.length; ++i) {
+ addRule(rules[i]);
+ }
+ }
+
+ public void mergePackage(Package existingPackage, Package newPackage)
+ throws PackageIntegrationException {
+ Map globals = existingPackage.getGlobals();
+ List imports = existingPackage.getImports();
+
+ // First update the binary files
+ // @todo: this probably has issues if you add classes in the incorrect
+ // order - functions, rules, invokers.
+ PackageCompilationData compilationData = existingPackage
+ .getPackageCompilationData();
+ PackageCompilationData newCompilationData = newPackage
+ .getPackageCompilationData();
+ String[] files = newCompilationData.list();
+ for (int i = 0, length = files.length; i < length; i++) {
+ compilationData.write(files[i], newCompilationData.read(files[i]));
+ }
- this.rulesPackages.add( rulesPackage );
+ // Merge imports
+ imports.addAll(newPackage.getImports());
- Rule[] rules = rulesPackage.getRules();
+ // Add invokers
+ compilationData.putAllInvokers(newCompilationData.getInvokers());
- for ( int i = 0, length = rules.length; i < length; ++i ) {
- addRule( rules[i] );
+ // Add globals
+ for (Iterator it = globals.keySet().iterator(); it.hasNext();) {
+ String identifier = (String) it.next();
+ Class type = (Class) globals.get(identifier);
+ if (globals.containsKey(identifier)
+ && !globals.get(identifier).equals(type)) {
+ throw new PackageIntegrationException(
+ "Unable to merge new Package", newPackage);
+ }
}
}
@@ -209,23 +240,35 @@ public void addPackage(Package rulesPackage) throws PackageIntegrationException
* @throws InvalidPatternException
*/
public void addRule(Rule rule) throws FactException,
- InvalidPatternException {
- if ( !rule.isValid() ) {
- throw new IllegalArgumentException( "The rule called " + rule.getName() + " is not valid. Check for compile errors reported." );
+ InvalidPatternException {
+ if (!rule.isValid()) {
+ throw new IllegalArgumentException("The rule called "
+ + rule.getName()
+ + " is not valid. Check for compile errors reported.");
}
- List rules = Builder.processRule( rule );
+ List rules = Builder.processRule(rule);
- this.leapsRules.put( rule,
- rules );
+ this.leapsRules.put(rule, rules);
+
+ for (Iterator it = this.workingMemories.keySet().iterator(); it
+ .hasNext();) {
+ ((WorkingMemoryImpl) it.next()).addLeapsRules(rules);
+ }
- for ( Iterator it = this.workingMemories.keySet().iterator(); it.hasNext(); ) {
- ((WorkingMemoryImpl) it.next()).addLeapsRules( rules );
+ // Iterate each workingMemory and attempt to fire any rules, that were
+ // activated as a result of the new rule addition
+ for (Iterator it = this.workingMemories.keySet().iterator(); it
+ .hasNext();) {
+ WorkingMemoryImpl workingMemory = (WorkingMemoryImpl) it.next();
+ workingMemory.fireAllRules();
}
}
public void removeRule(Rule rule) {
- for ( Iterator it = this.workingMemories.keySet().iterator(); it.hasNext(); ) {
- ((WorkingMemoryImpl) it.next()).removeRule( (List) this.leapsRules.remove( rule ) );
+ for (Iterator it = this.workingMemories.keySet().iterator(); it
+ .hasNext();) {
+ ((WorkingMemoryImpl) it.next()).removeRule((List) this.leapsRules
+ .remove(rule));
}
}
diff --git a/drools-core/src/main/java/org/drools/leaps/Token.java b/drools-core/src/main/java/org/drools/leaps/Token.java
index 8463bc452ef..8ec2ad3e140 100644
--- a/drools-core/src/main/java/org/drools/leaps/Token.java
+++ b/drools-core/src/main/java/org/drools/leaps/Token.java
@@ -34,40 +34,43 @@
* @author Alexander Bagerman
*
*/
-class Token
- implements
- Tuple,
- Serializable {
+class Token implements Tuple, Serializable {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- private WorkingMemoryImpl workingMemory;
+ private WorkingMemoryImpl workingMemory;
private final FactHandleImpl dominantFactHandle;
- private RuleHandle currentRuleHandle = null;
+ private RuleHandle currentRuleHandle = null;
- private FactHandleImpl[] currentFactHandles = new FactHandleImpl[0];
+ private FactHandleImpl[] currentFactHandles = new FactHandleImpl[0];
- boolean resume = false;
+ boolean resume = false;
- private Iterator rules = null;
+ private Iterator rules = null;
+
+ private final PropagationContextImpl propagationContext;
/**
- * agendaItem parts
+ *
*/
- public Token(WorkingMemoryImpl workingMemory,
- FactHandleImpl factHandle) {
+ public Token(WorkingMemoryImpl workingMemory, FactHandleImpl factHandle,
+ PropagationContextImpl propagationContext) {
this.workingMemory = workingMemory;
this.dominantFactHandle = factHandle;
+ this.propagationContext = propagationContext;
}
private Iterator rulesIterator() {
- if ( this.rules == null ) {
- if ( this.dominantFactHandle != null ) {
- this.rules = this.workingMemory.getFactTable( this.dominantFactHandle.getObject().getClass() ).getRulesIterator();
+ if (this.rules == null) {
+ if (this.dominantFactHandle != null) {
+ this.rules = this.workingMemory.getFactTable(
+ this.dominantFactHandle.getObject().getClass())
+ .getRulesIterator();
} else {
- this.rules = this.workingMemory.getNoRequiredColumnsLeapsRules();
+ this.rules = this.workingMemory
+ .getNoRequiredColumnsLeapsRules();
}
}
return this.rules;
@@ -75,7 +78,8 @@ private Iterator rulesIterator() {
public RuleHandle nextRuleHandle() {
this.currentRuleHandle = (RuleHandle) this.rules.next();
- this.currentFactHandles = new FactHandleImpl[this.currentRuleHandle.getLeapsRule().getNumberOfColumns()];
+ this.currentFactHandles = new FactHandleImpl[this.currentRuleHandle
+ .getLeapsRule().getNumberOfColumns()];
return this.currentRuleHandle;
}
@@ -87,19 +91,21 @@ public RuleHandle nextRuleHandle() {
public boolean hasNextRuleHandle() {
boolean ret = false;
- if ( this.rulesIterator() != null ) {
+ if (this.rulesIterator() != null) {
// starting with calling rulesIterator() to make sure that we picks
// rules because fact can be asserted before rules added
long levelId = this.workingMemory.getIdLastFireAllAt();
- if ( this.dominantFactHandle == null || this.dominantFactHandle.getId() >= levelId ) {
+ if (this.dominantFactHandle == null
+ || this.dominantFactHandle.getId() >= levelId) {
ret = this.rules.hasNext();
} else {
// then we need to skip rules that have id lower than
// workingMemory.idLastFireAllAt
boolean done = false;
- while ( !done ) {
- if ( this.rules.hasNext() ) {
- if ( ((RuleHandle) ((TableIterator) this.rules).peekNext()).getId() > levelId ) {
+ while (!done) {
+ if (this.rules.hasNext()) {
+ if (((RuleHandle) ((TableIterator) this.rules)
+ .peekNext()).getId() > levelId) {
ret = true;
done = true;
} else {
@@ -116,15 +122,14 @@ public boolean hasNextRuleHandle() {
}
public int hashCode() {
- if ( this.dominantFactHandle != null ) {
+ if (this.dominantFactHandle != null) {
return this.dominantFactHandle.hashCode();
} else {
return 0;
}
}
- public void set(int idx,
- FactHandleImpl factHandle) {
+ public void set(int idx, FactHandleImpl factHandle) {
this.currentFactHandles[idx] = factHandle;
}
@@ -150,11 +155,14 @@ public void setResume(boolean resume) {
* @see Object
*/
public boolean equals(Object that) {
- if ( this == that ) return true;
- if ( !(that instanceof Token) ) return false;
- if ( this.dominantFactHandle != null ) {
- if ( ((Token) that).dominantFactHandle != null ) {
- return this.dominantFactHandle.getId() == ((Token) that).dominantFactHandle.getId();
+ if (this == that)
+ return true;
+ if (!(that instanceof Token))
+ return false;
+ if (this.dominantFactHandle != null) {
+ if (((Token) that).dominantFactHandle != null) {
+ return this.dominantFactHandle.getId() == ((Token) that).dominantFactHandle
+ .getId();
} else {
return false;
}
@@ -178,7 +186,7 @@ public FactHandle get(int idx) {
* @see org.drools.spi.Tuple
*/
public FactHandle get(Declaration declaration) {
- return this.get( declaration.getColumn() );
+ return this.get(declaration.getColumn());
}
/**
@@ -202,10 +210,14 @@ public WorkingMemory getWorkingMemory() {
* @see java.lang.Object
*/
public String toString() {
- String ret = "TOKEN [" + this.dominantFactHandle + "]\n" + "\tRULE : " + this.currentRuleHandle + "\n";
- if ( this.currentFactHandles != null ) {
- for ( int i = 0, length = this.currentFactHandles.length; i < length; i++ ) {
- ret = ret + ((i == this.currentRuleHandle.getDominantPosition()) ? "***" : "") + "\t" + i + " -> " + this.currentFactHandles[i].getObject() + "\n";
+ String ret = "TOKEN [" + this.dominantFactHandle + "]\n" + "\tRULE : "
+ + this.currentRuleHandle + "\n";
+ if (this.currentFactHandles != null) {
+ for (int i = 0, length = this.currentFactHandles.length; i < length; i++) {
+ ret = ret
+ + ((i == this.currentRuleHandle.getDominantPosition()) ? "***"
+ : "") + "\t" + i + " -> "
+ + this.currentFactHandles[i].getObject() + "\n";
}
}
return ret;
@@ -216,10 +228,9 @@ public String toString() {
*
* @return LeapsTuple
*/
- LeapsTuple getTuple(PropagationContextImpl context) {
- return new LeapsTuple( this.currentFactHandles,
- this.currentRuleHandle.getLeapsRule(),
- context );
+ LeapsTuple getTuple() {
+ return new LeapsTuple(this.currentFactHandles, this.currentRuleHandle
+ .getLeapsRule(), this.propagationContext);
}
/**
@@ -232,8 +243,8 @@ LeapsTuple getTuple(PropagationContextImpl context) {
* object, otherwise <code>false</code>.
*/
public boolean dependsOn(FactHandle handle) {
- for ( int i = 0, length = this.currentFactHandles.length; i < length; i++ ) {
- if ( this.currentFactHandles[i].equals( handle ) ) {
+ for (int i = 0, length = this.currentFactHandles.length; i < length; i++) {
+ if (this.currentFactHandles[i].equals(handle)) {
return true;
}
}
@@ -250,4 +261,8 @@ public boolean dependsOn(FactHandle handle) {
public void setActivation(Activation activation) {
// do nothing
}
+
+ public PropagationContextImpl getPropagationContext() {
+ return propagationContext;
+ }
}
diff --git a/drools-core/src/main/java/org/drools/leaps/TokenEvaluator.java b/drools-core/src/main/java/org/drools/leaps/TokenEvaluator.java
index acc7bcd1c2e..8b21b712ee7 100644
--- a/drools-core/src/main/java/org/drools/leaps/TokenEvaluator.java
+++ b/drools-core/src/main/java/org/drools/leaps/TokenEvaluator.java
@@ -16,13 +16,10 @@
* limitations under the License.
*/
-import org.drools.common.PropagationContextImpl;
import org.drools.leaps.util.Table;
import org.drools.leaps.util.TableIterator;
import org.drools.rule.EvalCondition;
import org.drools.rule.InvalidRuleException;
-import org.drools.spi.Activation;
-import org.drools.spi.PropagationContext;
/**
* helper class that does condition evaluation on token when working memory does
@@ -41,32 +38,51 @@ final class TokenEvaluator {
* @throws Exception
* @throws InvalidRuleException
*/
- final static protected void evaluate(Token token) throws NoMatchesFoundException,
- Exception,
- InvalidRuleException {
- WorkingMemoryImpl workingMemory = (WorkingMemoryImpl) token.getWorkingMemory();
+ final static protected void evaluate(Token token)
+ throws NoMatchesFoundException, InvalidRuleException {
+ WorkingMemoryImpl workingMemory = (WorkingMemoryImpl) token
+ .getWorkingMemory();
LeapsRule leapsRule = token.getCurrentRuleHandle().getLeapsRule();
// sometimes there is no normal conditions, only not and exists
int numberOfColumns = leapsRule.getNumberOfColumns();
- if ( numberOfColumns > 0 ) {
- int dominantFactPosition = token.getCurrentRuleHandle().getDominantPosition();
- if ( leapsRule.getColumnConstraintsAtPosition( dominantFactPosition ).isAllowedAlpha( token.getDominantFactHandle(),
- token,
- workingMemory ) ) {
+ if (numberOfColumns > 0) {
+ int dominantFactPosition = token.getCurrentRuleHandle()
+ .getDominantPosition();
+ if (leapsRule.getColumnConstraintsAtPosition(dominantFactPosition)
+ .isAllowedAlpha(token.getDominantFactHandle(), token,
+ workingMemory)) {
TableIterator[] iterators = new TableIterator[numberOfColumns];
// getting iterators first
- for ( int i = 0; i < numberOfColumns; i++ ) {
- if ( i == dominantFactPosition ) {
- iterators[i] = Table.singleItemIterator( token.getDominantFactHandle() );
+ for (int i = 0; i < numberOfColumns; i++) {
+ if (i == dominantFactPosition) {
+ iterators[i] = Table.singleItemIterator(token
+ .getDominantFactHandle());
} else {
- if ( i > 0 && leapsRule.getColumnConstraintsAtPosition( i ).isAlphaPresent() ) {
- iterators[i] = workingMemory.getFactTable( leapsRule.getColumnClassObjectTypeAtPosition( i ) ).tailConstrainedIterator( workingMemory,
- leapsRule.getColumnConstraintsAtPosition( i ),
- token.getDominantFactHandle(),
- (token.isResume() ? token.get( i ) : token.getDominantFactHandle()) );
+ if (i > 0
+ && leapsRule.getColumnConstraintsAtPosition(i)
+ .isAlphaPresent()) {
+ iterators[i] = workingMemory
+ .getFactTable(
+ leapsRule
+ .getColumnClassObjectTypeAtPosition(i))
+ .tailConstrainedIterator(
+ workingMemory,
+ leapsRule
+ .getColumnConstraintsAtPosition(i),
+ token.getDominantFactHandle(),
+ (token.isResume() ? token.get(i)
+ : token
+ .getDominantFactHandle()));
} else {
- iterators[i] = workingMemory.getFactTable( leapsRule.getColumnClassObjectTypeAtPosition( i ) ).tailIterator( token.getDominantFactHandle(),
- (token.isResume() ? token.get( i ) : token.getDominantFactHandle()) );
+ iterators[i] = workingMemory
+ .getFactTable(
+ leapsRule
+ .getColumnClassObjectTypeAtPosition(i))
+ .tailIterator(
+ token.getDominantFactHandle(),
+ (token.isResume() ? token.get(i)
+ : token
+ .getDominantFactHandle()));
}
}
}
@@ -78,13 +94,16 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException
boolean doReset = false;
boolean skip = token.isResume();
TableIterator currentIterator;
- for ( int i = 0; i < numberOfColumns && !someIteratorsEmpty; i++ ) {
+ for (int i = 0; i < numberOfColumns && !someIteratorsEmpty; i++) {
currentIterator = iterators[i];
- if ( currentIterator.isEmpty() ) {
+ if (currentIterator.isEmpty()) {
someIteratorsEmpty = true;
} else {
- if ( !doReset ) {
- if ( skip && currentIterator.hasNext() && !currentIterator.peekNext().equals( token.get( i ) ) ) {
+ if (!doReset) {
+ if (skip
+ && currentIterator.hasNext()
+ && !currentIterator.peekNext().equals(
+ token.get(i))) {
skip = false;
doReset = true;
}
@@ -95,7 +114,7 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException
}
// check if one of them is empty and immediate return
- if ( someIteratorsEmpty ) {
+ if (someIteratorsEmpty) {
throw new NoMatchesFoundException();
// "some of tables do not have facts");
}
@@ -103,49 +122,48 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException
// column position in the nested loop
int jj = 0;
boolean done = false;
- while ( !done ) {
+ while (!done) {
currentIterator = iterators[jj];
- if ( !currentIterator.hasNext() ) {
- if ( jj == 0 ) {
+ if (!currentIterator.hasNext()) {
+ if (jj == 0) {
done = true;
} else {
//
currentIterator.reset();
- token.set( jj,
- (FactHandleImpl) null );
+ token.set(jj, (FactHandleImpl) null);
jj = jj - 1;
- if ( skip ) {
+ if (skip) {
skip = false;
}
}
} else {
currentIterator.next();
- token.set( jj,
- (FactHandleImpl) iterators[jj].current() );
+ token.set(jj, (FactHandleImpl) iterators[jj].current());
// check if match found
// we need to check only beta for dominant fact
// alpha was already checked
boolean localMatch = false;
- if ( jj == 0 && jj != dominantFactPosition ) {
- localMatch = leapsRule.getColumnConstraintsAtPosition( jj ).isAllowed( token.get( jj ),
- token,
- workingMemory );
+ if (jj == 0 && jj != dominantFactPosition) {
+ localMatch = leapsRule
+ .getColumnConstraintsAtPosition(jj)
+ .isAllowed(token.get(jj), token,
+ workingMemory);
} else {
- localMatch = leapsRule.getColumnConstraintsAtPosition( jj ).isAllowedBeta( token.get( jj ),
- token,
- workingMemory );
+ localMatch = leapsRule
+ .getColumnConstraintsAtPosition(jj)
+ .isAllowedBeta(token.get(jj), token,
+ workingMemory);
}
- if ( localMatch ) {
+ if (localMatch) {
// start iteratating next iterator
// or for the last one check negative conditions and
// fire
// consequence
- if ( jj == (numberOfColumns - 1) ) {
- if ( !skip ) {
- if ( processAfterAllPositiveConstraintOk( token,
- leapsRule,
- workingMemory ) ) {
+ if (jj == (numberOfColumns - 1)) {
+ if (!skip) {
+ if (processAfterAllPositiveConstraintOk(
+ token, leapsRule, workingMemory)) {
return;
}
} else {
@@ -155,7 +173,7 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException
jj = jj + 1;
}
} else {
- if ( skip ) {
+ if (skip) {
skip = false;
}
}
@@ -163,9 +181,8 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException
}
}
} else {
- if ( processAfterAllPositiveConstraintOk( token,
- leapsRule,
- workingMemory ) ) {
+ if (processAfterAllPositiveConstraintOk(token, leapsRule,
+ workingMemory)) {
return;
}
}
@@ -174,8 +191,8 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException
}
/**
- * Makes final check on eval, exists and not conditions after all column values
- * isAllowed by column constraints
+ * Makes final check on eval, exists and not conditions after all column
+ * values isAllowed by column constraints
*
* @param token
* @param leapsRule
@@ -184,39 +201,32 @@ final static protected void evaluate(Token token) throws NoMatchesFoundException
* @throws Exception
*/
final static boolean processAfterAllPositiveConstraintOk(Token token,
- LeapsRule leapsRule,
- WorkingMemoryImpl workingMemory) throws Exception {
- LeapsTuple tuple = token.getTuple( new PropagationContextImpl( workingMemory.increamentPropagationIdCounter(),
- PropagationContext.ASSERTION,
- leapsRule.getRule(),
- (Activation) null ) );
- if ( leapsRule.containsEvalConditions() ) {
- if ( !TokenEvaluator.evaluateEvalConditions( leapsRule,
- tuple,
- workingMemory ) ) {
+ LeapsRule leapsRule, WorkingMemoryImpl workingMemory) {
+ LeapsTuple tuple = token.getTuple();
+ if (leapsRule.containsEvalConditions()) {
+ if (!TokenEvaluator.evaluateEvalConditions(leapsRule, tuple,
+ workingMemory)) {
return false;
}
}
- if ( leapsRule.containsExistsColumns() ) {
- TokenEvaluator.evaluateExistsConditions( tuple,
- leapsRule,
- workingMemory );
+ if (leapsRule.containsExistsColumns()) {
+ TokenEvaluator.evaluateExistsConditions(tuple, leapsRule,
+ workingMemory);
}
- if ( leapsRule.containsNotColumns() ) {
- TokenEvaluator.evaluateNotConditions( tuple,
- leapsRule,
- workingMemory );
+ if (leapsRule.containsNotColumns()) {
+ TokenEvaluator.evaluateNotConditions(tuple, leapsRule,
+ workingMemory);
}
//
Class[] classes = leapsRule.getExistsNotColumnsClasses();
- for ( int i = 0, length = classes.length; i < length; i++ ) {
- workingMemory.getFactTable( classes[i] ).addTuple( tuple );
+ for (int i = 0, length = classes.length; i < length; i++) {
+ workingMemory.getFactTable(classes[i]).addTuple(tuple);
}
//
- if ( tuple.isReadyForActivation() ) {
+ if (tuple.isReadyForActivation()) {
// let agenda to do its work
- workingMemory.assertTuple( tuple );
+ workingMemory.assertTuple(tuple);
return true;
} else {
return false;
@@ -233,12 +243,10 @@ final static boolean processAfterAllPositiveConstraintOk(Token token,
* @throws Exception
*/
final static boolean evaluateEvalConditions(LeapsRule leapsRule,
- LeapsTuple tuple,
- WorkingMemoryImpl workingMemory) throws Exception {
+ LeapsTuple tuple, WorkingMemoryImpl workingMemory) {
EvalCondition[] evals = leapsRule.getEvalConditions();
- for ( int i = 0; i < evals.length; i++ ) {
- if ( !evals[i].isAllowed( tuple,
- workingMemory ) ) {
+ for (int i = 0; i < evals.length; i++) {
+ if (!evals[i].isAllowed(tuple, workingMemory)) {
return false;
}
}
@@ -254,28 +262,24 @@ final static boolean evaluateEvalConditions(LeapsRule leapsRule,
* @return success
* @throws Exception
*/
- final static void evaluateNotConditions(LeapsTuple tuple,
- LeapsRule rule,
- WorkingMemoryImpl workingMemory) throws Exception {
+ final static void evaluateNotConditions(LeapsTuple tuple, LeapsRule rule,
+ WorkingMemoryImpl workingMemory) {
FactHandleImpl factHandle;
TableIterator tableIterator;
ColumnConstraints constraint;
ColumnConstraints[] not = rule.getNotColumnConstraints();
- for ( int i = 0, length = not.length; i < length; i++ ) {
+ for (int i = 0, length = not.length; i < length; i++) {
constraint = not[i];
// scan the whole table
- tableIterator = workingMemory.getFactTable( constraint.getClassType() ).iterator();
+ tableIterator = workingMemory.getFactTable(
+ constraint.getClassType()).iterator();
// fails if exists
- while ( tableIterator.hasNext() ) {
+ while (tableIterator.hasNext()) {
factHandle = (FactHandleImpl) tableIterator.next();
// check constraint condition
- if ( constraint.isAllowed( factHandle,
- tuple,
- workingMemory ) ) {
- tuple.addNotFactHandle( factHandle,
- i );
- factHandle.addNotTuple( tuple,
- i );
+ if (constraint.isAllowed(factHandle, tuple, workingMemory)) {
+ tuple.addNotFactHandle(factHandle, i);
+ factHandle.addNotTuple(tuple, i);
}
}
}
@@ -289,27 +293,23 @@ final static void evaluateNotConditions(LeapsTuple tuple,
* @throws Exception
*/
final static void evaluateExistsConditions(LeapsTuple tuple,
- LeapsRule rule,
- WorkingMemoryImpl workingMemory) throws Exception {
+ LeapsRule rule, WorkingMemoryImpl workingMemory) {
FactHandleImpl factHandle;
TableIterator tableIterator;
ColumnConstraints constraint;
ColumnConstraints[] exists = rule.getExistsColumnConstraints();
- for ( int i = 0, length = exists.length; i < length; i++ ) {
+ for (int i = 0, length = exists.length; i < length; i++) {
constraint = exists[i];
// scan the whole table
- tableIterator = workingMemory.getFactTable( constraint.getClassType() ).iterator();
+ tableIterator = workingMemory.getFactTable(
+ constraint.getClassType()).iterator();
// fails if exists
- while ( tableIterator.hasNext() ) {
+ while (tableIterator.hasNext()) {
factHandle = (FactHandleImpl) tableIterator.next();
// check constraint conditions
- if ( constraint.isAllowed( factHandle,
- tuple,
- workingMemory ) ) {
- tuple.addExistsFactHandle( factHandle,
- i );
- factHandle.addExistsTuple( tuple,
- i );
+ if (constraint.isAllowed(factHandle, tuple, workingMemory)) {
+ tuple.addExistsFactHandle(factHandle, i);
+ factHandle.addExistsTuple(tuple, i);
}
}
}
diff --git a/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java b/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java
index 45916837a0e..b6beacc973d 100644
--- a/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java
+++ b/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java
@@ -62,20 +62,19 @@
* @see java.io.Serializable
*
*/
-class WorkingMemoryImpl extends AbstractWorkingMemory
- implements
- EventSupport,
- PropertyChangeListener {
- private static final long serialVersionUID = -2524904474925421759L;
+class WorkingMemoryImpl extends AbstractWorkingMemory implements EventSupport,
+ PropertyChangeListener {
+ private static final long serialVersionUID = -2524904474925421759L;
- protected final Agenda agenda;
+ protected final Agenda agenda;
- private final Map queryResults;
+ private final Map queryResults;
// rules consisting only of not and exists
- private final RuleTable noRequiredColumnsLeapsRules = new RuleTable( DefaultConflictResolver.getInstance().getRuleConflictResolver() );
+ private final RuleTable noRequiredColumnsLeapsRules = new RuleTable(
+ DefaultConflictResolver.getInstance().getRuleConflictResolver());
- private final IdentityMap leapsRulesToHandlesMap = new IdentityMap();
+ private final IdentityMap leapsRulesToHandlesMap = new IdentityMap();
/**
* Construct.
@@ -84,13 +83,17 @@ class WorkingMemoryImpl extends AbstractWorkingMemory
* The backing rule-base.
*/
public WorkingMemoryImpl(RuleBaseImpl ruleBase) {
- super( ruleBase,
- ruleBase.newFactHandleFactory() );
- this.agenda = new LeapsAgenda( this );
+ super(ruleBase, ruleBase.newFactHandleFactory());
+ this.agenda = new LeapsAgenda(this);
+ this.agenda.setFocus(AgendaGroup.MAIN);
+ //
this.queryResults = new HashMap();
// to pick up rules that do not require columns, only not and exists
- this.pushTokenOnStack( new Token( this,
- null ) );
+ PropagationContextImpl context = new PropagationContextImpl(
+ nextPropagationIdCounter(), PropagationContext.ASSERTION, null,
+ null);
+
+ this.pushTokenOnStack(new Token(this, null, context));
}
/**
@@ -99,25 +102,26 @@ public WorkingMemoryImpl(RuleBaseImpl ruleBase) {
* @return The new fact handle.
*/
FactHandle newFactHandle(Object object) {
- return ((HandleFactory) this.handleFactory).newFactHandle( object );
+ return ((HandleFactory) this.handleFactory).newFactHandle(object);
}
/**
* @see WorkingMemory
*/
- public void setGlobal(String name,
- Object value) {
+ public void setGlobal(String name, Object value) {
// Make sure the application data has been declared in the RuleBase
- Map applicationDataDefintions = ((RuleBaseImpl) this.ruleBase).getApplicationData();
- Class type = (Class) applicationDataDefintions.get( name );
- if ( (type == null) ) {
- throw new RuntimeException( "Unexpected application data [" + name + "]" );
- } else if ( !type.isInstance( value ) ) {
- throw new RuntimeException( "Illegal class for application data. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." );
+ Map applicationDataDefintions = ((RuleBaseImpl) this.ruleBase)
+ .getGlobalDeclarations();
+ Class type = (Class) applicationDataDefintions.get(name);
+ if ((type == null)) {
+ throw new RuntimeException("Unexpected global [" + name + "]");
+ } else if (!type.isInstance(value)) {
+ throw new RuntimeException("Illegal class for global. "
+ + "Expected [" + type.getName() + "], " + "found ["
+ + value.getClass().getName() + "].");
} else {
- this.applicationData.put( name,
- value );
+ this.getGlobals().put(name, value);
}
}
@@ -143,8 +147,9 @@ public Object getObject(FactHandle handle) {
public List getObjects(Class objectClass) {
List list = new LinkedList();
- for ( Iterator it = this.getFactTable( objectClass ).iterator(); it.hasNext(); ) {
- list.add( it.next() );
+ for (Iterator it = this.getFactTable(objectClass).iterator(); it
+ .hasNext();) {
+ list.add(it.next());
}
return list;
@@ -162,40 +167,26 @@ public boolean containsObject(FactHandle handle) {
* @see WorkingMemory
*/
public FactHandle assertObject(Object object) throws FactException {
- return assertObject( object, /* Not-Dynamic */
- false,
- false,
- null,
- null );
+ return assertObject(object, /* Not-Dynamic */
+ false, false, null, null);
}
/**
* @see WorkingMemory
*/
public FactHandle assertLogicalObject(Object object) throws FactException {
- return assertObject( object, /* Not-Dynamic */
- false,
- true,
- null,
- null );
+ return assertObject(object, /* Not-Dynamic */
+ false, true, null, null);
}
- public FactHandle assertObject(Object object,
- boolean dynamic) throws FactException {
- return assertObject( object,
- dynamic,
- false,
- null,
- null );
+ public FactHandle assertObject(Object object, boolean dynamic)
+ throws FactException {
+ return assertObject(object, dynamic, false, null, null);
}
- public FactHandle assertLogicalObject(Object object,
- boolean dynamic) throws FactException {
- return assertObject( object,
- dynamic,
- true,
- null,
- null );
+ public FactHandle assertLogicalObject(Object object, boolean dynamic)
+ throws FactException {
+ return assertObject(object, dynamic, true, null, null);
}
/**
@@ -210,69 +201,64 @@ public FactHandle assertLogicalObject(Object object,
*
* @see WorkingMemory
*/
- public FactHandle assertObject(Object object,
- boolean dynamic,
- boolean logical,
- Rule rule,
- Activation activation) throws FactException {
+ public FactHandle assertObject(Object object, boolean dynamic,
+ boolean logical, Rule rule, Activation activation)
+ throws FactException {
// check if the object already exists in the WM
- FactHandleImpl handle = (FactHandleImpl) this.identityMap.get( object );
+ FactHandleImpl handle = (FactHandleImpl) this.identityMap.get(object);
// return if the handle exists and this is a logical assertion
- if ( (handle != null) && (logical) ) {
+ if ((handle != null) && (logical)) {
return handle;
}
// lets see if the object is already logical asserted
- Object logicalState = this.equalsMap.get( object );
+ Object logicalState = this.equalsMap.get(object);
// if we have a handle and this STATED fact was previously STATED
- if ( (handle != null) && (!logical) && logicalState == AbstractWorkingMemory.STATED ) {
+ if ((handle != null) && (!logical)
+ && logicalState == AbstractWorkingMemory.STATED) {
return handle;
}
- if ( !logical ) {
+ if (!logical) {
// If this stated assertion already has justifications then we need
// to cancel them
- if ( logicalState instanceof FactHandleImpl ) {
+ if (logicalState instanceof FactHandleImpl) {
handle = (FactHandleImpl) logicalState;
handle.removeAllLogicalDependencies();
} else {
- handle = (FactHandleImpl) newFactHandle( object );
+ handle = (FactHandleImpl) newFactHandle(object);
}
- putObject( handle,
- object );
+ putObject(handle, object);
- this.equalsMap.put( object,
- AbstractWorkingMemory.STATED );
+ this.equalsMap.put(object, AbstractWorkingMemory.STATED);
- if ( dynamic ) {
- addPropertyChangeListener( object );
+ if (dynamic) {
+ addPropertyChangeListener(object);
}
} else {
// This object is already STATED, we cannot make it justifieable
- if ( logicalState == AbstractWorkingMemory.STATED ) {
+ if (logicalState == AbstractWorkingMemory.STATED) {
return null;
}
handle = (FactHandleImpl) logicalState;
// we create a lookup handle for the first asserted equals object
// all future equals objects will use that handle
- if ( handle == null ) {
- handle = (FactHandleImpl) newFactHandle( object );
+ if (handle == null) {
+ handle = (FactHandleImpl) newFactHandle(object);
- putObject( handle,
- object );
+ putObject(handle, object);
- this.equalsMap.put( object,
- handle );
+ this.equalsMap.put(object, handle);
}
// adding logical dependency
LeapsTuple tuple = (LeapsTuple) activation.getTuple();
- tuple.addLogicalDependency( handle );
- handle.addLogicalDependency( tuple );
+ tuple.addLogicalDependency(handle);
+ handle.addLogicalDependency(tuple);
}
// leaps handle already has object attached
@@ -288,66 +274,64 @@ public FactHandle assertObject(Object object,
LeapsTuple tuple;
LeapsRule leapsRule;
Class objectClass = object.getClass();
- for ( Iterator tables = this.getFactTablesList( objectClass ).iterator(); tables.hasNext(); ) {
+ for (Iterator tables = this.getFactTablesList(objectClass).iterator(); tables
+ .hasNext();) {
FactTable factTable = (FactTable) tables.next();
// adding fact to container
- factTable.add( handle );
- // inspect all tuples for exists and not conditions and activate / deactivate
+ factTable.add(handle);
+ // inspect all tuples for exists and not conditions and activate /
+ // deactivate
// agenda items
ColumnConstraints constraint;
ColumnConstraints[] constraints;
- for ( Iterator tuples = factTable.getTuplesIterator(); tuples.hasNext(); ) {
+ for (Iterator tuples = factTable.getTuplesIterator(); tuples
+ .hasNext();) {
tuple = (LeapsTuple) tuples.next();
leapsRule = tuple.getLeapsRule();
// check not constraints
constraints = leapsRule.getNotColumnConstraints();
- for ( int i = 0, length = constraints.length; i < length; i++ ) {
+ for (int i = 0, length = constraints.length; i < length; i++) {
constraint = constraints[i];
- if ( objectClass.isAssignableFrom( constraint.getClassType() ) && constraint.isAllowed( handle,
- tuple,
- this ) ) {
- tuple.addNotFactHandle( handle,
- i );
- handle.addNotTuple( tuple,
- i );
+ if (objectClass.isAssignableFrom(constraint.getClassType())
+ && constraint.isAllowed(handle, tuple, this)) {
+ tuple.addNotFactHandle(handle, i);
+ handle.addNotTuple(tuple, i);
}
}
// check exists constraints
constraints = leapsRule.getExistsColumnConstraints();
- for ( int i = 0, length = constraints.length; i < length; i++ ) {
+ for (int i = 0, length = constraints.length; i < length; i++) {
constraint = constraints[i];
- if ( objectClass.isAssignableFrom( constraint.getClassType() ) && constraint.isAllowed( handle,
- tuple,
- this ) ) {
- tuple.addExistsFactHandle( handle,
- i );
- handle.addExistsTuple( tuple,
- i );
+ if (objectClass.isAssignableFrom(constraint.getClassType())
+ && constraint.isAllowed(handle, tuple, this)) {
+ tuple.addExistsFactHandle(handle, i);
+ handle.addExistsTuple(tuple, i);
}
}
// check and see if we need deactivate / activate
- if ( tuple.isReadyForActivation() && tuple.isActivationNull() ) {
+ if (tuple.isReadyForActivation() && tuple.isActivationNull()) {
// ready to activate
- this.assertTuple( tuple );
+ this.assertTuple(tuple);
// remove tuple from fact table
tuples.remove();
- } else if ( !tuple.isReadyForActivation() && !tuple.isActivationNull() ) {
+ } else if (!tuple.isReadyForActivation()
+ && !tuple.isActivationNull()) {
// time to pull from agenda
- this.invalidateActivation( tuple );
+ this.invalidateActivation(tuple);
}
}
}
// new leaps stack token
- this.pushTokenOnStack( new Token( this,
- handle ) );
-
- this.workingMemoryEventSupport.fireObjectAsserted( new PropagationContextImpl( ++this.propagationIdCounter,
- PropagationContext.ASSERTION,
- rule,
- activation ),
- handle,
- object );
+ PropagationContextImpl context = new PropagationContextImpl(
+ nextPropagationIdCounter(), PropagationContext.ASSERTION, rule,
+ activation);
+
+ this.pushTokenOnStack(new Token(this, handle, context));
+
+ this.workingMemoryEventSupport.fireObjectAsserted(context, handle,
+ object);
+
return handle;
}
@@ -359,66 +343,63 @@ public FactHandle assertObject(Object object,
* @param object
* The object.
*/
- Object putObject(FactHandle handle,
- Object object) {
+ Object putObject(FactHandle handle, Object object) {
- this.identityMap.put( object,
- handle );
+ this.identityMap.put(object, handle);
- return this.objects.put( ((FactHandleImpl) handle).getId(),
- object );
+ return this.objects.put(((FactHandleImpl) handle).getId(), object);
}
Object removeObject(FactHandle handle) {
- this.identityMap.remove( ((FactHandleImpl) handle).getObject() );
+ this.identityMap.remove(((FactHandleImpl) handle).getObject());
- return this.objects.remove( ((FactHandleImpl) handle).getId() );
+ return this.objects.remove(((FactHandleImpl) handle).getId());
}
/**
* @see WorkingMemory
*/
- public void retractObject(FactHandle handle,
- boolean removeLogical,
- boolean updateEqualsMap,
- Rule rule,
- Activation activation) throws FactException {
+ public void retractObject(FactHandle handle, boolean removeLogical,
+ boolean updateEqualsMap, Rule rule, Activation activation)
+ throws FactException {
//
- removePropertyChangeListener( handle );
+ removePropertyChangeListener(handle);
/*
* leaps specific actions
*/
// remove fact from all relevant fact tables container
- for ( Iterator it = this.getFactTablesList( ((FactHandleImpl) handle).getObject().getClass() ).iterator(); it.hasNext(); ) {
- ((FactTable) it.next()).remove( handle );
+ for (Iterator it = this.getFactTablesList(
+ ((FactHandleImpl) handle).getObject().getClass()).iterator(); it
+ .hasNext();) {
+ ((FactTable) it.next()).remove(handle);
}
// 0. remove activated tuples
Iterator tuples = ((FactHandleImpl) handle).getActivatedTuples();
- for ( ; tuples != null && tuples.hasNext(); ) {
- this.invalidateActivation( (LeapsTuple) tuples.next() );
+ for (; tuples != null && tuples.hasNext();) {
+ this.invalidateActivation((LeapsTuple) tuples.next());
}
// 1. remove fact for nots and exists tuples
FactHandleTupleAssembly assembly;
Iterator it;
it = ((FactHandleImpl) handle).getNotTuples();
- if ( it != null ) {
- for ( ; it.hasNext(); ) {
+ if (it != null) {
+ for (; it.hasNext();) {
assembly = (FactHandleTupleAssembly) it.next();
- assembly.getTuple().removeNotFactHandle( handle,
- assembly.getIndex() );
+ assembly.getTuple().removeNotFactHandle(handle,
+ assembly.getIndex());
}
}
it = ((FactHandleImpl) handle).getExistsTuples();
- if ( it != null ) {
- for ( ; it.hasNext(); ) {
+ if (it != null) {
+ for (; it.hasNext();) {
assembly = (FactHandleTupleAssembly) it.next();
- assembly.getTuple().removeExistsFactHandle( handle,
- assembly.getIndex() );
+ assembly.getTuple().removeExistsFactHandle(handle,
+ assembly.getIndex());
}
}
// 2. assert all tuples that are ready for activation or cancel ones
@@ -426,76 +407,73 @@ public void retractObject(FactHandle handle,
LeapsTuple tuple;
IteratorChain chain = new IteratorChain();
it = ((FactHandleImpl) handle).getNotTuples();
- if ( it != null ) {
- chain.addIterator( it );
+ if (it != null) {
+ chain.addIterator(it);
}
it = ((FactHandleImpl) handle).getExistsTuples();
- if ( it != null ) {
- chain.addIterator( it );
+ if (it != null) {
+ chain.addIterator(it);
}
- for ( ; chain.hasNext(); ) {
+ for (; chain.hasNext();) {
tuple = ((FactHandleTupleAssembly) chain.next()).getTuple();
- if ( tuple.isReadyForActivation() && tuple.isActivationNull() ) {
+ if (tuple.isReadyForActivation() && tuple.isActivationNull()) {
// ready to activate
- this.assertTuple( tuple );
+ this.assertTuple(tuple);
} else {
// time to pull from agenda
- this.invalidateActivation( tuple );
+ this.invalidateActivation(tuple);
}
}
// remove it from stack
- this.stack.remove( new Token( this,
- (FactHandleImpl) handle ) );
+ this.stack.remove(new Token(this, (FactHandleImpl) handle, null));
//
// end leaps specific actions
//
- Object oldObject = removeObject( handle );
+ Object oldObject = removeObject(handle);
/* check to see if this was a logical asserted object */
- if ( removeLogical ) {
- this.equalsMap.remove( oldObject );
+ if (removeLogical) {
+ this.equalsMap.remove(oldObject);
}
- if ( updateEqualsMap ) {
- this.equalsMap.remove( oldObject );
+ if (updateEqualsMap) {
+ this.equalsMap.remove(oldObject);
}
// not applicable to leaps implementation
// this.factHandlePool.push( ((FactHandleImpl) handle).getId() );
- PropagationContextImpl context = new PropagationContextImpl( ++this.propagationIdCounter,
- PropagationContext.RETRACTION,
- rule,
- activation );
-
- this.workingMemoryEventSupport.fireObjectRetracted( context,
- handle,
- oldObject );
+ PropagationContextImpl context = new PropagationContextImpl(
+ nextPropagationIdCounter(), PropagationContext.RETRACTION,
+ rule, activation);
+
+ this.workingMemoryEventSupport.fireObjectRetracted(context, handle,
+ oldObject);
// not applicable to leaps fact handle
// ((FactHandleImpl) handle).invalidate();
}
private void invalidateActivation(LeapsTuple tuple) {
- if ( !tuple.isReadyForActivation() && !tuple.isActivationNull() ) {
+ if (!tuple.isReadyForActivation() && !tuple.isActivationNull()) {
Activation activation = tuple.getActivation();
// invalidate agenda agendaItem
- if ( activation.isActivated() ) {
+ if (activation.isActivated()) {
activation.remove();
- getAgendaEventSupport().fireActivationCancelled( activation );
+ getAgendaEventSupport().fireActivationCancelled(activation);
}
//
- tuple.setActivation( null );
+ tuple.setActivation(null);
}
// remove logical dependency
FactHandleImpl factHandle;
Iterator it = tuple.getLogicalDependencies();
- if ( it != null ) {
- for ( ; it.hasNext(); ) {
+ if (it != null) {
+ for (; it.hasNext();) {
factHandle = (FactHandleImpl) it.next();
- factHandle.removeLogicalDependency( tuple );
- if ( !factHandle.isLogicalyValid() ) {
- this.retractObject( factHandle );
+ factHandle.removeLogicalDependency(tuple);
+ if (!factHandle.isLogicalyValid()) {
+ this.retractObject(factHandle);
}
}
}
@@ -504,45 +482,38 @@ private void invalidateActivation(LeapsTuple tuple) {
/**
* @see WorkingMemory
*/
- public void modifyObject(FactHandle handle,
- Object object,
- Rule rule,
- Activation activation) throws FactException {
+ public void modifyObject(FactHandle handle, Object object, Rule rule,
+ Activation activation) throws FactException {
- this.retractObject( handle );
+ this.retractObject(handle);
- this.assertObject( object );
+ this.assertObject(object, false, false, rule, activation);
/*
* this.ruleBase.modifyObject( handle, object, this );
*/
- this.workingMemoryEventSupport.fireObjectModified( new PropagationContextImpl( ++this.propagationIdCounter,
- PropagationContext.MODIFICATION,
- rule,
- activation ),
- handle,
- ((FactHandleImpl) handle).getObject(),
- object );
+ this.workingMemoryEventSupport.fireObjectModified(
+ new PropagationContextImpl(nextPropagationIdCounter(),
+ PropagationContext.MODIFICATION, rule, activation),
+ handle, ((FactHandleImpl) handle).getObject(), object);
}
/**
- * leaps section
+ * ************* leaps section *********************
*/
+ private final Object lock = new Object();
- private final Object lock = new Object();
-
- // private long idsSequence;
-
- private long idLastFireAllAt = -1;
+ private long idLastFireAllAt = -1;
/**
- * algorithm stack. TreeSet is used to facilitate dynamic rule add/remove
+ * algorithm stack.
*/
+ private Stack stack = new Stack();
- private Stack stack = new Stack();
-
- // to store facts to cursor over it
- private final Hashtable factTables = new Hashtable();
+ /**
+ * to store facts to cursor over it
+ */
+ private final Hashtable factTables = new Hashtable();
/**
* generates or just return List of internal factTables that correspond a
@@ -553,9 +524,9 @@ public void modifyObject(FactHandle handle,
protected List getFactTablesList(Class c) {
ArrayList list = new ArrayList();
Class bufClass = c;
- while ( bufClass != null ) {
+ while (bufClass != null) {
//
- list.add( this.getFactTable( bufClass ) );
+ list.add(this.getFactTable(bufClass));
// and get the next class on the list
bufClass = bufClass.getSuperclass();
}
@@ -568,7 +539,7 @@ protected List getFactTablesList(Class c) {
* @param token
*/
protected void pushTokenOnStack(Token token) {
- this.stack.push( token );
+ this.stack.push(token);
}
/**
@@ -580,12 +551,11 @@ protected void pushTokenOnStack(Token token) {
*/
protected FactTable getFactTable(Class c) {
FactTable table;
- if ( this.factTables.containsKey( c ) ) {
- table = (FactTable) this.factTables.get( c );
+ if (this.factTables.containsKey(c)) {
+ table = (FactTable) this.factTables.get(c);
} else {
- table = new FactTable( DefaultConflictResolver.getInstance() );
- this.factTables.put( c,
- table );
+ table = new FactTable(DefaultConflictResolver.getInstance());
+ this.factTables.put(c, table);
}
return table;
@@ -597,59 +567,62 @@ protected FactTable getFactTable(Class c) {
* @param rules
*/
protected void addLeapsRules(List rules) {
- synchronized ( this.lock ) {
+ synchronized (this.lock) {
ArrayList ruleHandlesList;
LeapsRule rule;
RuleHandle ruleHandle;
- for ( Iterator it = rules.iterator(); it.hasNext(); ) {
+ for (Iterator it = rules.iterator(); it.hasNext();) {
rule = (LeapsRule) it.next();
// some times rules do not have "normal" constraints and only
// not and exists
- if ( rule.getNumberOfColumns() > 0 ) {
+ if (rule.getNumberOfColumns() > 0) {
ruleHandlesList = new ArrayList();
- for ( int i = 0; i < rule.getNumberOfColumns(); i++ ) {
- ruleHandle = new RuleHandle( ((HandleFactory) this.handleFactory).getNextId(),
- rule,
- i );
+ for (int i = 0; i < rule.getNumberOfColumns(); i++) {
+ ruleHandle = new RuleHandle(
+ ((HandleFactory) this.handleFactory)
+ .getNextId(), rule, i);
//
- this.getFactTable( rule.getColumnClassObjectTypeAtPosition( i ) ).addRule( this,
- ruleHandle );
+ this.getFactTable(
+ rule.getColumnClassObjectTypeAtPosition(i))
+ .addRule(this, ruleHandle);
//
- ruleHandlesList.add( ruleHandle );
+ ruleHandlesList.add(ruleHandle);
}
- this.leapsRulesToHandlesMap.put( rule,
- ruleHandlesList );
+ this.leapsRulesToHandlesMap.put(rule, ruleHandlesList);
} else {
- ruleHandle = new RuleHandle( ((HandleFactory) this.handleFactory).getNextId(),
- rule,
- -1 );
- this.noRequiredColumnsLeapsRules.add( ruleHandle );
- this.leapsRulesToHandlesMap.put( rule,
- ruleHandle );
+ ruleHandle = new RuleHandle(
+ ((HandleFactory) this.handleFactory).getNextId(),
+ rule, -1);
+ this.noRequiredColumnsLeapsRules.add(ruleHandle);
+ this.leapsRulesToHandlesMap.put(rule, ruleHandle);
}
}
}
}
protected void removeRule(List rules) {
- synchronized ( this.lock ) {
+ synchronized (this.lock) {
ArrayList ruleHandlesList;
LeapsRule rule;
RuleHandle ruleHandle;
- for ( Iterator it = rules.iterator(); it.hasNext(); ) {
+ for (Iterator it = rules.iterator(); it.hasNext();) {
rule = (LeapsRule) it.next();
// some times rules do not have "normal" constraints and only
// not and exists
- if ( rule.getNumberOfColumns() > 0 ) {
- ruleHandlesList = (ArrayList) this.leapsRulesToHandlesMap.remove( rule );
- for ( int i = 0; i < ruleHandlesList.size(); i++ ) {
- ruleHandle = (RuleHandle) ruleHandlesList.get( i );
+ if (rule.getNumberOfColumns() > 0) {
+ ruleHandlesList = (ArrayList) this.leapsRulesToHandlesMap
+ .remove(rule);
+ for (int i = 0; i < ruleHandlesList.size(); i++) {
+ ruleHandle = (RuleHandle) ruleHandlesList.get(i);
//
- this.getFactTable( rule.getColumnClassObjectTypeAtPosition( i ) ).removeRule( ruleHandle );
+ this.getFactTable(
+ rule.getColumnClassObjectTypeAtPosition(i))
+ .removeRule(ruleHandle);
}
} else {
- ruleHandle = (RuleHandle) this.leapsRulesToHandlesMap.remove( rule );
- this.noRequiredColumnsLeapsRules.remove( ruleHandle );
+ ruleHandle = (RuleHandle) this.leapsRulesToHandlesMap
+ .remove(rule);
+ this.noRequiredColumnsLeapsRules.remove(ruleHandle);
}
}
}
@@ -665,65 +638,64 @@ public void fireAllRules(AgendaFilter agendaFilter) throws FactException {
// nested inside, avoiding concurrent-modification
// exceptions, depending on code paths of the actions.
- if ( !this.firing ) {
+ if (!this.firing) {
try {
this.firing = true;
// normal rules with required columns
- while ( !this.stack.isEmpty() ) {
+ while (!this.stack.isEmpty()) {
Token token = (Token) this.stack.peek();
boolean done = false;
- while ( !done ) {
- if ( !token.isResume() ) {
- if ( token.hasNextRuleHandle() ) {
+ while (!done) {
+ if (!token.isResume()) {
+ if (token.hasNextRuleHandle()) {
token.nextRuleHandle();
} else {
// we do not pop because something might get
// asserted
// and placed on hte top of the stack during
// firing
- this.stack.remove( token );
+ this.stack.remove(token);
done = true;
}
}
- if ( !done ) {
+ if (!done) {
try {
// ok. now we have tuple, dominant fact and
// rules and ready to seek to checks if any
// agendaItem
// matches on current rule
- TokenEvaluator.evaluate( token );
+ TokenEvaluator.evaluate(token);
// something was found so set marks for
// resume processing
- if ( token.getDominantFactHandle() != null ) {
- token.setResume( true );
+ if (token.getDominantFactHandle() != null) {
+ token.setResume(true);
done = true;
}
- } catch ( NoMatchesFoundException ex ) {
- token.setResume( false );
- } catch ( Exception e ) {
- e.printStackTrace();
- System.out.println( "exception - " + e );
+ } catch (NoMatchesFoundException ex) {
+ token.setResume(false);
}
}
// we put everything on agenda
// and if there is no modules or anything like it
// it would fire just activated rule
- while ( this.agenda.fireNextItem( agendaFilter ) ) {
+ while (this.agenda.fireNextItem(agendaFilter)) {
;
}
}
}
- // pick activations generated by retraction
- // retraction does not put tokens on stack but
+ // pick activations generated by retraction
+ // retraction does not put tokens on stack but
// can generate activations off exists and not pending tuples
- while ( this.agenda.fireNextItem( agendaFilter ) ) {
+ while (this.agenda.fireNextItem(agendaFilter)) {
;
}
// mark when method was called last time
- this.idLastFireAllAt = ((HandleFactory) this.handleFactory).getNextId();
+ this.idLastFireAllAt = ((HandleFactory) this.handleFactory)
+ .getNextId();
// set all factTables to be reseeded
- for ( Enumeration e = this.factTables.elements(); e.hasMoreElements(); ) {
- ((FactTable) e.nextElement()).setReseededStack( true );
+ for (Enumeration e = this.factTables.elements(); e
+ .hasMoreElements();) {
+ ((FactTable) e.nextElement()).setReseededStack(true);
}
} finally {
this.firing = false;
@@ -740,13 +712,13 @@ public String toString() {
Object key;
ret = ret + "\n" + "Working memory";
ret = ret + "\n" + "Fact Tables by types:";
- for ( Enumeration e = this.factTables.keys(); e.hasMoreElements(); ) {
+ for (Enumeration e = this.factTables.keys(); e.hasMoreElements();) {
key = e.nextElement();
ret = ret + "\n" + "****************** " + key;
- ret = ret + ((FactTable) this.factTables.get( key )).toString();
+ ret = ret + ((FactTable) this.factTables.get(key)).toString();
}
ret = ret + "\n" + "Stack:";
- for ( Iterator it = this.stack.iterator(); it.hasNext(); ) {
+ for (Iterator it = this.stack.iterator(); it.hasNext();) {
ret = ret + "\n" + "\t" + it.next();
}
return ret;
@@ -764,109 +736,107 @@ public String toString() {
*/
public void assertTuple(LeapsTuple tuple) {
PropagationContext context = tuple.getContext();
- Rule rule = context.getRuleOrigin();
+ Rule rule = tuple.getLeapsRule().getRule();
// if the current Rule is no-loop and the origin rule is the same then
// return
- if ( rule.getNoLoop() && rule.equals( context.getRuleOrigin() ) ) {
+ if (rule.getNoLoop() && rule.equals(context.getRuleOrigin())) {
return;
}
Duration dur = rule.getDuration();
Activation agendaItem;
- if ( dur != null && dur.getDuration( tuple ) > 0 ) {
- agendaItem = new ScheduledAgendaItem( context.getPropagationNumber(),
- tuple,
- this.agenda,
- context,
- rule );
- this.agenda.scheduleItem( (ScheduledAgendaItem) agendaItem );
- tuple.setActivation( agendaItem );
- agendaItem.setActivated( true );
- this.getAgendaEventSupport().fireActivationCreated( agendaItem );
+ if (dur != null && dur.getDuration(tuple) > 0) {
+ agendaItem = new ScheduledAgendaItem(
+ context.getPropagationNumber(), tuple, this.agenda,
+ context, rule);
+ this.agenda.scheduleItem((ScheduledAgendaItem) agendaItem);
+ tuple.setActivation(agendaItem);
+ agendaItem.setActivated(true);
+ this.getAgendaEventSupport().fireActivationCreated(agendaItem);
} else {
- // -----------------
- // Lazy instantiation and addition to the Agenda of AgendGroup
- // implementations
- // ----------------
- AgendaGroupImpl agendaGroup = null;
- if ( rule.getAgendaGroup() == null || rule.getAgendaGroup().equals( "" ) || rule.getAgendaGroup().equals( AgendaGroup.MAIN ) ) {
- // Is the Rule AgendaGroup undefined? If it is use MAIN, which
- // is added to the Agenda by default
- agendaGroup = (AgendaGroupImpl) this.agenda.getAgendaGroup( AgendaGroup.MAIN );
- } else {
- // AgendaGroup is defined, so try and get the AgendaGroup from
- // the Agenda
- agendaGroup = (AgendaGroupImpl) this.agenda.getAgendaGroup( rule.getAgendaGroup() );
- }
+ LeapsRule leapsRule = tuple.getLeapsRule();
+ AgendaGroupImpl agendaGroup = leapsRule.getAgendaGroup();
+ if (agendaGroup == null) {
+ if (rule.getAgendaGroup() == null
+ || rule.getAgendaGroup().equals("")
+ || rule.getAgendaGroup().equals(AgendaGroup.MAIN)) {
+ // Is the Rule AgendaGroup undefined? If it is use MAIN,
+ // which is added to the Agenda by default
+ agendaGroup = (AgendaGroupImpl) this.agenda
+ .getAgendaGroup(AgendaGroup.MAIN);
+ } else {
+ // AgendaGroup is defined, so try and get the AgendaGroup
+ // from the Agenda
+ agendaGroup = (AgendaGroupImpl) this.agenda
+ .getAgendaGroup(rule.getAgendaGroup());
+ }
- if ( agendaGroup == null ) {
- // The AgendaGroup is defined but not yet added to the Agenda,
- // so create the AgendaGroup and add to the Agenda.
- agendaGroup = new AgendaGroupImpl( rule.getAgendaGroup() );
- this.agenda.addAgendaGroup( agendaGroup );
+ if (agendaGroup == null) {
+ // The AgendaGroup is defined but not yet added to the
+ // Agenda, so create the AgendaGroup and add to the Agenda.
+ agendaGroup = new AgendaGroupImpl(rule.getAgendaGroup());
+ this.getAgenda().addAgendaGroup(agendaGroup);
+ }
+
+ leapsRule.setAgendaGroup(agendaGroup);
}
// set the focus if rule autoFocus is true
- if ( rule.getAutoFocus() ) {
- this.agenda.setFocus( agendaGroup );
+ if (rule.getAutoFocus()) {
+ this.agenda.setFocus(agendaGroup);
+ }
+
+ // Lazy assignment of the AgendaGroup's Activation Lifo Queue
+ if (leapsRule.getLifo() == null) {
+ leapsRule.setLifo(agendaGroup.getActivationQueue(rule
+ .getSalience()));
}
- ActivationQueue queue = agendaGroup.getActivationQueue( rule.getSalience() );
- agendaItem = new AgendaItem( context.getPropagationNumber(),
- tuple,
- context,
- rule,
- queue );
+ ActivationQueue queue = leapsRule.getLifo();
- queue.add( agendaItem );
+ agendaItem = new AgendaItem(context.getPropagationNumber(), tuple,
+ context, rule, queue);
+
+ queue.add(agendaItem);
// Makes sure the Lifo is added to the AgendaGroup priority queue
// If the AgendaGroup is already in the priority queue it just
// returns.
- agendaGroup.addToAgenda( queue );
- tuple.setActivation( agendaItem );
- agendaItem.setActivated( true );
- this.getAgendaEventSupport().fireActivationCreated( agendaItem );
+
+ agendaGroup.addToAgenda(leapsRule.getLifo());
+ tuple.setActivation(agendaItem);
+ agendaItem.setActivated(true);
+ this.getAgendaEventSupport().fireActivationCreated(agendaItem);
+
// retract support
- FactHandleImpl[] factHandles = (FactHandleImpl[]) tuple.getFactHandles();
- for ( int i = 0; i < factHandles.length; i++ ) {
- factHandles[i].addActivatedTuple( tuple );
+ FactHandleImpl[] factHandles = (FactHandleImpl[]) tuple
+ .getFactHandles();
+ for (int i = 0; i < factHandles.length; i++) {
+ factHandles[i].addActivatedTuple(tuple);
}
}
}
- protected long increamentPropagationIdCounter() {
+ protected long nextPropagationIdCounter() {
return ++this.propagationIdCounter;
}
public void dispose() {
- ((RuleBaseImpl) this.ruleBase).disposeWorkingMemory( this );
- }
-
- /**
- * Retrieve the rule-firing <code>Agenda</code> for this
- * <code>WorkingMemory</code>.
- *
- * @return The <code>Agenda</code>.
- */
- public Agenda getAgenda() {
- return this.agenda;
+ ((RuleBaseImpl) this.ruleBase).disposeWorkingMemory(this);
}
public List getQueryResults(String query) {
- return (List) this.queryResults.remove( query );
+ return (List) this.queryResults.remove(query);
}
- void addToQueryResults(String query,
- Tuple tuple) {
- LinkedList list = (LinkedList) this.queryResults.get( query );
- if ( list == null ) {
+ void addToQueryResults(String query, Tuple tuple) {
+ LinkedList list = (LinkedList) this.queryResults.get(query);
+ if (list == null) {
list = new LinkedList();
- this.queryResults.put( query,
- list );
+ this.queryResults.put(query, list);
}
- list.add( tuple );
+ list.add(tuple);
}
protected TableIterator getNoRequiredColumnsLeapsRules() {
@@ -876,12 +846,17 @@ protected TableIterator getNoRequiredColumnsLeapsRules() {
public AgendaGroup getFocus() {
return this.agenda.getFocus();
}
-
+
public void setFocus(String focus) {
- this.agenda.setFocus( focus );
+ this.agenda.setFocus(focus);
}
-
+
public void setFocus(AgendaGroup focus) {
- this.agenda.setFocus( focus );
- }
+ this.agenda.setFocus(focus);
+ }
+
+ public Agenda getAgenda() {
+ return this.agenda;
+ }
+
}
diff --git a/drools-core/src/main/java/org/drools/leaps/util/Table.java b/drools-core/src/main/java/org/drools/leaps/util/Table.java
index 8aa1a1473b6..ac3276aae63 100644
--- a/drools-core/src/main/java/org/drools/leaps/util/Table.java
+++ b/drools-core/src/main/java/org/drools/leaps/util/Table.java
@@ -28,298 +28,301 @@
/**
*
* @author Alexander Bagerman
- *
+ *
*/
public class Table implements Serializable {
- private final TreeMap map;
-
- protected TableRecord headRecord;
-
- protected TableRecord tailRecord;
-
- private boolean empty = true;
-
- private int count = 0;
-
- public Table(Comparator comparator) {
- this.map = new TreeMap(comparator);
- }
-
- protected void clear() {
- this.headRecord = new TableRecord(null);
- this.empty = true;
- this.count = 0;
- this.map.clear();
- }
-
- /**
- * @param object
- * to add
- */
- public void add(Object object) {
- boolean foundEqualObject = false;
- TableRecord newRecord = new TableRecord(object);
- if (this.empty) {
- this.headRecord = newRecord;
- this.empty = false;
- } else {
- SortedMap bufMap = this.map.headMap(object);
- if (!bufMap.isEmpty()) {
- TableRecord bufRec = (TableRecord) this.map.get(bufMap.lastKey());
- if (bufRec.right != null) {
- bufRec.right.left = newRecord;
- }
- newRecord.right = bufRec.right;
- bufRec.right = newRecord;
- newRecord.left = bufRec;
-
- } else {
- this.headRecord.left = newRecord;
- newRecord.right = this.headRecord;
- this.headRecord = newRecord;
- }
- }
- if (!foundEqualObject) {
- // check if the new record was added at the end of the list
- // and assign new value to the tail record
- if (newRecord.right == null) {
- this.tailRecord = newRecord;
- }
- //
- this.count++;
- //
- this.map.put(object, newRecord);
- }
- }
-
- /**
- * Removes object from the table
- *
- * @param object
- * to remove from the table
- */
- public void remove(Object object) {
- if (!this.empty) {
- TableRecord record = (TableRecord) this.map.get(object);
-
- if (record != null) {
- if (record == this.headRecord) {
- if (record.right != null) {
- this.headRecord = record.right;
- this.headRecord.left = null;
- } else {
- // single element in table being valid
- // table is empty now
- this.headRecord = new TableRecord(null);
- this.tailRecord = this.headRecord;
- this.empty = true;
- }
- } else if (record == this.tailRecord) {
- // single element in the table case is being solved above
- // when
- // we checked for headRecord match
- this.tailRecord = record.left;
- this.tailRecord.right = null;
- } else {
- // left
- record.left.right = record.right;
- record.right.left = record.left;
- }
- }
- this.count--;
- //
- this.map.remove(object);
- }
- }
-
- /**
- * @param object
- * @return indicator of presence of given object in the table
- */
- public boolean contains(Object object) {
- boolean ret = false;
- if (!this.empty) {
- ret = this.map.containsKey(object);
- }
- return ret;
- }
-
- /**
- * @return TableIterator for this Table
- * @see org.drools.leaps.util.TableIterator
- * @see org.drools.leaps.util.BaseTableIterator
- */
- public TableIterator iterator() {
- TableIterator ret;
- if (this.empty) {
- ret = new BaseTableIterator(null, null, null);
- } else {
- ret = new BaseTableIterator(this.headRecord, this.headRecord,
- this.tailRecord);
- }
- return ret;
- }
-
- /**
- * iterator over "tail" part of the table data.
- *
- * @param objectAtStart -
- * upper boundary of the iteration
- * @param objectAtPosition -
- * starting point of the iteration
- * @return leaps table iterator
- * @throws TableOutOfBoundException
- */
- class Markers {
- TableRecord start;
- TableRecord current;
- TableRecord last;
- }
-
- public TableIterator tailConstrainedIterator(WorkingMemory workingMemory,
- ColumnConstraints constraints, Object objectAtStart,
- Object objectAtPosition) throws TableOutOfBoundException {
- Markers markers = this.getTailIteratorMarkers(objectAtStart,
- objectAtPosition);
- return new ConstrainedFactTableIterator(workingMemory, constraints,
- markers.start, markers.current, markers.last);
-
- }
-
- public TableIterator tailIterator(Object objectAtStart,
- Object objectAtPosition) throws TableOutOfBoundException {
- Markers markers = this.getTailIteratorMarkers(objectAtStart, objectAtPosition);
- return new BaseTableIterator(markers.start, markers.current,
- markers.last);
- }
-
-
- private Markers getTailIteratorMarkers(Object objectAtStart,
- Object objectAtPosition) throws TableOutOfBoundException {
- // validate
- Markers ret = new Markers();
- ret.start = null;
- ret.current = null;
- ret.last = null;
- //
- if (this.map.comparator().compare(objectAtStart, objectAtPosition) > 0) {
- throw new TableOutOfBoundException(
- "object at position is out of upper bound");
- }
- TableRecord startRecord = null;
- TableRecord currentRecord = null;
- TableRecord lastRecord = this.tailRecord;
-
- if (!this.empty) { // validate
- // if (!this.map.isEmpty()) { // validate
- if (this.map.comparator().compare(objectAtStart,
- this.tailRecord.object) <= 0) {
- // let's check if we need iterator over the whole table
- SortedMap bufMap = this.map.tailMap(objectAtStart);
- if (!bufMap.isEmpty()) {
- startRecord = (TableRecord) bufMap.get(bufMap.firstKey());
- if (this.map.comparator().compare(objectAtStart,
- objectAtPosition) == 0) {
- currentRecord = startRecord;
- } else {
- // rewind to position
- bufMap = bufMap.tailMap(objectAtPosition);
-
- if (!bufMap.isEmpty()) {
- currentRecord = ((TableRecord) bufMap.get(bufMap
- .firstKey()));
- } else {
- currentRecord = startRecord;
- }
- }
- ret.start = startRecord;
- ret.current = currentRecord;
- ret.last = lastRecord;
- }
- }
- }
-
- return ret;
- }
-
- /**
- * iterator over "head" part of the table data. it does not take
- * "positional" parameter because it's used for scanning shadow tables and
- * this scan never "resumes"
- *
- * @param objectAtEnd -
- * lower boundary of the iteration
- * @return leaps table iterator
- */
- public TableIterator headIterator(Object objectAtEnd) {
- TableIterator iterator = null;
- TableRecord startRecord = this.headRecord;
- TableRecord currentRecord = this.headRecord;
- TableRecord lastRecord = null;
-
- if (!this.empty) { // validate
- if (this.map.comparator().compare(this.headRecord.object,
- objectAtEnd) <= 0) {
- // let's check if we need iterator over the whole table
- SortedMap bufMap = this.map.headMap(objectAtEnd);
- if (!bufMap.isEmpty()) {
- lastRecord = (TableRecord) bufMap.get(bufMap.lastKey());
- // check if the next one is what we need
- if (lastRecord.right != null
- && this.map.comparator().compare(
- lastRecord.right.object, objectAtEnd) == 0) {
- lastRecord = lastRecord.right;
- }
- iterator = new BaseTableIterator(startRecord, currentRecord,
- lastRecord);
- } else {
- // empty iterator
- iterator = new BaseTableIterator(null, null, null);
- }
- } else {
- // empty iterator
- iterator = new BaseTableIterator(null, null, null);
- }
- } else {
- // empty iterator
- iterator = new BaseTableIterator(null, null, null);
- }
-
- return iterator;
- }
-
- /**
- * indicates if table has any elements
- *
- * @return empty indicator
- */
- public boolean isEmpty() {
- return this.empty;
- }
-
- public String toString() {
- String ret = "";
-
- for (Iterator it = this.iterator(); it.hasNext();) {
- ret = ret + it.next() + "\n";
- }
- return ret;
- }
-
- public int size() {
- return this.count;
- }
-
- public Object top() {
- return this.headRecord.object;
- }
-
- public Object bottom() {
- return this.tailRecord.object;
- }
-
- public static TableIterator singleItemIterator(Object object){
- return new BaseTableIterator(new TableRecord(object));
- }
+ private final TreeMap map;
+
+ protected TableRecord headRecord;
+
+ protected TableRecord tailRecord;
+
+ private boolean empty = true;
+
+ private int count = 0;
+
+ public Table(Comparator comparator) {
+ this.map = new TreeMap(comparator);
+ }
+
+ protected void clear() {
+ this.headRecord = new TableRecord(null);
+ this.empty = true;
+ this.count = 0;
+ this.map.clear();
+ }
+
+ /**
+ * @param object
+ * to add
+ */
+ public void add(Object object) {
+ boolean foundEqualObject = false;
+ TableRecord newRecord = new TableRecord(object);
+ if (this.empty) {
+ this.headRecord = newRecord;
+ this.empty = false;
+ } else {
+ SortedMap bufMap = this.map.headMap(object);
+ if (!bufMap.isEmpty()) {
+ TableRecord bufRec = (TableRecord) this.map.get(bufMap
+ .lastKey());
+ if (bufRec.right != null) {
+ bufRec.right.left = newRecord;
+ }
+ newRecord.right = bufRec.right;
+ bufRec.right = newRecord;
+ newRecord.left = bufRec;
+
+ } else {
+ this.headRecord.left = newRecord;
+ newRecord.right = this.headRecord;
+ this.headRecord = newRecord;
+ }
+ }
+ if (!foundEqualObject) {
+ // check if the new record was added at the end of the list
+ // and assign new value to the tail record
+ if (newRecord.right == null) {
+ this.tailRecord = newRecord;
+ }
+ //
+ this.count++;
+ //
+ this.map.put(object, newRecord);
+ }
+ }
+
+ /**
+ * Removes object from the table
+ *
+ * @param object
+ * to remove from the table
+ */
+ public void remove(Object object) {
+ if (!this.empty) {
+ TableRecord record = (TableRecord) this.map.get(object);
+
+ if (record != null) {
+ if (record == this.headRecord) {
+ if (record.right != null) {
+ this.headRecord = record.right;
+ this.headRecord.left = null;
+ } else {
+ // single element in table being valid
+ // table is empty now
+ this.headRecord = new TableRecord(null);
+ this.tailRecord = this.headRecord;
+ this.empty = true;
+ }
+ } else if (record == this.tailRecord) {
+ // single element in the table case is being solved above
+ // when
+ // we checked for headRecord match
+ this.tailRecord = record.left;
+ this.tailRecord.right = null;
+ } else {
+ // left
+ record.left.right = record.right;
+ record.right.left = record.left;
+ }
+ }
+ this.count--;
+ //
+ this.map.remove(object);
+ }
+ }
+
+ /**
+ * @param object
+ * @return indicator of presence of given object in the table
+ */
+ public boolean contains(Object object) {
+ boolean ret = false;
+ if (!this.empty) {
+ ret = this.map.containsKey(object);
+ }
+ return ret;
+ }
+
+ /**
+ * @return TableIterator for this Table
+ * @see org.drools.leaps.util.TableIterator
+ * @see org.drools.leaps.util.BaseTableIterator
+ */
+ public TableIterator iterator() {
+ TableIterator ret;
+ if (this.empty) {
+ ret = new BaseTableIterator(null, null, null);
+ } else {
+ ret = new BaseTableIterator(this.headRecord, this.headRecord,
+ this.tailRecord);
+ }
+ return ret;
+ }
+
+ /**
+ * iterator over "tail" part of the table data.
+ *
+ * @param objectAtStart -
+ * upper boundary of the iteration
+ * @param objectAtPosition -
+ * starting point of the iteration
+ * @return leaps table iterator
+ * @throws TableOutOfBoundException
+ */
+ class Markers {
+ TableRecord start;
+
+ TableRecord current;
+
+ TableRecord last;
+ }
+
+ public TableIterator tailConstrainedIterator(WorkingMemory workingMemory,
+ ColumnConstraints constraints, Object objectAtStart,
+ Object objectAtPosition) {
+ Markers markers = this.getTailIteratorMarkers(objectAtStart,
+ objectAtPosition);
+ return new ConstrainedFactTableIterator(workingMemory, constraints,
+ markers.start, markers.current, markers.last);
+
+ }
+
+ public TableIterator tailIterator(Object objectAtStart,
+ Object objectAtPosition) {
+ Markers markers = this.getTailIteratorMarkers(objectAtStart,
+ objectAtPosition);
+ return new BaseTableIterator(markers.start, markers.current,
+ markers.last);
+ }
+
+ private Markers getTailIteratorMarkers(Object objectAtStart,
+ Object objectAtPosition) {
+ // validate
+ Markers ret = new Markers();
+ ret.start = null;
+ ret.current = null;
+ ret.last = null;
+ //
+ if (this.map.comparator().compare(objectAtStart, objectAtPosition) > 0) {
+ // return empty iterator
+ return ret;
+ }
+ TableRecord startRecord = null;
+ TableRecord currentRecord = null;
+ TableRecord lastRecord = this.tailRecord;
+
+ if (!this.empty) { // validate
+ // if (!this.map.isEmpty()) { // validate
+ if (this.map.comparator().compare(objectAtStart,
+ this.tailRecord.object) <= 0) {
+ // let's check if we need iterator over the whole table
+ SortedMap bufMap = this.map.tailMap(objectAtStart);
+ if (!bufMap.isEmpty()) {
+ startRecord = (TableRecord) bufMap.get(bufMap.firstKey());
+ if (this.map.comparator().compare(objectAtStart,
+ objectAtPosition) == 0) {
+ currentRecord = startRecord;
+ } else {
+ // rewind to position
+ bufMap = bufMap.tailMap(objectAtPosition);
+
+ if (!bufMap.isEmpty()) {
+ currentRecord = ((TableRecord) bufMap.get(bufMap
+ .firstKey()));
+ } else {
+ currentRecord = startRecord;
+ }
+ }
+ ret.start = startRecord;
+ ret.current = currentRecord;
+ ret.last = lastRecord;
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ /**
+ * iterator over "head" part of the table data. it does not take
+ * "positional" parameter because it's used for scanning shadow tables and
+ * this scan never "resumes"
+ *
+ * @param objectAtEnd -
+ * lower boundary of the iteration
+ * @return leaps table iterator
+ */
+ public TableIterator headIterator(Object objectAtEnd) {
+ TableIterator iterator = null;
+ TableRecord startRecord = this.headRecord;
+ TableRecord currentRecord = this.headRecord;
+ TableRecord lastRecord = null;
+
+ if (!this.empty) { // validate
+ if (this.map.comparator().compare(this.headRecord.object,
+ objectAtEnd) <= 0) {
+ // let's check if we need iterator over the whole table
+ SortedMap bufMap = this.map.headMap(objectAtEnd);
+ if (!bufMap.isEmpty()) {
+ lastRecord = (TableRecord) bufMap.get(bufMap.lastKey());
+ // check if the next one is what we need
+ if (lastRecord.right != null
+ && this.map.comparator().compare(
+ lastRecord.right.object, objectAtEnd) == 0) {
+ lastRecord = lastRecord.right;
+ }
+ iterator = new BaseTableIterator(startRecord,
+ currentRecord, lastRecord);
+ } else {
+ // empty iterator
+ iterator = new BaseTableIterator(null, null, null);
+ }
+ } else {
+ // empty iterator
+ iterator = new BaseTableIterator(null, null, null);
+ }
+ } else {
+ // empty iterator
+ iterator = new BaseTableIterator(null, null, null);
+ }
+
+ return iterator;
+ }
+
+ /**
+ * indicates if table has any elements
+ *
+ * @return empty indicator
+ */
+ public boolean isEmpty() {
+ return this.empty;
+ }
+
+ public String toString() {
+ String ret = "";
+
+ for (Iterator it = this.iterator(); it.hasNext();) {
+ ret = ret + it.next() + "\n";
+ }
+ return ret;
+ }
+
+ public int size() {
+ return this.count;
+ }
+
+ public Object top() {
+ return this.headRecord.object;
+ }
+
+ public Object bottom() {
+ return this.tailRecord.object;
+ }
+
+ public static TableIterator singleItemIterator(Object object) {
+ return new BaseTableIterator(new TableRecord(object));
+ }
}
diff --git a/drools-core/src/main/java/org/drools/leaps/util/TableOutOfBoundException.java b/drools-core/src/main/java/org/drools/leaps/util/TableOutOfBoundException.java
deleted file mode 100644
index 2aad4938ec6..00000000000
--- a/drools-core/src/main/java/org/drools/leaps/util/TableOutOfBoundException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package org.drools.leaps.util;
-
-/*
- * Copyright 2005 Alexander Bagerman
- *
- * 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.
- */
-
-/**
- *
- * @author Alexander Bagerman
- *
- */
-public class TableOutOfBoundException extends Exception {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- public TableOutOfBoundException() {
- super();
- }
-
- public TableOutOfBoundException(String msg) {
- super(msg);
- }
-
- public TableOutOfBoundException(Exception ex) {
- super(ex);
- }
-}
diff --git a/drools-core/src/test/java/org/drools/leaps/LogicalAssertionTest.java b/drools-core/src/test/java/org/drools/leaps/LogicalAssertionTest.java
index 3734ea589ea..0160fe3273c 100644
--- a/drools-core/src/test/java/org/drools/leaps/LogicalAssertionTest.java
+++ b/drools-core/src/test/java/org/drools/leaps/LogicalAssertionTest.java
@@ -16,6 +16,8 @@
* limitations under the License.
*/
+import java.util.ArrayList;
+
import org.drools.DroolsTestCase;
import org.drools.FactException;
import org.drools.FactHandle;
@@ -58,6 +60,8 @@ public void testEqualsMap() throws Exception {
rule1.setConsequence(this.consequence);
+ LeapsRule leapsRule1 = new LeapsRule(rule1, new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList());
+
FactHandleImpl[] factHandles = new FactHandleImpl[1];
PropagationContext context1;
LeapsTuple tuple1;
@@ -68,7 +72,7 @@ public void testEqualsMap() throws Exception {
context1 = new PropagationContextImpl(1, PropagationContext.ASSERTION,
rule1, null);
factHandles[0] = (FactHandleImpl) handle1;
- tuple1 = new LeapsTuple(factHandles, null, context1);
+ tuple1 = new LeapsTuple(factHandles, leapsRule1, context1);
this.workingMemory.assertTuple(tuple1);
FactHandle logicalHandle1 = this.workingMemory.assertObject(
logicalString1, false, true, null, this.workingMemory
@@ -79,7 +83,7 @@ public void testEqualsMap() throws Exception {
logicalString2, false, true, rule1, this.workingMemory
.getAgenda().getActivations()[0]);
factHandles[0] = (FactHandleImpl) logicalHandle2;
- tuple1 = new LeapsTuple(factHandles, null, context1);
+ tuple1 = new LeapsTuple(factHandles, leapsRule1, context1);
this.workingMemory.assertTuple(tuple1);
assertSame(logicalHandle1, logicalHandle2);
@@ -101,6 +105,8 @@ public void testStatedOverride() throws Exception {
rule1.setConsequence(this.consequence);
+ LeapsRule leapsRule1 = new LeapsRule(rule1, new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList());
+
FactHandleImpl[] factHandles = new FactHandleImpl[1];
PropagationContext context1;
LeapsTuple tuple1;
@@ -111,7 +117,7 @@ public void testStatedOverride() throws Exception {
context1 = new PropagationContextImpl(1, PropagationContext.ASSERTION,
rule1, null);
factHandles[0] = (FactHandleImpl) handle1;
- tuple1 = new LeapsTuple(factHandles, null, context1);
+ tuple1 = new LeapsTuple(factHandles, leapsRule1, context1);
this.workingMemory.assertTuple(tuple1);
FactHandle logicalHandle1 = this.workingMemory.assertObject(
logicalString1, false, true, null, this.workingMemory
@@ -133,7 +139,7 @@ public void testStatedOverride() throws Exception {
// Test that a logical assertion cannot override a STATED assertion
factHandles[0] = (FactHandleImpl) logicalHandle2;
- tuple1 = new LeapsTuple(factHandles, null, context1);
+ tuple1 = new LeapsTuple(factHandles, leapsRule1, context1);
this.workingMemory.assertTuple(tuple1);
logicalString2 = new String("logical");
@@ -174,6 +180,8 @@ public void testRetract() throws Exception {
// create the first agendaItem which will justify the fact "logical"
rule1.setConsequence(this.consequence);
+ LeapsRule leapsRule1 = new LeapsRule(rule1, new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList());
+
FactHandleImpl tuple1FactHandle = (FactHandleImpl) this.workingMemory
.assertObject("tuple1 object");
FactHandleImpl tuple2FactHandle = (FactHandleImpl) this.workingMemory
@@ -185,9 +193,9 @@ public void testRetract() throws Exception {
PropagationContext context = new PropagationContextImpl(0,
PropagationContext.ASSERTION, rule1, null);
- LeapsTuple tuple1 = new LeapsTuple(factHandlesTuple1, null,
+ LeapsTuple tuple1 = new LeapsTuple(factHandlesTuple1, leapsRule1,
context);
- LeapsTuple tuple2 = new LeapsTuple(factHandlesTuple2, null,
+ LeapsTuple tuple2 = new LeapsTuple(factHandlesTuple2, leapsRule1,
context);
this.workingMemory.assertTuple(tuple1);
Activation activation1 = this.workingMemory.getAgenda()
@@ -204,7 +212,7 @@ public void testRetract() throws Exception {
rule2.setConsequence(this.consequence);
PropagationContext context2 = new PropagationContextImpl(0,
PropagationContext.ASSERTION, rule2, null);
- tuple1 = new LeapsTuple(factHandlesTuple2, null, context2);
+ tuple1 = new LeapsTuple(factHandlesTuple2, leapsRule1, context2);
this.workingMemory.assertTuple(tuple1);
Activation activation2 = this.workingMemory.getAgenda()
.getActivations()[1];
@@ -227,6 +235,9 @@ public void testMultipleLogicalRelationships() throws FactException {
final Rule rule1 = new Rule("test-rule1");
// create the first agendaItem which will justify the fact "logical"
rule1.setConsequence(this.consequence);
+
+ LeapsRule leapsRule1 = new LeapsRule(rule1, new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList());
+
FactHandleImpl tuple1Fact = (FactHandleImpl) this.workingMemory
.assertObject("tuple1 object");
FactHandleImpl tuple2Fact = (FactHandleImpl) this.workingMemory
@@ -238,7 +249,7 @@ public void testMultipleLogicalRelationships() throws FactException {
PropagationContext context1 = new PropagationContextImpl(0,
PropagationContext.ASSERTION, rule1, null);
- LeapsTuple tuple1 = new LeapsTuple(tuple1Handles, null, context1);
+ LeapsTuple tuple1 = new LeapsTuple(tuple1Handles, leapsRule1, context1);
this.workingMemory.assertTuple(tuple1);
Activation activation1 = this.workingMemory.getAgenda()
.getActivations()[0];
@@ -253,7 +264,7 @@ public void testMultipleLogicalRelationships() throws FactException {
rule2.setConsequence(this.consequence);
PropagationContext context2 = new PropagationContextImpl(0,
PropagationContext.ASSERTION, rule2, null);
- LeapsTuple tuple2 = new LeapsTuple(tuple2Handles, null, context2);
+ LeapsTuple tuple2 = new LeapsTuple(tuple2Handles, leapsRule1, context2);
this.workingMemory.assertTuple(tuple2);
// "logical" should only appear once
Activation activation2 = this.workingMemory.getAgenda()
diff --git a/drools-core/src/test/java/org/drools/leaps/SchedulerTest.java b/drools-core/src/test/java/org/drools/leaps/SchedulerTest.java
index 4e243de91f2..25153262ee3 100644
--- a/drools-core/src/test/java/org/drools/leaps/SchedulerTest.java
+++ b/drools-core/src/test/java/org/drools/leaps/SchedulerTest.java
@@ -147,7 +147,7 @@ public void evaluate(KnowledgeHelper knowledgeHelper,
data.size() );
// sleep for 0.5 seconds
- Thread.sleep( 500 );
+ Thread.sleep( 1000 );
// now check for update
assertEquals( 4,
diff --git a/drools-core/src/test/java/org/drools/leaps/util/TableTest.java b/drools-core/src/test/java/org/drools/leaps/util/TableTest.java
index ff230cd3cb7..6e876f8235d 100644
--- a/drools-core/src/test/java/org/drools/leaps/util/TableTest.java
+++ b/drools-core/src/test/java/org/drools/leaps/util/TableTest.java
@@ -171,43 +171,39 @@ public void testTailIterator() {
this.testTable.add(this.h1000);
this.testTable.add(this.h100);
this.testTable.add(this.h10);
- try {
- TableIterator it = this.testTable.tailIterator(this.h100, this.h10);
- assertTrue(it.hasNext());
- assertEquals(it.next(), this.h10);
- assertTrue(it.hasNext());
- assertEquals(it.next(), this.h1);
- assertFalse(it.hasNext());
- it.reset();
- assertTrue(it.hasNext());
- assertEquals(it.next(), this.h100);
- assertTrue(it.hasNext());
- assertEquals(it.next(), this.h10);
- assertTrue(it.hasNext());
- assertEquals(it.next(), this.h1);
- assertFalse(it.hasNext());
-
- this.testTable.clear();
- Handle fh1 = new Handle(1, new Guest("1", Sex.resolve("m"), Hobby
- .resolve("h2")));
- Handle fh2 = new Handle(2, new Guest("1", Sex.resolve("m"), Hobby
- .resolve("h1")));
- Handle fh3 = new Handle(3, new Guest("1", Sex.resolve("m"), Hobby
- .resolve("h3")));
- Handle fh4 = new Handle(4, new Guest("3", Sex.resolve("f"), Hobby
- .resolve("h2")));
- Handle fhC = new Handle(5, new Context("start"));
- this.testTable.add(fh1);
- this.testTable.add(fh2);
- this.testTable.add(fh3);
- this.testTable.add(fh4);
- it = this.testTable.tailIterator(fhC, fhC);
- assertTrue(it.hasNext());
- assertEquals(it.next(), fh4);
-
- } catch (TableOutOfBoundException ex) {
-
- }
+
+ TableIterator it = this.testTable.tailIterator(this.h100, this.h10);
+ assertTrue(it.hasNext());
+ assertEquals(it.next(), this.h10);
+ assertTrue(it.hasNext());
+ assertEquals(it.next(), this.h1);
+ assertFalse(it.hasNext());
+ it.reset();
+ assertTrue(it.hasNext());
+ assertEquals(it.next(), this.h100);
+ assertTrue(it.hasNext());
+ assertEquals(it.next(), this.h10);
+ assertTrue(it.hasNext());
+ assertEquals(it.next(), this.h1);
+ assertFalse(it.hasNext());
+
+ this.testTable.clear();
+ Handle fh1 = new Handle(1, new Guest("1", Sex.resolve("m"), Hobby
+ .resolve("h2")));
+ Handle fh2 = new Handle(2, new Guest("1", Sex.resolve("m"), Hobby
+ .resolve("h1")));
+ Handle fh3 = new Handle(3, new Guest("1", Sex.resolve("m"), Hobby
+ .resolve("h3")));
+ Handle fh4 = new Handle(4, new Guest("3", Sex.resolve("f"), Hobby
+ .resolve("h2")));
+ Handle fhC = new Handle(5, new Context("start"));
+ this.testTable.add(fh1);
+ this.testTable.add(fh2);
+ this.testTable.add(fh3);
+ this.testTable.add(fh4);
+ it = this.testTable.tailIterator(fhC, fhC);
+ assertTrue(it.hasNext());
+ assertEquals(it.next(), fh4);
}
public void testHeadIterator() {
|
7d474706065c400dd59a6808c0a05d9ad1ac77ab
|
restlet-framework-java
|
- Simple HTTP connector works again--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/source/ext/simple3.1/com/noelios/restlet/ext/simple/SimpleServer.java b/source/ext/simple3.1/com/noelios/restlet/ext/simple/SimpleServer.java
index 46c0adedaa..3ce0a5ecd6 100644
--- a/source/ext/simple3.1/com/noelios/restlet/ext/simple/SimpleServer.java
+++ b/source/ext/simple3.1/com/noelios/restlet/ext/simple/SimpleServer.java
@@ -22,28 +22,19 @@
package com.noelios.restlet.ext.simple;
-import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
-import java.security.KeyStore;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-
import org.restlet.component.Component;
import org.restlet.data.ParameterList;
-import org.restlet.data.Protocols;
-import simple.http.BufferedPipelineFactory;
import simple.http.PipelineHandler;
-import simple.http.PipelineHandlerFactory;
import simple.http.ProtocolHandler;
import simple.http.Request;
import simple.http.Response;
import simple.http.connect.Connection;
-import simple.http.connect.ConnectionFactory;
import com.noelios.restlet.impl.HttpServer;
@@ -89,42 +80,6 @@ public SimpleServer(Component owner, ParameterList parameters, String address, i
super(owner, parameters, address, port);
}
- /** Starts the Restlet. */
- public void start() throws Exception
- {
- if(!isStarted())
- {
- if (Protocols.HTTP.equals(super.protocols))
- {
- socket = new ServerSocket(port);
- }
- else if (Protocols.HTTPS.equals(super.protocols))
- {
- KeyStore keyStore = KeyStore.getInstance("JKS");
- keyStore.load(new FileInputStream(keystorePath), keystorePassword
- .toCharArray());
- KeyManagerFactory keyManagerFactory = KeyManagerFactory
- .getInstance("SunX509");
- keyManagerFactory.init(keyStore, keyPassword.toCharArray());
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
- socket = sslContext.getServerSocketFactory().createServerSocket(port);
- socket.setSoTimeout(60000);
- }
- else
- {
- // Should never happen.
- throw new RuntimeException("Unsupported protocol: " + super.protocols);
- }
-
- this.confidential = Protocols.HTTPS.equals(getProtocols());
- this.handler = PipelineHandlerFactory.getInstance(this, 20, 200);
- this.connection = ConnectionFactory.getConnection(handler, new BufferedPipelineFactory());
- this.connection.connect(socket);
- super.start();
- }
- }
-
/** Stops the Restlet. */
public void stop() throws Exception
{
diff --git a/source/main/com/noelios/restlet/impl/FactoryImpl.java b/source/main/com/noelios/restlet/impl/FactoryImpl.java
index 3e3fa990f0..ac34f648ce 100644
--- a/source/main/com/noelios/restlet/impl/FactoryImpl.java
+++ b/source/main/com/noelios/restlet/impl/FactoryImpl.java
@@ -30,7 +30,6 @@
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
-import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -116,7 +115,7 @@ public FactoryImpl()
try
{
Class<? extends Client> providerClass = (Class<? extends Client>) Class.forName(providerClassName);
- this.clients.add(providerClass.newInstance());
+ this.clients.add(providerClass.getConstructor(Component.class, ParameterList.class).newInstance(null, null));
}
catch(Exception e)
{
@@ -166,7 +165,7 @@ public FactoryImpl()
try
{
Class<? extends Server> providerClass = (Class<? extends Server>) Class.forName(providerClassName);
- this.servers.add(providerClass.newInstance());
+ this.servers.add(providerClass.getConstructor(Component.class, ParameterList.class, String.class, int.class).newInstance(null, null, null, new Integer(-1)));
}
catch(Exception e)
{
@@ -204,7 +203,7 @@ public Client createClient(List<Protocol> protocols, Component owner, ParameterL
{
try
{
- return client.getClass().getConstructor(Component.class, Map.class).newInstance(owner, parameters);
+ return client.getClass().getConstructor(Component.class, ParameterList.class).newInstance(owner, parameters);
}
catch (Exception e)
{
@@ -267,7 +266,7 @@ public Server createServer(List<Protocol> protocols, Component owner, ParameterL
{
try
{
- return server.getClass().getConstructor(Component.class, Map.class, String.class, int.class).newInstance(owner, parameters, address, port);
+ return server.getClass().getConstructor(Component.class, ParameterList.class, String.class, int.class).newInstance(owner, parameters, address, port);
}
catch (Exception e)
{
diff --git a/source/main/meta-inf/services/org.restlet.connector.Client b/source/main/meta-inf/services/org.restlet.connector.Client
index 01c6b38b2a..41ab6574c1 100644
--- a/source/main/meta-inf/services/org.restlet.connector.Client
+++ b/source/main/meta-inf/services/org.restlet.connector.Client
@@ -1,3 +1,2 @@
com.noelios.restlet.impl.HttpClient # HTTP, HTTPS
-com.noelios.restlet.impl.FileClient # FILE
-com.noelios.restlet.impl.ContextClient # CONTEXT
+com.noelios.restlet.impl.ContextClient # CONTEXT, FILE
|
406bbcc65dbfe7f43f20f9ed86fa4f09535f331d
|
drools
|
BZ-1006481 - UI support for 'extends' rule keyword- broken--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java
index 4421e9d5b2a..c1f16e93153 100644
--- a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java
+++ b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/shared/oracle/ProjectDataModelOracle.java
@@ -16,6 +16,7 @@
package org.drools.workbench.models.commons.shared.oracle;
+import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -32,8 +33,12 @@ public interface ProjectDataModelOracle {
//Fact and Field related methods
String[] getFactTypes();
+ Map<String,Collection<String>> getRuleNamesMap();
+
List<String> getRuleNames();
+ Collection<String> getRuleNamesForPackage(String packageName);
+
String getFactNameFromType( final String classType );
boolean isFactTypeRecognized( final String factType );
diff --git a/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java b/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java
index dde4f87be37..dbf1abeb0e6 100644
--- a/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java
+++ b/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/oracle/ProjectDataModelOracleImpl.java
@@ -2,6 +2,7 @@
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
@@ -59,7 +60,7 @@ public class ProjectDataModelOracleImpl implements ProjectDataModelOracle {
protected Map<String, Boolean> projectCollectionTypes = new HashMap<String, Boolean>();
// List of available rule names
- private List<String> ruleNames = new ArrayList<String>();
+ private Map<String, Collection<String>> ruleNames = new HashMap<String, Collection<String>>();
// List of available package names
private List<String> packageNames = new ArrayList<String>();
@@ -775,15 +776,29 @@ public Map<String, Boolean> getProjectCollectionTypes() {
return this.projectCollectionTypes;
}
- public void addRuleNames(List<String> ruleNames) {
- this.ruleNames.addAll(ruleNames);
+ public void addRuleNames(String packageName, Collection<String> ruleNames) {
+ this.ruleNames.put(packageName, ruleNames);
}
@Override
- public List<String> getRuleNames() {
+ public Map<String, Collection<String>> getRuleNamesMap() {
return ruleNames;
}
+ @Override
+ public List<String> getRuleNames() {
+ List<String> allTheRuleNames = new ArrayList<String>();
+ for (String packageName : ruleNames.keySet()) {
+ allTheRuleNames.addAll(ruleNames.get(packageName));
+ }
+ return allTheRuleNames;
+ }
+
+ @Override
+ public Collection<String> getRuleNamesForPackage(String packageName) {
+ return ruleNames.get(packageName);
+ }
+
public void addPackageNames(List<String> packageNames) {
this.packageNames.addAll(packageNames);
}
|
013fd99d0dd0df30e0bb7fcb98e41cd1633319cb
|
hbase
|
HBASE-2513 hbase-2414 added bug where we'd- tight-loop if no root available--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@941546 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/core/src/main/java/org/apache/hadoop/hbase/master/RegionServerOperationQueue.java b/core/src/main/java/org/apache/hadoop/hbase/master/RegionServerOperationQueue.java
index c85c1414b086..3749805ccc2d 100644
--- a/core/src/main/java/org/apache/hadoop/hbase/master/RegionServerOperationQueue.java
+++ b/core/src/main/java/org/apache/hadoop/hbase/master/RegionServerOperationQueue.java
@@ -122,8 +122,8 @@ public synchronized ProcessingResultCode process(final HServerAddress rootRegion
// it first.
if (rootRegionLocation != null) {
op = delayedToDoQueue.poll();
- } else {
- // if there aren't any todo items in the queue, sleep for a bit.
+ }
+ if (op == null) {
try {
op = toDoQueue.poll(threadWakeFrequency, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
|
59d1720a5d1020d1167bea1a31b9616a685398a2
|
orientdb
|
Fixed bug on oidentifable but not odocument- fetching--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java b/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java
index d2d01458406..ecb2a3e5189 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java
@@ -298,9 +298,9 @@ private static void processRecord(final ORecordSchemaAware<?> record, final Obje
iContext.onAfterStandardField(fieldValue, fieldName, iUserObject);
} else {
try {
- if (!(fieldValue instanceof ODocument
- && (((ODocument) fieldValue).isEmbedded() || !((ODocument) fieldValue).getIdentity().isValid()) && iContext
- .fetchEmbeddedDocuments()) && !iFetchPlan.containsKey(fieldPath) && depthLevel > -1 && iCurrentLevel > depthLevel) {
+ if (!(!(fieldValue instanceof ODocument) || (((ODocument) fieldValue).isEmbedded() || !((ODocument) fieldValue)
+ .getIdentity().isValid()) && iContext.fetchEmbeddedDocuments())
+ && !iFetchPlan.containsKey(fieldPath) && depthLevel > -1 && iCurrentLevel > depthLevel) {
// MAX DEPTH REACHED: STOP TO FETCH THIS FIELD
continue;
}
@@ -329,13 +329,13 @@ private static void fetch(final ORecordSchemaAware<?> iRootRecord, final Object
}
if (fieldValue == null) {
iListener.processStandardField(iRootRecord, null, fieldName, iContext);
- } else if (fieldValue instanceof ODocument) {
- if (((ODocument) fieldValue).getClassName() != null
+ } else if (fieldValue instanceof OIdentifiable) {
+ if (fieldValue instanceof ODocument && ((ODocument) fieldValue).getClassName() != null
&& ((ODocument) fieldValue).getClassName().equals(OMVRBTreeRIDSet.OCLASS_NAME)) {
fetchCollection(iRootRecord, iUserObject, iFetchPlan, fieldValue, fieldName, currentLevel, iLevelFromRoot, fieldDepthLevel,
parsedRecords, iFieldPathFromRoot, iListener, iContext);
} else {
- fetchDocument(iRootRecord, iUserObject, iFetchPlan, (ODocument) fieldValue, fieldName, currentLevel, iLevelFromRoot,
+ fetchDocument(iRootRecord, iUserObject, iFetchPlan, (OIdentifiable) fieldValue, fieldName, currentLevel, iLevelFromRoot,
fieldDepthLevel, parsedRecords, iFieldPathFromRoot, iListener, iContext);
}
} else if (fieldValue instanceof Collection<?>) {
@@ -443,7 +443,7 @@ private static void fetchDocument(final ORecordSchemaAware<?> iRootRecord, final
final Map<String, Integer> iFetchPlan, final OIdentifiable fieldValue, final String fieldName, final int iCurrentLevel,
final int iLevelFromRoot, final int iFieldDepthLevel, final Map<ORID, Integer> parsedRecords,
final String iFieldPathFromRoot, final OFetchListener iListener, final OFetchContext iContext) throws IOException {
- final Integer fieldDepthLevel = parsedRecords.get(((ODocument) fieldValue).getIdentity());
+ final Integer fieldDepthLevel = parsedRecords.get(fieldValue.getIdentity());
if (!fieldValue.getIdentity().isValid() || (fieldDepthLevel != null && fieldDepthLevel.intValue() == iLevelFromRoot)) {
removeParsedFromMap(parsedRecords, fieldValue);
final ODocument linked = (ODocument) fieldValue;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/fetch/object/OObjectFetchListener.java b/core/src/main/java/com/orientechnologies/orient/core/fetch/object/OObjectFetchListener.java
index 4fe65d8485b..11738dfb141 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/fetch/object/OObjectFetchListener.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/fetch/object/OObjectFetchListener.java
@@ -45,8 +45,8 @@ public void processStandardCollectionValue(Object iFieldValue, OFetchContext iCo
public void parseLinked(final ORecordSchemaAware<?> iRootRecord, final OIdentifiable iLinked, final Object iUserObject,
final String iFieldName, final OFetchContext iContext) throws OFetchException {
final Class<?> type = OObjectSerializerHelper.getFieldType(iUserObject, iFieldName);
- if (Set.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)
- || type.isArray()) {
+ if (type == null || Set.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type)
+ || Map.class.isAssignableFrom(type) || type.isArray()) {
return;
} else if (iLinked instanceof ORecordSchemaAware
&& !(((OObjectFetchContext) iContext).getObj2RecHandler().existsUserObjectByRID(iLinked.getIdentity()))) {
|
9304ec103d2d104e11c9f96c87864d6f7a026b64
|
kotlin
|
wrongly added test removed (correct one was added- before by Zhenja)--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/SpecialFiles.java b/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/SpecialFiles.java
index 97335a21b9bba..9b160e88e0373 100644
--- a/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/SpecialFiles.java
+++ b/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/SpecialFiles.java
@@ -122,8 +122,6 @@ private static void fillExcludedFiles() {
excludedFiles.add("kt1779.kt"); // Bug KT-2202 - private fun tryToComputeNext() in AbstractIterator.kt
excludedFiles.add("kt344.jet"); // Bug KT-2251
excludedFiles.add("kt529.kt"); // Bug
-
- excludedFiles.add("kt2981.kt"); // with java
}
private SpecialFiles() {
|
6188550a4817e1f8f0f024034d0f0b5f03b6ecc3
|
spring-framework
|
ServletRequestAttributes skips well-known- immutable values when updating accessed session attributes--Issue: SPR-11738-
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.java b/spring-web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.java
index 8ad2fdb9979d..20a17c3fcebd 100644
--- a/spring-web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.java
+++ b/spring-web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.java
@@ -248,7 +248,7 @@ protected void updateAccessedSessionAttributes() {
String name = entry.getKey();
Object newValue = entry.getValue();
Object oldValue = this.session.getAttribute(name);
- if (oldValue == newValue) {
+ if (oldValue == newValue && !isImmutableSessionAttribute(name, newValue)) {
this.session.setAttribute(name, newValue);
}
}
@@ -260,6 +260,23 @@ protected void updateAccessedSessionAttributes() {
this.sessionAttributesToUpdate.clear();
}
+ /**
+ * Determine whether the given value is to be considered as an immutable session
+ * attribute, that is, doesn't have to be re-set via {@code session.setAttribute}
+ * since its value cannot meaningfully change internally.
+ * <p>The default implementation returns {@code true} for {@code String},
+ * {@code Character}, {@code Boolean} and {@code Number} values.
+ * @param name the name of the attribute
+ * @param value the corresponding value to check
+ * @return {@code true} if the value is to be considered as immutable for the
+ * purposes of session attribute management; {@code false} otherwise
+ * @see #updateAccessedSessionAttributes()
+ */
+ protected boolean isImmutableSessionAttribute(String name, Object value) {
+ return (value instanceof String || value instanceof Character ||
+ value instanceof Boolean || value instanceof Number);
+ }
+
/**
* Register the given callback as to be executed after session termination.
* <p>Note: The callback object should be serializable in order to survive
diff --git a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java
index 2e5688857f82..226b05d3d1ef 100644
--- a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java
+++ b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2013 the original author or authors.
+ * Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,10 +17,12 @@
package org.springframework.web.context.request;
import java.io.Serializable;
-
+import java.math.BigInteger;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
import org.junit.Test;
+
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpSession;
@@ -39,23 +41,12 @@ public class ServletRequestAttributesTests {
private static final Serializable VALUE = new Serializable() {
};
+
@Test(expected = IllegalArgumentException.class)
public void ctorRejectsNullArg() throws Exception {
new ServletRequestAttributes(null);
}
- @Test
- public void updateAccessedAttributes() throws Exception {
- MockHttpSession session = new MockHttpSession();
- session.setAttribute(KEY, VALUE);
- MockHttpServletRequest request = new MockHttpServletRequest();
- request.setSession(session);
- ServletRequestAttributes attrs = new ServletRequestAttributes(request);
- Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
- assertSame(VALUE, value);
- attrs.requestCompleted();
- }
-
@Test
public void setRequestScopedAttribute() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -162,4 +153,64 @@ public void removeSessionScopedAttributeDoesNotForceCreationOfSession() throws E
verify(request).getSession(false);
}
+ @Test
+ public void updateAccessedAttributes() throws Exception {
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ HttpSession session = mock(HttpSession.class);
+ when(request.getSession(anyBoolean())).thenReturn(session);
+ when(session.getAttribute(KEY)).thenReturn(VALUE);
+
+ ServletRequestAttributes attrs = new ServletRequestAttributes(request);
+ assertSame(VALUE, attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION));
+ attrs.requestCompleted();
+
+ verify(session, times(2)).getAttribute(KEY);
+ verify(session).setAttribute(KEY, VALUE);
+ verifyNoMoreInteractions(session);
+ }
+
+ @Test
+ public void skipImmutableString() {
+ doSkipImmutableValue("someString");
+ }
+
+ @Test
+ public void skipImmutableCharacter() {
+ doSkipImmutableValue(new Character('x'));
+ }
+
+ @Test
+ public void skipImmutableBoolean() {
+ doSkipImmutableValue(Boolean.TRUE);
+ }
+
+ @Test
+ public void skipImmutableInteger() {
+ doSkipImmutableValue(new Integer(1));
+ }
+
+ @Test
+ public void skipImmutableFloat() {
+ doSkipImmutableValue(new Float(1.1));
+ }
+
+ @Test
+ public void skipImmutableBigInteger() {
+ doSkipImmutableValue(new BigInteger("1"));
+ }
+
+ private void doSkipImmutableValue(Object immutableValue) {
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ HttpSession session = mock(HttpSession.class);
+ when(request.getSession(anyBoolean())).thenReturn(session);
+ when(session.getAttribute(KEY)).thenReturn(immutableValue);
+
+ ServletRequestAttributes attrs = new ServletRequestAttributes(request);
+ attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
+ attrs.requestCompleted();
+
+ verify(session, times(2)).getAttribute(KEY);
+ verifyNoMoreInteractions(session);
+ }
+
}
|
69c6e80acd16d0073400d78bd0e52caf44ef8f40
|
ReactiveX-RxJava
|
added variance to Action*
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java
index a688d03792..c24a7143f8 100644
--- a/rxjava-core/src/main/java/rx/Observable.java
+++ b/rxjava-core/src/main/java/rx/Observable.java
@@ -247,7 +247,7 @@ private Subscription protectivelyWrapAndSubscribe(Observer<T> o) {
return subscription.wrap(subscribe(new SafeObserver<T>(subscription, o)));
}
- public Subscription subscribe(final Action1<T> onNext) {
+ public Subscription subscribe(final Action1<? super T> onNext) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
@@ -278,11 +278,11 @@ public void onNext(T args) {
});
}
- public Subscription subscribe(final Action1<T> onNext, Scheduler scheduler) {
+ public Subscription subscribe(final Action1<? super T> onNext, Scheduler scheduler) {
return subscribeOn(scheduler).subscribe(onNext);
}
- public Subscription subscribe(final Action1<T> onNext, final Action1<Throwable> onError) {
+ public Subscription subscribe(final Action1<? super T> onNext, final Action1<? super Throwable> onError) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
@@ -316,11 +316,11 @@ public void onNext(T args) {
});
}
- public Subscription subscribe(final Action1<T> onNext, final Action1<Throwable> onError, Scheduler scheduler) {
+ public Subscription subscribe(final Action1<? super T> onNext, final Action1<? super Throwable> onError, Scheduler scheduler) {
return subscribeOn(scheduler).subscribe(onNext, onError);
}
- public Subscription subscribe(final Action1<T> onNext, final Action1<Throwable> onError, final Action0 onComplete) {
+ public Subscription subscribe(final Action1<? super T> onNext, final Action1<? super Throwable> onError, final Action0 onComplete) {
if (onNext == null) {
throw new IllegalArgumentException("onNext can not be null");
}
@@ -357,7 +357,7 @@ public void onNext(T args) {
});
}
- public Subscription subscribe(final Action1<T> onNext, final Action1<Throwable> onError, final Action0 onComplete, Scheduler scheduler) {
+ public Subscription subscribe(final Action1<? super T> onNext, final Action1<? super Throwable> onError, final Action0 onComplete, Scheduler scheduler) {
return subscribeOn(scheduler).subscribe(onNext, onError, onComplete);
}
diff --git a/rxjava-core/src/main/java/rx/observables/BlockingObservable.java b/rxjava-core/src/main/java/rx/observables/BlockingObservable.java
index 299c2fdc17..fa502843a4 100644
--- a/rxjava-core/src/main/java/rx/observables/BlockingObservable.java
+++ b/rxjava-core/src/main/java/rx/observables/BlockingObservable.java
@@ -355,7 +355,7 @@ private Subscription protectivelyWrapAndSubscribe(Observer<T> o) {
* @throws RuntimeException
* if an error occurs
*/
- public void forEach(final Action1<T> onNext) {
+ public void forEach(final Action1<? super T> onNext) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> exceptionFromOnError = new AtomicReference<Throwable>();
diff --git a/rxjava-core/src/main/java/rx/util/functions/Functions.java b/rxjava-core/src/main/java/rx/util/functions/Functions.java
index 867b47d114..7809b3240d 100644
--- a/rxjava-core/src/main/java/rx/util/functions/Functions.java
+++ b/rxjava-core/src/main/java/rx/util/functions/Functions.java
@@ -253,7 +253,7 @@ public Void call(Object... args) {
* @param f
* @return {@link FuncN}
*/
- public static <T0> FuncN<Void> fromAction(final Action1<T0> f) {
+ public static <T0> FuncN<Void> fromAction(final Action1<? super T0> f) {
return new FuncN<Void>() {
@SuppressWarnings("unchecked")
@@ -275,7 +275,7 @@ public Void call(Object... args) {
* @param f
* @return {@link FuncN}
*/
- public static <T0, T1> FuncN<Void> fromAction(final Action2<T0, T1> f) {
+ public static <T0, T1> FuncN<Void> fromAction(final Action2<? super T0, ? super T1> f) {
return new FuncN<Void>() {
@SuppressWarnings("unchecked")
@@ -297,7 +297,7 @@ public Void call(Object... args) {
* @param f
* @return {@link FuncN}
*/
- public static <T0, T1, T2> FuncN<Void> fromAction(final Action3<T0, T1, T2> f) {
+ public static <T0, T1, T2> FuncN<Void> fromAction(final Action3<? super T0, ? super T1, ? super T2> f) {
return new FuncN<Void>() {
@SuppressWarnings("unchecked")
|
1ffcd613de9c2fcc691b31355c635df9ffd6caca
|
drools
|
JBRULES-446 Support rulebase configuration via- jsr94 registerRuleExecutionSet properties--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@13123 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-jsr94/.classpath b/drools-jsr94/.classpath
index cab36f7a135..332f406afe5 100644
--- a/drools-jsr94/.classpath
+++ b/drools-jsr94/.classpath
@@ -1,22 +1,24 @@
-<classpath>
- <classpathentry kind="src" path="src/main/java"/>
- <classpathentry kind="src" path="src/main/resources" excluding="**/*.java"/>
- <classpathentry kind="src" path="src/test/java" output="target/test-classes"/>
- <classpathentry kind="src" path="src/test/resources" output="target/test-classes" excluding="**/*.java"/>
- <classpathentry kind="output" path="target/classes"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="var" path="M2_REPO/xpp3/xpp3/1.1.3.4.O/xpp3-1.1.3.4.O.jar"/>
- <classpathentry kind="src" path="/drools-core"/>
- <classpathentry kind="src" path="/drools-compiler"/>
- <classpathentry kind="var" path="M2_REPO/xerces/xercesImpl/2.4.0/xercesImpl-2.4.0.jar"/>
- <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/>
- <classpathentry kind="var" path="M2_REPO/org/mvel/mvel14/1.2beta27/mvel14-1.2beta27.jar"/>
- <classpathentry kind="var" path="M2_REPO/jsr94/jsr94/1.1/jsr94-1.1.jar"/>
- <classpathentry kind="var" path="M2_REPO/org/eclipse/jdt/core/3.2.3.v_686_R32x/core-3.2.3.v_686_R32x.jar"/>
- <classpathentry kind="var" path="M2_REPO/janino/janino/2.5.7/janino-2.5.7.jar"/>
- <classpathentry kind="var" path="M2_REPO/org/antlr/antlr-runtime/3.0/antlr-runtime-3.0.jar"/>
- <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-sigtest/1.1/jsr94-sigtest-1.1.jar"/>
- <classpathentry kind="var" path="M2_REPO/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar"/>
- <classpathentry kind="var" path="M2_REPO/xstream/xstream/1.1.3/xstream-1.1.3.jar"/>
- <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-tck/1.0.3/jsr94-tck-1.0.3.jar"/>
-</classpath>
\ No newline at end of file
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src/main/java"/>
+ <classpathentry excluding="**/*.java" kind="src" path="src/main/resources"/>
+ <classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
+ <classpathentry excluding="**/*.java" kind="src" output="target/test-classes" path="src/test/resources"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="var" path="M2_REPO/xpp3/xpp3/1.1.3.4.O/xpp3-1.1.3.4.O.jar"/>
+ <classpathentry kind="src" path="/drools-core"/>
+ <classpathentry kind="src" path="/drools-compiler"/>
+ <classpathentry kind="var" path="M2_REPO/xerces/xercesImpl/2.4.0/xercesImpl-2.4.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/mvel/mvel14/1.2beta27/mvel14-1.2beta27.jar"/>
+ <classpathentry kind="var" path="M2_REPO/jsr94/jsr94/1.1/jsr94-1.1.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/eclipse/jdt/core/3.2.3.v_686_R32x/core-3.2.3.v_686_R32x.jar"/>
+ <classpathentry kind="var" path="M2_REPO/janino/janino/2.5.7/janino-2.5.7.jar"/>
+ <classpathentry kind="var" path="M2_REPO/org/antlr/antlr-runtime/3.0/antlr-runtime-3.0.jar"/>
+ <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-sigtest/1.1/jsr94-sigtest-1.1.jar"/>
+ <classpathentry kind="var" path="M2_REPO/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar"/>
+ <classpathentry kind="var" path="M2_REPO/xstream/xstream/1.1.3/xstream-1.1.3.jar"/>
+ <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-tck/1.0.3/jsr94-tck-1.0.3.jar"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/drools-decisiontables"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java
index 1de15d3560b..0c4b40f427d 100644
--- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java
+++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java
@@ -37,4 +37,18 @@ private Constants() {
/** <code>RuleExecutionSet</code> description constant. */
public static final String RES_DESCRIPTION = "javax.rules.admin.RuleExecutionSet.description";
+
+ public static final String RES_SOURCE = "javax.rules.admin.RuleExecutionSet.source";
+
+ public static final String RES_SOURCE_TYPE_XML = "javax.rules.admin.RuleExecutionSet.source.xml";
+
+ public static final String RES_SOURCE_TYPE_DECISION_TABLE = "javax.rules.admin.RuleExecutionSet.source.decisiontable";
+
+ public static final String RES_DSRL = "javax.rules.admin.RuleExecutionSet.dsrl";
+
+ /** <code>RuleExecutionSet</code> rulebase config constant. */
+ public static final String RES_RULEBASE_CONFIG = "javax.rules.admin.RuleExecutionSet.ruleBaseConfiguration";
+
+ /** <code>RuleExecutionSet</code> package builder config constant. */
+ public static final String RES_PACKAGEBUILDER_CONFIG = "javax.rules.admin.RuleExecutionSet.ruleBaseConfiguration";
}
diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java
index 252567344e4..78cba0e8602 100644
--- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java
+++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java
@@ -30,6 +30,10 @@
import org.drools.IntegrationException;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
+import org.drools.compiler.PackageBuilderConfiguration;
+import org.drools.decisiontable.InputType;
+import org.drools.decisiontable.SpreadsheetCompiler;
+import org.drools.jsr94.rules.Constants;
import org.drools.rule.Package;
/**
@@ -73,8 +77,23 @@ public LocalRuleExecutionSetProviderImpl() {
* @return The created <code>RuleExecutionSet</code>.
*/
public RuleExecutionSet createRuleExecutionSet(final InputStream ruleExecutionSetStream,
- final Map properties) throws RuleExecutionSetCreateException {
- return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties);
+ final Map properties) throws RuleExecutionSetCreateException {
+ if ( properties != null ) {
+ String source = ( String ) properties.get( Constants.RES_SOURCE );
+ if ( source == null ) {
+ // support legacy name
+ source = ( String ) properties.get( "source" );
+ }
+ if ( source != null && source.equals( Constants.RES_SOURCE_TYPE_DECISION_TABLE ) ) {
+ final SpreadsheetCompiler converter = new SpreadsheetCompiler();
+ final String drl = converter.compile( ruleExecutionSetStream,
+ InputType.XLS );
+ return createRuleExecutionSet( new StringReader( drl ), properties );
+ } else {
+ return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties);
+ }
+ } else
+ return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties);
}
@@ -99,37 +118,56 @@ public RuleExecutionSet createRuleExecutionSet(final InputStream ruleExecutionSe
public RuleExecutionSet createRuleExecutionSet(final Reader ruleExecutionSetReader,
final Map properties) throws RuleExecutionSetCreateException {
try {
- final PackageBuilder builder = new PackageBuilder();
- Object dsl = null;
+ PackageBuilderConfiguration config= null;
+
+ if ( properties != null ) {
+ config = (PackageBuilderConfiguration) properties.get( Constants.RES_PACKAGEBUILDER_CONFIG );
+ }
+
+ PackageBuilder builder = null;
+ if ( config != null ) {
+ builder = new PackageBuilder(config);
+ } else {
+ builder = new PackageBuilder();
+ }
+
+ Object dsrl = null;
String source = null;
if ( properties != null ) {
- dsl = properties.get( "dsl" );
- source = ( String ) properties.get( "source" );
+ dsrl = properties.get( Constants.RES_DSRL );
+ if ( dsrl == null ) {
+ // check for old legacy name ending
+ dsrl = properties.get( "dsl" );
+ }
+ source = ( String ) properties.get( Constants.RES_SOURCE );
+ if ( source == null ) {
+ // check for old legacy name ending
+ source = ( String ) properties.get( "source" );
+ }
}
if ( source == null ) {
source = "drl";
- }
-
+ }
- if ( dsl == null ) {
- if ( source.equals( "xml" ) ) {
+ if ( dsrl == null ) {
+ if ( source.equals( Constants.RES_SOURCE_TYPE_XML ) || source.equals( "xml" ) ) {
builder.addPackageFromXml( ruleExecutionSetReader );
} else {
builder.addPackageFromDrl( ruleExecutionSetReader );
}
} else {
- if ( source.equals( "xml" ) ) {
+ if ( source.equals( Constants.RES_SOURCE_TYPE_XML ) || source.equals( "xml" ) ) {
// xml cannot specify a dsl
builder.addPackageFromXml( ruleExecutionSetReader );
} else {
- if ( dsl instanceof Reader ) {
+ if ( dsrl instanceof Reader ) {
builder.addPackageFromDrl( ruleExecutionSetReader,
- (Reader) dsl );
+ (Reader) dsrl );
} else {
builder.addPackageFromDrl( ruleExecutionSetReader,
- new StringReader( (String) dsl ) );
+ new StringReader( (String) dsrl ) );
}
}
}
diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java
index 6da640ecd37..3636b65ff09 100644
--- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java
+++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java
@@ -26,9 +26,11 @@
import org.drools.IntegrationException;
import org.drools.RuleBase;
+import org.drools.RuleBaseConfiguration;
import org.drools.RuleIntegrationException;
import org.drools.StatefulSession;
import org.drools.StatelessSession;
+import org.drools.jsr94.rules.Constants;
import org.drools.jsr94.rules.Jsr94FactHandleFactory;
import org.drools.rule.Package;
import org.drools.rule.Rule;
@@ -114,9 +116,17 @@ public class RuleExecutionSetImpl
}
this.pkg = pkg;
this.description = pkg.getName();//..getDocumentation( );
-
- final org.drools.reteoo.ReteooRuleBase ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(),
- new Jsr94FactHandleFactory() );
+
+ RuleBaseConfiguration config = ( RuleBaseConfiguration ) this.properties.get( Constants.RES_RULEBASE_CONFIG );
+ org.drools.reteoo.ReteooRuleBase ruleBase;
+ if ( config != null ) {
+ ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(),
+ config,
+ new Jsr94FactHandleFactory() );
+ } else {
+ ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(),
+ new Jsr94FactHandleFactory() );
+ }
ruleBase.addPackage( pkg );
this.ruleBase = ruleBase;
diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java b/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java
new file mode 100644
index 00000000000..d6ae471da6e
--- /dev/null
+++ b/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java
@@ -0,0 +1,45 @@
+package org.drools.decisiontable;
+
+/*
+ * Copyright 2005 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.
+ */
+
+public class Cheese {
+ private String type;
+ private int price;
+
+ public Cheese() {
+
+ }
+ public Cheese(final String type,
+ final int price) {
+ super();
+ this.type = type;
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return this.price;
+ }
+
+ public String getType() {
+ return this.type;
+ }
+
+ public void setPrice(final int price) {
+ this.price = price;
+ }
+
+}
\ No newline at end of file
diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java b/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java
new file mode 100644
index 00000000000..b467a800e0a
--- /dev/null
+++ b/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java
@@ -0,0 +1,93 @@
+package org.drools.decisiontable;
+
+/*
+ * Copyright 2005 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.
+ */
+
+public class Person {
+ private String name;
+ private String likes;
+ private int age;
+
+ private char sex;
+
+ private boolean alive;
+
+ private String status;
+
+ public Person() {
+
+ }
+ public Person(final String name) {
+ this( name,
+ "",
+ 0 );
+ }
+
+ public Person(final String name,
+ final String likes) {
+ this( name,
+ likes,
+ 0 );
+ }
+
+ public Person(final String name,
+ final String likes,
+ final int age) {
+ this.name = name;
+ this.likes = likes;
+ this.age = age;
+ }
+
+ public String getStatus() {
+ return this.status;
+ }
+
+ public void setStatus(final String status) {
+ this.status = status;
+ }
+
+ public String getLikes() {
+ return this.likes;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public int getAge() {
+ return this.age;
+ }
+
+ public boolean isAlive() {
+ return this.alive;
+ }
+
+ public void setAlive(final boolean alive) {
+ this.alive = alive;
+ }
+
+ public char getSex() {
+ return this.sex;
+ }
+
+ public void setSex(final char sex) {
+ this.sex = sex;
+ }
+
+ public String toString() {
+ return "[Person name='" + this.name + "']";
+ }
+}
\ No newline at end of file
diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java b/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java
new file mode 100644
index 00000000000..4a7c9e302e0
--- /dev/null
+++ b/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java
@@ -0,0 +1,91 @@
+package org.drools.decisiontable;
+
+/*
+ * Copyright 2005 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.
+ */
+
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.rules.RuleRuntime;
+import javax.rules.RuleServiceProvider;
+import javax.rules.RuleServiceProviderManager;
+import javax.rules.RuleSession;
+import javax.rules.StatefulRuleSession;
+import javax.rules.admin.LocalRuleExecutionSetProvider;
+import javax.rules.admin.RuleAdministrator;
+import javax.rules.admin.RuleExecutionSet;
+
+import junit.framework.TestCase;
+
+import org.acme.insurance.launcher.PricingRuleLauncher;
+import org.drools.RuleBase;
+import org.drools.RuleBaseFactory;
+import org.drools.WorkingMemory;
+import org.drools.compiler.PackageBuilder;
+import org.drools.jsr94.rules.Constants;
+import org.drools.jsr94.rules.ExampleRuleEngineFacade;
+import org.drools.jsr94.rules.RuleEngineTestBase;
+import org.drools.jsr94.rules.RuleServiceProviderImpl;
+import org.drools.rule.Package;
+
+public class SpreadsheetIntegrationTest extends TestCase {
+
+ public void testExecute() throws Exception {
+ Map properties = new HashMap();
+ properties.put( Constants.RES_SOURCE,
+ Constants.RES_SOURCE_TYPE_DECISION_TABLE );
+
+ RuleServiceProviderManager.registerRuleServiceProvider( ExampleRuleEngineFacade.RULE_SERVICE_PROVIDER,
+ RuleServiceProviderImpl.class );
+
+ RuleServiceProvider ruleServiceProvider = RuleServiceProviderManager.getRuleServiceProvider( ExampleRuleEngineFacade.RULE_SERVICE_PROVIDER );
+ RuleAdministrator ruleAdministrator = ruleServiceProvider.getRuleAdministrator();
+ LocalRuleExecutionSetProvider ruleSetProvider = ruleAdministrator.getLocalRuleExecutionSetProvider( null );
+
+ RuleExecutionSet ruleExecutionSet = ruleSetProvider.createRuleExecutionSet( SpreadsheetIntegrationTest.class.getResourceAsStream( "IntegrationExampleTest.xls" ),
+ properties );
+
+ ruleAdministrator.registerRuleExecutionSet( "IntegrationExampleTest.xls",
+ ruleExecutionSet,
+ properties );
+
+ properties.clear();
+ final List list = new ArrayList();
+ properties.put( "list",
+ list );
+
+ RuleRuntime ruleRuntime = ruleServiceProvider.getRuleRuntime();
+ StatefulRuleSession session = (StatefulRuleSession) ruleRuntime.createRuleSession( "IntegrationExampleTest.xls",
+ properties,
+ RuleRuntime.STATEFUL_SESSION_TYPE );
+
+ //ASSERT AND FIRE
+ session.addObject( new Cheese( "stilton",
+ 42 ) );
+ session.addObject( new Person( "michael",
+ "stilton",
+ 42 ) );
+
+ session.executeRules();
+ assertEquals( 1,
+ list.size() );
+
+ }
+
+}
\ No newline at end of file
diff --git a/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java b/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java
index 18128d1e679..f735ca4ee47 100644
--- a/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java
+++ b/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java
@@ -86,7 +86,7 @@ public ExampleRuleEngineFacade() throws Exception {
this.ruleAdministrator = this.ruleServiceProvider.getRuleAdministrator();
this.ruleSetProvider = this.ruleAdministrator.getLocalRuleExecutionSetProvider( null );
- }
+ }
public void addRuleExecutionSet(final String bindUri,
final InputStream resourceAsStream) throws Exception {
diff --git a/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls b/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls
new file mode 100644
index 00000000000..adf5d9829a8
Binary files /dev/null and b/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls differ
|
642ed17a4808e36f1458546cc66d52e212cc5acf
|
hadoop
|
HADOOP-6951. Distinct minicluster services (e.g.- NN and JT) overwrite each other's service policies. Contributed by Aaron T.- Myers.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1002896 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 3850d6ecad5d9..0590fa7e4b981 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -250,6 +250,9 @@ Trunk (unreleased changes)
HADOOP-6940. RawLocalFileSystem's markSupported method misnamed markSupport.
(Tom White via eli).
+ HADOOP-6951. Distinct minicluster services (e.g. NN and JT) overwrite each
+ other's service policies. (Aaron T. Myers via tomwhite)
+
Release 0.21.0 - Unreleased
INCOMPATIBLE CHANGES
diff --git a/src/java/org/apache/hadoop/ipc/Server.java b/src/java/org/apache/hadoop/ipc/Server.java
index e8ee049cb6025..01d76d886ae4f 100644
--- a/src/java/org/apache/hadoop/ipc/Server.java
+++ b/src/java/org/apache/hadoop/ipc/Server.java
@@ -60,6 +60,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.io.BytesWritable;
@@ -78,6 +79,7 @@
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.apache.hadoop.security.authorize.AuthorizationException;
+import org.apache.hadoop.security.authorize.PolicyProvider;
import org.apache.hadoop.security.authorize.ServiceAuthorizationManager;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.security.token.SecretManager;
@@ -182,6 +184,7 @@ public static String getRemoteAddress() {
private Configuration conf;
private SecretManager<TokenIdentifier> secretManager;
+ private ServiceAuthorizationManager serviceAuthorizationManager = new ServiceAuthorizationManager();
private int maxQueueSize;
private final int maxRespSize;
@@ -239,6 +242,22 @@ public RpcMetrics getRpcMetrics() {
return rpcMetrics;
}
+ /**
+ * Refresh the service authorization ACL for the service handled by this server.
+ */
+ public void refreshServiceAcl(Configuration conf, PolicyProvider provider) {
+ serviceAuthorizationManager.refresh(conf, provider);
+ }
+
+ /**
+ * Returns a handle to the serviceAuthorizationManager (required in tests)
+ * @return instance of ServiceAuthorizationManager for this server
+ */
+ @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
+ public ServiceAuthorizationManager getServiceAuthorizationManager() {
+ return serviceAuthorizationManager;
+ }
+
/** A call queued for handling. */
private static class Call {
private int id; // the client's call id
@@ -1652,7 +1671,7 @@ public void authorize(UserGroupInformation user,
throw new AuthorizationException("Unknown protocol: " +
connection.getProtocol());
}
- ServiceAuthorizationManager.authorize(user, protocol, getConf(), hostname);
+ serviceAuthorizationManager.authorize(user, protocol, getConf(), hostname);
}
}
diff --git a/src/java/org/apache/hadoop/security/authorize/ServiceAuthorizationManager.java b/src/java/org/apache/hadoop/security/authorize/ServiceAuthorizationManager.java
index 3f78cf9ef2e4f..a73fa2cd9fec5 100644
--- a/src/java/org/apache/hadoop/security/authorize/ServiceAuthorizationManager.java
+++ b/src/java/org/apache/hadoop/security/authorize/ServiceAuthorizationManager.java
@@ -20,6 +20,7 @@
import java.io.IOException;
import java.util.IdentityHashMap;
import java.util.Map;
+import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -43,7 +44,7 @@ public class ServiceAuthorizationManager {
private static final Log LOG = LogFactory
.getLog(ServiceAuthorizationManager.class);
- private static Map<Class<?>, AccessControlList> protocolToAcl =
+ private Map<Class<?>, AccessControlList> protocolToAcl =
new IdentityHashMap<Class<?>, AccessControlList>();
/**
@@ -73,7 +74,7 @@ public class ServiceAuthorizationManager {
* @param hostname fully qualified domain name of the client
* @throws AuthorizationException on authorization failure
*/
- public static void authorize(UserGroupInformation user,
+ public void authorize(UserGroupInformation user,
Class<?> protocol,
Configuration conf,
String hostname
@@ -129,7 +130,7 @@ public static void authorize(UserGroupInformation user,
AUDITLOG.info(AUTHZ_SUCCESSFULL_FOR + user + " for protocol="+protocol);
}
- public static synchronized void refresh(Configuration conf,
+ public synchronized void refresh(Configuration conf,
PolicyProvider provider) {
// Get the system property 'hadoop.policy.file'
String policyFile =
@@ -158,4 +159,9 @@ public static synchronized void refresh(Configuration conf,
// Flip to the newly parsed permissions
protocolToAcl = newAcls;
}
+
+ // Package-protected for use in tests.
+ Set<Class<?>> getProtocolsWithAcls() {
+ return protocolToAcl.keySet();
+ }
}
diff --git a/src/test/core/org/apache/hadoop/ipc/TestRPC.java b/src/test/core/org/apache/hadoop/ipc/TestRPC.java
index c87391e4d58b8..9ca6a6e936142 100644
--- a/src/test/core/org/apache/hadoop/ipc/TestRPC.java
+++ b/src/test/core/org/apache/hadoop/ipc/TestRPC.java
@@ -41,7 +41,6 @@
import org.apache.hadoop.security.authorize.AuthorizationException;
import org.apache.hadoop.security.authorize.PolicyProvider;
import org.apache.hadoop.security.authorize.Service;
-import org.apache.hadoop.security.authorize.ServiceAuthorizationManager;
import org.apache.hadoop.security.AccessControlException;
import static org.mockito.Mockito.*;
@@ -364,11 +363,11 @@ public Service[] getServices() {
}
private void doRPCs(Configuration conf, boolean expectFailure) throws Exception {
- ServiceAuthorizationManager.refresh(conf, new TestPolicyProvider());
-
Server server = RPC.getServer(TestProtocol.class,
new TestImpl(), ADDRESS, 0, 5, true, conf, null);
+ server.refreshServiceAcl(conf, new TestPolicyProvider());
+
TestProtocol proxy = null;
server.start();
|
130a91a2d393bc9a0128cc2fafa3e52c6528e005
|
Mylyn Reviews
|
bug 380843: index commit messages of changesets
Added an initial implementation of an index for the scm repositories.
The commit message, the revision and repository url are indexed, which
allows to search for all commits for a task in specific repositories.
Currently, the index is rebuild at the startup, which limits its use
only for smaller git projects. This should be fixed in the near future,
when a notification of repository changes is implemented, as well as
a mechanism, which determines if the repository has changed while
eclipse was not running.
Change-Id: If7aebd06dd9ca19090b2af3b5f447fe8454df7d0
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF
index fafe890a..c20a3f9c 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF
@@ -2,14 +2,19 @@ Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %Bundle-Name
Bundle-SymbolicName: org.eclipse.mylyn.versions.tasks.mapper.generic;singleton:=true
-Bundle-Version: 0.1.0.qualifier
+Bundle-Version: 1.0.0.qualifier
Bundle-RequiredExecutionEnvironment: J2SE-1.5
Require-Bundle: org.eclipse.mylyn.tasks.core;bundle-version="3.8.0",
org.eclipse.mylyn.versions.core;bundle-version="1.0.0",
org.eclipse.mylyn.versions.tasks.ui,
org.eclipse.core.runtime,
org.eclipse.core.resources,
+ org.eclipse.mylyn.versions.tasks.core;bundle-version="1.0.0",
org.eclipse.mylyn.tasks.ui;bundle-version="3.8.0",
- org.eclipse.mylyn.versions.tasks.core;bundle-version="1.0.0"
-Export-Package: org.eclipse.mylyn.versions.tasks.mapper.generic;x-internal:=true
+ org.apache.lucene.core;bundle-version="2.9.1",
+ org.eclipse.team.core;bundle-version="3.6.0"
+Export-Package: org.eclipse.mylyn.versions.tasks.mapper.generic;x-internal:=true,
+ org.eclipse.mylyn.versions.tasks.mapper.internal
Bundle-Vendor: %Bundle-Vendor
+Bundle-ActivationPolicy: lazy
+Bundle-Activator: org.eclipse.mylyn.versions.tasks.mapper.internal.RepositoryIndexerPlugin
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/pom.xml b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/pom.xml
index 44e42970..71e4552a 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/pom.xml
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/pom.xml
@@ -5,10 +5,11 @@
<parent>
<artifactId>mylyn-reviews-tasks-parent</artifactId>
<groupId>org.eclipse.mylyn.reviews</groupId>
- <version>0.7.0-SNAPSHOT</version>
+ <version>1.0.0-SNAPSHOT</version>
</parent>
+ <groupId>org.eclipse.mylyn.reviews</groupId>
<artifactId>org.eclipse.mylyn.versions.tasks.mapper.generic</artifactId>
- <version>0.1.0-SNAPSHOT</version>
+ <version>1.0.0-SNAPSHOT</version>
<packaging>eclipse-plugin</packaging>
<build>
<plugins>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java
index 6c3d230b..3cbe23b9 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java
@@ -10,22 +10,34 @@
*******************************************************************************/
package org.eclipse.mylyn.versions.tasks.mapper.generic;
+import java.io.File;
+import java.io.NotSerializableException;
+import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IStorage;
+import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.versions.core.ChangeSet;
import org.eclipse.mylyn.versions.core.ScmCore;
import org.eclipse.mylyn.versions.core.ScmRepository;
import org.eclipse.mylyn.versions.core.spi.ScmConnector;
import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping;
+import org.eclipse.mylyn.versions.tasks.mapper.internal.ChangeSetIndexer;
+import org.eclipse.mylyn.versions.tasks.mapper.internal.RepositoryIndexerPlugin;
import org.eclipse.mylyn.versions.tasks.ui.AbstractChangesetMappingProvider;
+import org.eclipse.team.core.history.IFileRevision;
+import org.eclipse.team.core.history.ITag;
+import org.eclipse.team.core.history.provider.FileRevision;
/**
*
@@ -36,44 +48,98 @@ public class GenericTaskChangesetMapper extends
AbstractChangesetMappingProvider {
private IConfiguration configuration;
+ private IChangeSetIndexSearcher indexSearch;
public GenericTaskChangesetMapper() {
this.configuration = new EclipsePluginConfiguration();
-
+ this.indexSearch = RepositoryIndexerPlugin.getDefault().getIndexer();
}
public GenericTaskChangesetMapper(IConfiguration configuration) {
this.configuration = configuration;
}
- public void getChangesetsForTask(IChangeSetMapping mapping,
- IProgressMonitor monitor) throws CoreException {
+ public void getChangesetsForTask(final IChangeSetMapping mapping,
+ final IProgressMonitor monitor) throws CoreException {
ITask task = mapping.getTask();
if (task == null)
throw new IllegalArgumentException("task must not be null");
+
List<ScmRepository> repos = getRepositoriesFor(task);
- for (ScmRepository repo : repos) {
-
- List<ChangeSet> allChangeSets = repo.getConnector().getChangeSets(
- repo, new NullProgressMonitor());
- for (ChangeSet cs : allChangeSets) {
- if (changeSetMatches(cs, task)) {
- mapping.addChangeSet(cs);
- }
- }
+ for (final ScmRepository repo : repos) {
+ indexSearch.search(task, repo.getUrl(), 10, new IChangeSetCollector() {
+
+ public void collect(String revision, String repositoryUrl) throws CoreException {
+ mapping.addChangeSet(getChangeset(revision, repo,monitor));
+ }
+ });
}
}
- private boolean changeSetMatches(ChangeSet cs, ITask task) {
- // FIXME better detection
- return cs.getMessage().contains(task.getTaskKey())
- || cs.getMessage().contains(task.getUrl());
+ class FileRevision implements IFileRevision{
+ private String contentIdentifier;
+
+ public FileRevision(String contentIdentifier){
+ this.contentIdentifier=contentIdentifier;
+ }
+
+ public IStorage getStorage(IProgressMonitor monitor)
+ throws CoreException {
+ throw new UnsupportedOperationException();
+ }
+
+ public String getName() {
+ throw new UnsupportedOperationException();
+ }
+
+ public URI getURI() {
+ throw new UnsupportedOperationException();
+ }
+
+ public long getTimestamp() {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean exists() {
+ throw new UnsupportedOperationException();
+ }
+
+ public String getContentIdentifier() {
+ return contentIdentifier;
+ }
+
+ public String getAuthor() {
+ throw new UnsupportedOperationException();
+ }
+
+ public String getComment() {
+ throw new UnsupportedOperationException();
+ }
+
+ public ITag[] getBranches() {
+ throw new UnsupportedOperationException();
+ }
+
+ public ITag[] getTags() {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isPropertyMissing() {
+ throw new UnsupportedOperationException();
+ }
+
+ public IFileRevision withAllProperties(IProgressMonitor monitor)
+ throws CoreException {
+ throw new UnsupportedOperationException();
+ }}
+
+ protected ChangeSet getChangeset(String revision, ScmRepository repo,IProgressMonitor monitor) throws CoreException {
+ return repo.getConnector().getChangeSet(repo, new FileRevision(revision), monitor);
}
private List<ScmRepository> getRepositoriesFor(ITask task)
throws CoreException {
-
Set<ScmRepository> repos = new HashSet<ScmRepository>();
List<IProject> projects = configuration.getProjectsForTaskRepository(
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetCollector.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetCollector.java
new file mode 100644
index 00000000..394c83d6
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetCollector.java
@@ -0,0 +1,23 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.generic;
+
+import org.eclipse.core.runtime.CoreException;
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public interface IChangeSetCollector {
+
+ void collect(String revision, String repositoryUrl) throws CoreException;
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetIndexSearcher.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetIndexSearcher.java
new file mode 100644
index 00000000..c616f7ac
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetIndexSearcher.java
@@ -0,0 +1,26 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.generic;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.mylyn.tasks.core.ITask;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public interface IChangeSetIndexSearcher {
+
+ public int search(ITask task, String scmRepositoryUrl, int resultsLimit,
+ IChangeSetCollector collector) throws CoreException;
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/TaskChangeSet.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetIndexer.java
similarity index 65%
rename from tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/TaskChangeSet.java
rename to tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetIndexer.java
index c3c69a1a..1ea42546 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/TaskChangeSet.java
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetIndexer.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
* 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
@@ -9,8 +9,6 @@
* Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.versions.tasks.mapper.generic;
-
-import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.versions.core.ChangeSet;
/**
@@ -18,20 +16,8 @@
* @author Kilian Matt
*
*/
-public class TaskChangeSet {
- private ChangeSet changeset;
- private ITask task;
-
- public TaskChangeSet(ITask task, ChangeSet cs) {
- this.task = task;
- this.changeset = cs;
- }
+public interface IChangeSetIndexer {
- public ChangeSet getChangeset() {
- return changeset;
- }
+ public void index(ChangeSet changeset);
- public ITask getTask() {
- return task;
- }
}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetSource.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetSource.java
new file mode 100644
index 00000000..ab0a6334
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IChangeSetSource.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.generic;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public interface IChangeSetSource{
+
+ void fetchAllChangesets(IProgressMonitor monitor, IChangeSetIndexer indexer) throws CoreException;
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java
new file mode 100644
index 00000000..24e7ed98
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexer.java
@@ -0,0 +1,163 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+import org.apache.lucene.LucenePackage;
+import org.apache.lucene.analysis.KeywordAnalyzer;
+import org.apache.lucene.analysis.PerFieldAnalyzerWrapper;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriter.MaxFieldLength;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.DisjunctionMaxQuery;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.PhraseQuery;
+import org.apache.lucene.search.PrefixQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.ScoreDoc;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.search.spans.SpanOrQuery;
+import org.apache.lucene.search.spans.SpanQuery;
+import org.apache.lucene.search.spans.SpanTermQuery;
+import org.apache.lucene.store.NIOFSDirectory;
+import org.apache.lucene.util.Version;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetCollector;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexSearcher;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexer;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetSource;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class ChangeSetIndexer implements IChangeSetIndexSearcher {
+
+ private IChangeSetSource source;
+
+ private File indexDirectory;
+ private IndexWriter indexWriter;
+ private IndexReader indexReader;
+
+ public ChangeSetIndexer(File directory, IChangeSetSource source) {
+ this.indexDirectory = directory;
+ this.source = source;
+ }
+
+ public void reindex(IProgressMonitor monitor) {
+ try {
+ PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.LUCENE_CURRENT));
+ analyzer.addAnalyzer(IndexedFields.REPOSITORY.getIndexKey(), new KeywordAnalyzer());
+ indexWriter = new IndexWriter(new NIOFSDirectory(indexDirectory),
+ analyzer, true, MaxFieldLength.UNLIMITED);
+
+ IChangeSetIndexer indexer = new IChangeSetIndexer() {
+
+ public void index(ChangeSet changeset) {
+ try {
+ Document document = new Document();
+ for (IndexedFields field : IndexedFields.values()) {
+ document.add(new Field(field.getIndexKey(), field.getAccessor().getValue(changeset),
+ Store.YES, Field.Index.ANALYZED));
+ }
+ indexWriter.addDocument(document);
+ } catch (IOException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+ };
+ source.fetchAllChangesets(monitor, indexer);
+ indexWriter.close();
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ public int search(ITask task, String scmRepositoryUrl, int resultsLimit, IChangeSetCollector collector) throws CoreException {
+ int count = 0;
+ IndexReader indexReader = getIndexReader();
+ if (indexReader != null) {
+ IndexSearcher indexSearcher = new IndexSearcher(indexReader);
+ try {
+ Query query = createQuery(task,scmRepositoryUrl);
+ TopDocs results = indexSearcher.search(query, resultsLimit);
+ for (ScoreDoc scoreDoc : results.scoreDocs) {
+ Document document = indexReader.document(scoreDoc.doc);
+ count++;
+ if(count > resultsLimit)
+ break;
+
+
+ String revision = document.getField(IndexedFields.REVISION.getIndexKey()).stringValue();
+ String repositoryUrl =document.getField(IndexedFields.REPOSITORY.getIndexKey()).stringValue();
+
+ collector.collect(revision, repositoryUrl);
+ }
+ } catch (IOException e) {
+// StatusHandler.log(new Status(IStatus.ERROR, org.eclipse.mylyn.versions.tasks.ui.internal.TaPLUGIN_ID,
+//"Unexpected failure within task list index", e)); //$NON-NLS-1$
+ } finally {
+ try {
+ indexSearcher.close();
+ } catch (IOException e) {
+ // ignore
+ }
+ }
+ }
+ return count;
+
+ }
+
+ private Query createQuery(ITask task, String repositoryUrl) {
+ BooleanQuery query =new BooleanQuery();
+ query.setMinimumNumberShouldMatch(1);
+ query.add(new TermQuery(new Term(IndexedFields.REPOSITORY.getIndexKey(),repositoryUrl)),Occur.MUST);
+ query.add(new PrefixQuery(new Term(IndexedFields.COMMIT_MESSAGE.getIndexKey(),task.getUrl())),Occur.SHOULD);
+ query.add(new PrefixQuery(new Term(IndexedFields.COMMIT_MESSAGE.getIndexKey(),task.getTaskId())),Occur.SHOULD);
+ return query;
+ }
+
+
+ private IndexReader getIndexReader() {
+ try {
+ synchronized (this) {
+ if (indexReader == null) {
+ indexReader = IndexReader.open(new NIOFSDirectory(indexDirectory), true);
+ }
+ return indexReader;
+ }
+ } catch (CorruptIndexException e) {
+ // rebuild index
+ } catch (FileNotFoundException e) {
+ // rebuild index
+ } catch (IOException e) {
+ // ignore
+ }
+ return null;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangesetPropertyAccess.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangesetPropertyAccess.java
new file mode 100644
index 00000000..91c5ed75
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangesetPropertyAccess.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public enum ChangesetPropertyAccess {
+
+ REVISION() {
+ public String getValue(ChangeSet cs) {
+ return cs.getId();
+ }
+ },
+ REPOSITORY() {
+ public String getValue(ChangeSet cs) {
+ return cs.getRepository().getUrl();
+ }
+ },
+ COMMIT_MESSAGE() {
+ public String getValue(ChangeSet cs) {
+ return cs.getMessage();
+ }
+ };
+
+ public abstract String getValue(ChangeSet cs);
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseWorkspaceRepositorySource.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseWorkspaceRepositorySource.java
new file mode 100644
index 00000000..5a05735e
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/EclipseWorkspaceRepositorySource.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+import org.eclipse.mylyn.versions.core.ScmCore;
+import org.eclipse.mylyn.versions.core.ScmRepository;
+import org.eclipse.mylyn.versions.core.spi.ScmConnector;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexer;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetSource;
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class EclipseWorkspaceRepositorySource implements IChangeSetSource {
+ public void fetchAllChangesets(IProgressMonitor monitor,
+ IChangeSetIndexer indexer) throws CoreException {
+ Set<ScmRepository> repositories = new HashSet<ScmRepository>();
+
+ for (IProject project : ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects()) {
+ ScmConnector connector = ScmCore.getConnector(project);
+ if(connector!=null) {
+ repositories.add(connector.getRepository(project, monitor));
+ }
+ }
+
+ for (ScmRepository repo : repositories) {
+ List<ChangeSet> changesets;
+ changesets = repo.getConnector().getChangeSets(repo, monitor);
+ for (ChangeSet cs : changesets) {
+ indexer.index(cs);
+ }
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFields.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFields.java
new file mode 100644
index 00000000..82f38d72
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFields.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+import org.eclipse.core.runtime.Assert;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public enum IndexedFields {
+ REVISION("revision", ChangesetPropertyAccess.REVISION),
+ REPOSITORY("repositoryUrl", ChangesetPropertyAccess.REPOSITORY),
+ COMMIT_MESSAGE("message", ChangesetPropertyAccess.COMMIT_MESSAGE),
+ ;
+
+ private final String indexKey;
+ private final ChangesetPropertyAccess accessor;
+
+ IndexedFields(String indexKey, ChangesetPropertyAccess accessor) {
+ this.indexKey = indexKey;
+ this.accessor = accessor;
+ Assert.isNotNull(indexKey);
+ Assert.isNotNull(accessor);
+ }
+
+ public String getIndexKey() {
+ return indexKey;
+ }
+
+ public ChangesetPropertyAccess getAccessor() {
+ return accessor;
+ }
+
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexer.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexer.java
new file mode 100644
index 00000000..ecea2908
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexer.java
@@ -0,0 +1,50 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexSearcher;
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class RepositoryIndexer {
+
+ private IndexRepositoryJob repoSyncJob;
+
+ public RepositoryIndexer() {
+
+ repoSyncJob = new IndexRepositoryJob();
+ repoSyncJob.schedule(10000);
+ }
+
+ private static class IndexRepositoryJob extends Job {
+
+ public IndexRepositoryJob() {
+ super("Indexing repositories.");
+ }
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ IChangeSetIndexSearcher indexer = RepositoryIndexerPlugin.getDefault().getIndexer();
+ ((ChangeSetIndexer)indexer).reindex(monitor);
+
+ return new Status(IStatus.OK, RepositoryIndexerPlugin.PLUGIN_ID,
+ "Indexing finished");
+ }
+
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPlugin.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPlugin.java
new file mode 100644
index 00000000..72872649
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/internal/RepositoryIndexerPlugin.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+
+import java.io.File;
+
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexSearcher;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class RepositoryIndexerPlugin implements BundleActivator {
+ private static RepositoryIndexerPlugin instance;
+ public static final String PLUGIN_ID="org.eclipse.mylyn.versions.tasks.mapper";
+
+ private RepositoryIndexer synchronizer;
+ private IChangeSetIndexSearcher indexSearch;
+
+ public RepositoryIndexerPlugin() {
+ instance = this;
+ }
+
+ public static RepositoryIndexerPlugin getDefault() {
+ return instance;
+ }
+
+ public void start(BundleContext context) throws Exception {
+ synchronizer= new RepositoryIndexer();
+
+ File file = new File(TasksUiPlugin.getDefault().getDataDirectory(),".changeSetIndex");
+ indexSearch=new ChangeSetIndexer(file,new EclipseWorkspaceRepositorySource());
+ }
+ public IChangeSetIndexSearcher getIndexer(){
+ return indexSearch;
+ }
+
+ public void stop(BundleContext context) throws Exception {
+ this.instance=null;
+
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/.classpath b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/.classpath
new file mode 100644
index 00000000..ad32c83a
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/.project b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/.project
new file mode 100644
index 00000000..6f619447
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.mylyn.versions.tasks.mapper.tests</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..ad4ffef5
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/META-INF/MANIFEST.MF
@@ -0,0 +1,12 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Task Mapper Tests
+Bundle-SymbolicName: org.eclipse.mylyn.versions.tasks.mapper.tests
+Bundle-Version: 1.0.0.qualifier
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Require-Bundle: org.junit;bundle-version="4.8.2",
+ org.eclipse.mylyn.versions.tasks.mapper.generic;bundle-version="0.1.0",
+ org.eclipse.mylyn.versions.core;bundle-version="1.0.0",
+ org.eclipse.core.runtime;bundle-version="3.7.0",
+ org.eclipse.mylyn.tasks.core;bundle-version="3.8.0",
+ org.eclipse.mylyn.tasks.tests;bundle-version="3.8.0"
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/about.html b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/about.html
new file mode 100644
index 00000000..d774b07c
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/about.html
@@ -0,0 +1,27 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<html>
+<head>
+<title>About</title>
+<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
+</head>
+<body lang="EN-US">
+<h2>About This Content</h2>
+
+<p>June 25, 2008</p>
+<h3>License</h3>
+
+<p>The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise
+indicated below, the Content is provided to you under the terms and conditions of the
+Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available
+at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
+For purposes of the EPL, "Program" will mean the Content.</p>
+
+<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
+being redistributed by another party ("Redistributor") and different terms and conditions may
+apply to your use of any object code in the Content. Check the Redistributor's license that was
+provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
+indicated below, the terms and conditions of the EPL still apply to any source code in the Content
+and such source code may be obtained at <a href="/">http://www.eclipse.org</a>.</p>
+
+</body>
+</html>
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/build.properties b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/build.properties
new file mode 100644
index 00000000..34d2e4d2
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/build.properties
@@ -0,0 +1,4 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/pom.xml b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/pom.xml
new file mode 100644
index 00000000..f747fa78
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/pom.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <artifactId>mylyn-reviews-tasks-parent</artifactId>
+ <groupId>org.eclipse.mylyn.reviews</groupId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+ <groupId>org.eclipse.mylyn.reviews</groupId>
+ <artifactId>org.eclipse.mylyn.versions.tasks.mapper.tests</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ <packaging>eclipse-plugin</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.eclipse.tycho</groupId>
+ <artifactId>tycho-source-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-pmd-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IndexTest.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IndexTest.java
new file mode 100644
index 00000000..311cb582
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IndexTest.java
@@ -0,0 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.generic;
+import org.junit.Test;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class IndexTest {
+
+ @Test
+ public void testIndexCreation(){
+
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexerTest.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexerTest.java
new file mode 100644
index 00000000..f909b736
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangeSetIndexerTest.java
@@ -0,0 +1,150 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.tests.connector.MockTask;
+import org.eclipse.mylyn.versions.core.Change;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+import org.eclipse.mylyn.versions.core.ScmRepository;
+import org.eclipse.mylyn.versions.core.ScmUser;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetCollector;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetIndexer;
+import org.eclipse.mylyn.versions.tasks.mapper.generic.IChangeSetSource;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class ChangeSetIndexerTest {
+
+ protected static final String REPO_URL = "http://git.eclipse.org/c/mylyn/org.eclipse.mylyn.versions.git";
+ private ChangeSetIndexer indexer;
+
+ @Before
+ public void prepareIndex() {
+ File dir = createTempDirectoryForIndex();
+
+ indexer = new ChangeSetIndexer(dir, createIndexerSource());
+ indexer.reindex(new NullProgressMonitor());
+ }
+
+ @Test
+ public void testSingleResult() throws CoreException{
+ ITask task = new MockTask(REPO_URL,"1");
+ task.setUrl(REPO_URL+"/1");
+ ExpectingChangeSetCollector collectors= new ExpectingChangeSetCollector();
+ collectors.expect("1", REPO_URL);
+ assertEquals(1, indexer.search(task,REPO_URL, 5,collectors));
+ collectors.verifyAllExpectations();
+ }
+ @Test
+ public void testMultipleResults() throws CoreException{
+ ITask task = new MockTask(REPO_URL,"2");
+ task.setUrl(REPO_URL+"/1");
+ ExpectingChangeSetCollector collectors= new ExpectingChangeSetCollector();
+ collectors.expect("2", REPO_URL);
+ collectors.expect("3", REPO_URL);
+ assertEquals(2, indexer.search(task,REPO_URL, 5,collectors));
+ collectors.verifyAllExpectations();
+ }
+
+
+ static class ExpectingChangeSetCollector implements IChangeSetCollector{
+ private List<Pair> expected=new LinkedList<Pair>();
+ void expect(String revision, String repositoryUrl){
+ this.expected.add(new Pair(revision,repositoryUrl));
+ }
+
+ public void verifyAllExpectations() {
+ if(expected.size()>0){
+ fail( expected.size() + " expected changesets not collected");
+ }
+ }
+
+ private static class Pair{
+ Pair(String rev, String repoUrl){
+ this.rev=rev;
+ this.repoUrl=repoUrl;
+ }
+ final String rev;
+ final String repoUrl;
+ }
+
+ @Override
+ public void collect(String revision, String repositoryUrl)
+ throws CoreException {
+ if(expected.size()==0){
+ fail("unexpected changeset");
+ }
+ Pair first = expected.remove(0);
+ assertEquals(first.rev, revision);
+ assertEquals(first.repoUrl, repositoryUrl);
+ }
+ }
+ private ListChangeSetSource createIndexerSource() {
+ ScmRepository repository=new ScmRepository(null, "", REPO_URL);
+ ScmRepository otherRepo=new ScmRepository(null, "", "http://git.eclipse.org/c/mylyn/org.eclipse.mylyn.reviews.git");
+ ListChangeSetSource source = new ListChangeSetSource(Arrays.asList(
+ new ChangeSet(new ScmUser("test", "Name", "[email protected]"), new Date(), "1", "commit message 1", repository, new ArrayList<Change>()),
+ new ChangeSet(new ScmUser("test", "Name", "[email protected]"), new Date(), "1", "commit message 1", otherRepo, new ArrayList<Change>()),
+ new ChangeSet(new ScmUser("test", "Name", "[email protected]"), new Date(), "2", "commit message 2", repository, new ArrayList<Change>()),
+ new ChangeSet(new ScmUser("test", "Name", "[email protected]"), new Date(), "3", "commit message 2", repository, new ArrayList<Change>())
+ ));
+ return source;
+ }
+
+ class ListChangeSetSource implements IChangeSetSource {
+ private List<ChangeSet> changesets;
+ public ListChangeSetSource(List<ChangeSet> changesets){
+ this.changesets=changesets;
+ }
+ @Override
+ public void fetchAllChangesets(IProgressMonitor monitor,
+ IChangeSetIndexer indexer) throws CoreException {
+ for(ChangeSet changeset : changesets){
+ indexer.index(changeset);
+ }
+ }
+ }
+
+ private File createTempDirectoryForIndex() {
+ File dir = null;
+ try {
+ dir = File.createTempFile("test","dasd");
+ dir.delete();
+ dir.mkdir();
+ dir.deleteOnExit();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return dir;
+ }
+
+
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangesetPropertyAccessTest.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangesetPropertyAccessTest.java
new file mode 100644
index 00000000..1ba01552
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/ChangesetPropertyAccessTest.java
@@ -0,0 +1,58 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.Date;
+
+import org.eclipse.mylyn.versions.core.Change;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+import org.eclipse.mylyn.versions.core.ScmRepository;
+import org.junit.Before;
+import org.junit.Test;
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class ChangesetPropertyAccessTest {
+
+ private ChangeSet cs;
+ final String expectedId = "123";
+ final String expectedMessage = "Sample Message";
+ final String expectedRepository = "git://git.eclipse.org/c/mylyn/org.eclipse.versions.git";
+
+ @Before
+ public void prepare() {
+ cs = new ChangeSet(null, new Date(), expectedId, expectedMessage, new ScmRepository(null, "test", expectedRepository),
+ new ArrayList<Change>());
+ }
+
+ @Test
+ public void testRevisionAccess() {
+ assertEquals(expectedId, ChangesetPropertyAccess.REVISION.getValue(cs));
+ }
+
+ @Test
+ public void testCommitMessageAccess() {
+ assertEquals(expectedMessage,
+ ChangesetPropertyAccess.COMMIT_MESSAGE.getValue(cs));
+ }
+
+ @Test
+ public void testRepositoryAccess() {
+ assertEquals(expectedRepository,
+ ChangesetPropertyAccess.REPOSITORY.getValue(cs));
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFieldsTest.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFieldsTest.java
new file mode 100644
index 00000000..c815b332
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/internal/IndexedFieldsTest.java
@@ -0,0 +1,40 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.internal;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.junit.Test;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class IndexedFieldsTest {
+
+ @Test
+ public void indexKeyIsUnique(){
+ Set<String > fields = new TreeSet<String>();
+ for(IndexedFields f : IndexedFields.values()){
+ String indexKey = f.getIndexKey();
+ assertNotNull(indexKey);
+ if(fields.contains(indexKey)){
+ fail("Duplicate Index key " + indexKey);
+ }
+ fields.add(indexKey);
+ }
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
index 85ce1716..ae1f7447 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
@@ -16,3 +16,4 @@ Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: J2SE-1.5
Export-Package: org.eclipse.mylyn.versions.tasks.ui;x-internal:=true
Bundle-Vendor: %Bundle-Vendor
+Bundle-Activator: org.eclipse.mylyn.versions.tasks.ui.internal.TaskVersionsUiPlugin
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskVersionsUiPlugin.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskVersionsUiPlugin.java
new file mode 100644
index 00000000..1946de09
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskVersionsUiPlugin.java
@@ -0,0 +1,33 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.ui.internal;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class TaskVersionsUiPlugin extends AbstractUIPlugin {
+ private static TaskVersionsUiPlugin instance;
+ public static final String PLUGIN_ID="org.eclipse.mylyn.versions.tasks.ui";
+
+ public TaskVersionsUiPlugin() {
+ instance = this;
+ }
+
+ public static TaskVersionsUiPlugin getDefault() {
+ return instance;
+ }
+
+}
diff --git a/tbr/pom.xml b/tbr/pom.xml
index 1b587c31..2f936dcf 100644
--- a/tbr/pom.xml
+++ b/tbr/pom.xml
@@ -18,5 +18,7 @@
<module>org.eclipse.mylyn.reviews.tasks.ui</module>
<module>org.eclipse.mylyn.versions.tasks.core</module>
<module>org.eclipse.mylyn.versions.tasks.ui</module>
+ <module>org.eclipse.mylyn.versions.tasks.mapper.generic</module>
+ <module>org.eclipse.mylyn.versions.tasks.mapper.tests</module>
</modules>
</project>
|
f84e57e1c6ae9b09dc5fab974a8b9010c04147ef
|
genericworkflownodes$genericknimenodes
|
be passed to the node generator which is then used as the directory in where to look for plugin.properties. Otherwise the current working directory is used.
- The payload directory must now reside in the plugin.properties'
|
p
|
https://github.com/genericworkflownodes/genericknimenodes
|
diff --git a/src/org/ballproject/knime/base/config/CTDNodeConfigurationReader.java b/src/org/ballproject/knime/base/config/CTDNodeConfigurationReader.java
index 9f560b27..58398164 100644
--- a/src/org/ballproject/knime/base/config/CTDNodeConfigurationReader.java
+++ b/src/org/ballproject/knime/base/config/CTDNodeConfigurationReader.java
@@ -52,492 +52,440 @@
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
-public class CTDNodeConfigurationReader implements NodeConfigurationReader
-{
-
- private static Logger log = Logger.getLogger(CTDNodeConfigurationReader.class.getCanonicalName());
-
+public class CTDNodeConfigurationReader implements NodeConfigurationReader {
+
+ private static Logger log = Logger
+ .getLogger(CTDNodeConfigurationReader.class.getCanonicalName());
+
private Document doc;
private DefaultNodeConfiguration config = new DefaultNodeConfiguration();
-
- public CTDNodeConfigurationReader()
- {
+
+ public CTDNodeConfigurationReader() {
}
-
-
+
protected String SECTION_NODE_NAME = "NODE";
- protected String INPUTFILE_TAG = "input file";
- protected String OUTPUTFILE_TAG = "output file";
-
+ protected String INPUTFILE_TAG = "input file";
+ protected String OUTPUTFILE_TAG = "output file";
+
protected Set<String> captured_ports = new HashSet<String>();
-
- private static List<Port> in_ports;
- private static List<Port> out_ports;
-
- private void readPorts() throws Exception
- {
- in_ports = new ArrayList<Port>();
+
+ private static List<Port> in_ports;
+ private static List<Port> out_ports;
+
+ private void readPorts() throws Exception {
+ in_ports = new ArrayList<Port>();
out_ports = new ArrayList<Port>();
-
- Node node = doc.selectSingleNode("/tool/PARAMETERS");
+
+ Node node = this.doc.selectSingleNode("/tool/PARAMETERS");
Element root = (Element) node;
- processIOPorts(root);
-
- config.setInports((Port[]) in_ports.toArray(new Port[in_ports.size()]));
- config.setOutports((Port[]) out_ports.toArray(new Port[out_ports.size()]));
+ this.processIOPorts(root);
+
+ this.config.setInports(in_ports.toArray(new Port[in_ports.size()]));
+ this.config.setOutports(out_ports.toArray(new Port[out_ports.size()]));
}
-
-
+
@SuppressWarnings("unchecked")
- public void processIOPorts(Element root) throws Exception
- {
- List<Node> items = root.selectNodes("//ITEM[contains(@tags,'"+OUTPUTFILE_TAG+"')]");
- for(Node n: items)
- {
- createPortFromNode(n, false);
- }
- items = root.selectNodes("//ITEM[contains(@tags,'"+INPUTFILE_TAG+"')]");
- for(Node n: items)
- {
- createPortFromNode(n, false);
- }
- items = root.selectNodes("//ITEMLIST[contains(@tags,'"+INPUTFILE_TAG+"')]");
- for(Node n: items)
- {
- createPortFromNode(n, true);
- }
- items = root.selectNodes("//ITEMLIST[contains(@tags,'"+OUTPUTFILE_TAG+"')]");
- for(Node n: items)
- {
- createPortFromNode(n, true);
+ public void processIOPorts(Element root) throws Exception {
+ List<Node> items = root.selectNodes("//ITEM[contains(@tags,'"
+ + this.OUTPUTFILE_TAG + "')]");
+ for (Node n : items) {
+ this.createPortFromNode(n, false);
+ }
+ items = root.selectNodes("//ITEM[contains(@tags,'" + this.INPUTFILE_TAG
+ + "')]");
+ for (Node n : items) {
+ this.createPortFromNode(n, false);
+ }
+ items = root.selectNodes("//ITEMLIST[contains(@tags,'"
+ + this.INPUTFILE_TAG + "')]");
+ for (Node n : items) {
+ this.createPortFromNode(n, true);
+ }
+ items = root.selectNodes("//ITEMLIST[contains(@tags,'"
+ + this.OUTPUTFILE_TAG + "')]");
+ for (Node n : items) {
+ this.createPortFromNode(n, true);
}
}
-
+
@SuppressWarnings("unchecked")
- public void readParameters() throws Exception
- {
- Node root = doc.selectSingleNode("/tool/PARAMETERS");
- List<Node> items = root.selectNodes("//ITEM[not(contains(@tags,'"+OUTPUTFILE_TAG+"')) and not(contains(@tags,'"+INPUTFILE_TAG+"'))]");
- for(Node n: items)
- {
- processItem(n);
- }
- items = root.selectNodes("//ITEMLIST[not(contains(@tags,'"+OUTPUTFILE_TAG+"')) and not(contains(@tags,'"+INPUTFILE_TAG+"'))]");
- for(Node n: items)
- {
- processMultiItem(n);
+ public void readParameters() throws Exception {
+ Node root = this.doc.selectSingleNode("/tool/PARAMETERS");
+ List<Node> items = root.selectNodes("//ITEM[not(contains(@tags,'"
+ + this.OUTPUTFILE_TAG + "')) and not(contains(@tags,'"
+ + this.INPUTFILE_TAG + "'))]");
+ for (Node n : items) {
+ this.processItem(n);
+ }
+ items = root.selectNodes("//ITEMLIST[not(contains(@tags,'"
+ + this.OUTPUTFILE_TAG + "')) and not(contains(@tags,'"
+ + this.INPUTFILE_TAG + "'))]");
+ for (Node n : items) {
+ this.processMultiItem(n);
}
}
-
- public String getPath(Node n)
- {
-
+
+ public String getPath(Node n) {
+
List<String> path_nodes = new ArrayList<String>();
- while(n!=null&&!n.getName().equals("PARAMETERS"))
- {
+ while (n != null && !n.getName().equals("PARAMETERS")) {
path_nodes.add(n.valueOf("@name"));
n = n.getParent();
}
-
+
Collections.reverse(path_nodes);
-
-
+
String ret = "";
int N = path_nodes.size();
- for(int i=0;i<N;i++)
- {
- if(i==N-1)
- ret+=path_nodes.get(i);
- else
- ret+=path_nodes.get(i)+".";
+ for (int i = 0; i < N; i++) {
+ if (i == N - 1) {
+ ret += path_nodes.get(i);
+ } else {
+ ret += path_nodes.get(i) + ".";
+ }
}
return ret;
}
-
- private void createPortFromNode(Node node, boolean multi) throws Exception
- {
-
+
+ private void createPortFromNode(Node node, boolean multi) throws Exception {
+
Element elem = (Element) node;
-
- String name = node.valueOf("@name");
- String descr = node.valueOf("@description");
- String tags = node.valueOf("@tags");
-
- if(name.equals("write_ini")||name.equals("write_par")||name.equals("par")||name.equals("help"))
- {
+
+ String name = node.valueOf("@name");
+ String descr = node.valueOf("@description");
+ String tags = node.valueOf("@tags");
+
+ if (name.equals("write_ini") || name.equals("write_par")
+ || name.equals("par") || name.equals("help"))
return;
- }
-
-
+
Port port = new Port();
-
-
+
port.setMultiFile(multi);
-
- if(tags.contains(INPUTFILE_TAG)||tags.contains(OUTPUTFILE_TAG))
- {
- String[] file_extensions = null;
-
- if(elem.attributeValue("supported_formats")==null)
- {
- if(elem.attributeValue("restrictions")!=null)
- {
- String formats = node.valueOf("@restrictions");
+
+ if (tags.contains(this.INPUTFILE_TAG)
+ || tags.contains(this.OUTPUTFILE_TAG)) {
+ String[] file_extensions = null;
+
+ if (elem.attributeValue("supported_formats") == null) {
+ if (elem.attributeValue("restrictions") != null) {
+ String formats = node.valueOf("@restrictions");
file_extensions = formats.split(",");
- for(int i=0;i<file_extensions.length;i++)
- {
- file_extensions[i] = file_extensions[i].replace("*.", "");
+ for (int i = 0; i < file_extensions.length; i++) {
+ file_extensions[i] = file_extensions[i].replace("*.",
+ "");
}
- }
- else
- throw new Exception("i/o item '"+elem.attributeValue("name")+"' with missing attribute supported_formats detected");
- }
- else
- {
- String formats = node.valueOf("@supported_formats");
+ } else
+ throw new Exception(
+ "i/o item '"
+ + elem.attributeValue("name")
+ + "' with missing attribute supported_formats detected");
+ } else {
+ String formats = node.valueOf("@supported_formats");
file_extensions = formats.split(",");
- for(int i=0;i<file_extensions.length;i++)
+ for (int i = 0; i < file_extensions.length; i++) {
file_extensions[i] = file_extensions[i].trim();
+ }
}
-
-
-
-
- String path = getPath(node);
+ String path = this.getPath(node);
port.setName(path);
-
+
port.setDescription(descr);
-
+
boolean optional = true;
- if(tags.contains("mandatory")||tags.contains("required"))
+ if (tags.contains("mandatory") || tags.contains("required")) {
optional = false;
- else
+ } else {
optional = true;
+ }
port.setOptional(optional);
-
-
- for(String mt : file_extensions)
- {
+
+ for (String mt : file_extensions) {
port.addMimeType(new MIMEtype(mt.trim()));
}
-
+
}
- if(tags.contains(OUTPUTFILE_TAG))
- {
+ if (tags.contains(this.OUTPUTFILE_TAG)) {
out_ports.add(port);
- captured_ports.add(port.getName());
-
- if(multi)
- {
- String path = getPath(node);
- FileListParameter param = new FileListParameter(name, new ArrayList<String>());
+ this.captured_ports.add(port.getName());
+
+ if (multi) {
+ String path = this.getPath(node);
+ FileListParameter param = new FileListParameter(name,
+ new ArrayList<String>());
param.setPort(port);
param.setDescription(descr);
param.setIsOptional(false);
- config.addParameter(path, param);
+ this.config.addParameter(path, param);
}
}
- if(tags.contains(INPUTFILE_TAG))
- {
+ if (tags.contains(this.INPUTFILE_TAG)) {
in_ports.add(port);
- captured_ports.add(port.getName());
- }
-
+ this.captured_ports.add(port.getName());
+ }
+
}
-
- public void processItem(Node elem) throws Exception
- {
+
+ public void processItem(Node elem) throws Exception {
String name = elem.valueOf("@name");
-
- String path = getPath(elem);
-
- if(captured_ports.contains(path))
+
+ String path = this.getPath(elem);
+
+ if (this.captured_ports.contains(path))
return;
-
- if(name.equals("write_ini")||name.equals("write_par")||name.equals("par")||name.equals("help"))
- {
+
+ if (name.equals("write_ini") || name.equals("write_par")
+ || name.equals("par") || name.equals("help"))
return;
- }
-
- Parameter<?> param = getParameterFromNode(elem);
- config.addParameter(path, param);
+
+ Parameter<?> param = this.getParameterFromNode(elem);
+ this.config.addParameter(path, param);
}
-
- public void processMultiItem(Node elem) throws Exception
- {
+
+ public void processMultiItem(Node elem) throws Exception {
String name = elem.valueOf("@name");
-
- String path = getPath(elem);
-
- if(captured_ports.contains(path))
+
+ String path = this.getPath(elem);
+
+ if (this.captured_ports.contains(path))
return;
-
- if(name.equals("write_ini")||name.equals("write_par")||name.equals("par")||name.equals("help"))
- {
+
+ if (name.equals("write_ini") || name.equals("write_par")
+ || name.equals("par") || name.equals("help"))
return;
- }
-
- Parameter<?> param = getMultiParameterFromNode(elem);
- config.addParameter(path, param);
+
+ Parameter<?> param = this.getMultiParameterFromNode(elem);
+ this.config.addParameter(path, param);
}
-
- private void readDescription() throws Exception
- {
- Node node = doc.selectSingleNode("/tool");
- if(node==null)
+
+ private void readDescription() throws Exception {
+ Node node = this.doc.selectSingleNode("/tool");
+ if (node == null)
throw new Exception("CTD has no root named tool");
-
- String lstatus = node.valueOf("@status");
- if(lstatus!=null && lstatus.equals(""))
+
+ String lstatus = node.valueOf("@status");
+ if (lstatus != null && lstatus.equals(""))
throw new Exception("CTD has no status");
-
- config.setStatus(lstatus);
-
- node = doc.selectSingleNode("/tool/name");
- if(node==null)
+
+ this.config.setStatus(lstatus);
+
+ node = this.doc.selectSingleNode("/tool/name");
+ if (node == null)
throw new Exception("CTD has no tool name");
- String name = node.valueOf("text()");
- if(name.equals(""))
+ String name = node.valueOf("text()");
+ if (name.equals(""))
throw new Exception("CTD has no tool name");
- config.setName(name);
-
-
-
- node = doc.selectSingleNode("/tool/description");
- String sdescr = "";
- if(node!=null)
- sdescr = node.valueOf("text()");
- config.setDescription(sdescr);
-
- node = doc.selectSingleNode("/tool/path");
- String spath = "";
- if(node!=null)
- spath = node.valueOf("text()");
-
- config.setCommand(spath);
-
- node = doc.selectSingleNode("/tool/manual");
+ this.config.setName(name);
+
+ node = this.doc.selectSingleNode("/tool/description");
+ String sdescr = "";
+ if (node != null) {
+ sdescr = node.valueOf("text()");
+ }
+ this.config.setDescription(sdescr);
+
+ node = this.doc.selectSingleNode("/tool/path");
+ String spath = "";
+ if (node != null) {
+ spath = node.valueOf("text()");
+ }
+
+ this.config.setCommand(spath);
+
+ node = this.doc.selectSingleNode("/tool/manual");
String ldescr = "";
- if(node!=null)
- ldescr = node.valueOf("text()");
- config.setManual(ldescr);
-
- node = doc.selectSingleNode("/tool/version");
+ if (node != null) {
+ ldescr = node.valueOf("text()");
+ }
+ this.config.setManual(ldescr);
+
+ node = this.doc.selectSingleNode("/tool/version");
String lversion = "";
- if(node!=null)
- lversion = node.valueOf("text()");
- config.setVersion(lversion);
-
- node = doc.selectSingleNode("/tool/docurl");
- String docurl = "";
- if(node!=null)
- docurl = node.valueOf("text()");
- config.setDocUrl(docurl);
-
- node = doc.selectSingleNode("/tool/category");
+ if (node != null) {
+ lversion = node.valueOf("text()");
+ }
+ this.config.setVersion(lversion);
+
+ node = this.doc.selectSingleNode("/tool/docurl");
+ String docurl = "";
+ if (node != null) {
+ docurl = node.valueOf("text()");
+ }
+ this.config.setDocUrl(docurl);
+
+ node = this.doc.selectSingleNode("/tool/category");
String cat = "";
- if(node!=null)
- cat = node.valueOf("text()");
- config.setCategory(cat);
+ if (node != null) {
+ cat = node.valueOf("text()");
+ }
+ this.config.setCategory(cat);
}
-
- private Parameter<?> getParameterFromNode(Node node) throws Exception
- {
+
+ private Parameter<?> getParameterFromNode(Node node) throws Exception {
Parameter<?> ret = null;
- String type = node.valueOf("@type");
- String name = node.valueOf("@name");
- String value = node.valueOf("@value");
+ String type = node.valueOf("@type");
+ String name = node.valueOf("@name");
+ String value = node.valueOf("@value");
String restrs = node.valueOf("@restrictions");
- String descr = node.valueOf("@description");
- String tags = node.valueOf("@tags");
-
- if (type.toLowerCase().equals("double")||type.toLowerCase().equals("float"))
- {
- ret = processDoubleParameter(name, value, restrs, tags);
- }
- else
- {
- if(type.toLowerCase().equals("int"))
- {
- ret = processIntParameter(name, value, restrs, tags);
- }
- else
- {
- if(type.toLowerCase().equals("string"))
- {
- ret = processStringParameter(name, value, restrs, tags);
+ String descr = node.valueOf("@description");
+ String tags = node.valueOf("@tags");
+
+ if (type.toLowerCase().equals("double")
+ || type.toLowerCase().equals("float")) {
+ ret = this.processDoubleParameter(name, value, restrs, tags);
+ } else {
+ if (type.toLowerCase().equals("int")) {
+ ret = this.processIntParameter(name, value, restrs, tags);
+ } else {
+ if (type.toLowerCase().equals("string")) {
+ ret = this
+ .processStringParameter(name, value, restrs, tags);
}
}
}
-
+
ret.setDescription(descr);
Set<String> tagset = tokenSet(tags);
-
- if(tagset.contains("mandatory")||tagset.contains("required"))
+
+ if (tagset.contains("mandatory") || tagset.contains("required")) {
ret.setIsOptional(false);
-
- if(tagset.contains("advanced"))
+ }
+
+ if (tagset.contains("advanced")) {
ret.setAdvanced(true);
-
+ }
+
return ret;
}
-
- private Parameter<?> getMultiParameterFromNode(Node node) throws Exception
- {
- String type = node.valueOf("@type");
- String name = node.valueOf("@name");
- String value = node.valueOf("@value");
+
+ private Parameter<?> getMultiParameterFromNode(Node node) throws Exception {
+ String type = node.valueOf("@type");
+ String name = node.valueOf("@name");
+ String value = node.valueOf("@value");
String restrs = node.valueOf("@restrictions");
- String descr = node.valueOf("@description");
- String tags = node.valueOf("@tags");
-
+ String descr = node.valueOf("@description");
+ String tags = node.valueOf("@tags");
+
Set<String> tagset = tokenSet(tags);
-
+
@SuppressWarnings("unchecked")
- List<Node> subnodes = node.selectNodes("LISTITEM");
-
- List<String> values = new ArrayList<String>();
- for(Node n: subnodes)
- {
+ List<Node> subnodes = node.selectNodes("LISTITEM");
+
+ List<String> values = new ArrayList<String>();
+ for (Node n : subnodes) {
values.add(n.valueOf("@value"));
}
-
+
Parameter<?> param = null;
-
- if (type.toLowerCase().equals("double")||type.toLowerCase().equals("float"))
- {
- param = processDoubleListParameter(name, values, restrs, tags);
- }
- else
- {
- if(type.toLowerCase().equals("int"))
- {
- param = processIntListParameter(name, values, restrs, tags);
- }
- else
- {
- if(type.toLowerCase().equals("string"))
- {
- param = processStringListParameter(name, values, restrs, tags);
+ if (type.toLowerCase().equals("double")
+ || type.toLowerCase().equals("float")) {
+ param = this.processDoubleListParameter(name, values, restrs, tags);
+ } else {
+ if (type.toLowerCase().equals("int")) {
+ param = this
+ .processIntListParameter(name, values, restrs, tags);
+ } else {
+ if (type.toLowerCase().equals("string")) {
+ param = this.processStringListParameter(name, values,
+ restrs, tags);
}
}
}
-
+
param.setDescription(descr);
-
- if(tagset.contains("mandatory")||tagset.contains("required"))
+
+ if (tagset.contains("mandatory") || tagset.contains("required")) {
param.setIsOptional(false);
+ }
- if(tagset.contains("advanced"))
+ if (tagset.contains("advanced")) {
param.setAdvanced(true);
-
+ }
+
return param;
}
- private Parameter<?> processStringListParameter(String name, List<String> values, String restrs, String tags)
- {
- return new StringListParameter(name,values);
+ private Parameter<?> processStringListParameter(String name,
+ List<String> values, String restrs, String tags) {
+ return new StringListParameter(name, values);
}
-
- private Parameter<?> processIntListParameter(String name, List<String> values, String restrs, String tags)
- {
+ private Parameter<?> processIntListParameter(String name,
+ List<String> values, String restrs, String tags) {
List<Integer> vals = new ArrayList<Integer>();
- for(String cur_val: values)
- {
+ for (String cur_val : values) {
vals.add(Integer.parseInt(cur_val));
}
-
- IntegerListParameter ret = new IntegerListParameter(name,vals);
-
+
+ IntegerListParameter ret = new IntegerListParameter(name, vals);
+
Integer[] bounds = new Integer[2];
- getIntegerBoundsFromRestrictions( restrs, bounds);
+ this.getIntegerBoundsFromRestrictions(restrs, bounds);
ret.setLowerBound(bounds[0]);
ret.setUpperBound(bounds[1]);
-
+
return ret;
}
-
- private Parameter<?> processDoubleListParameter(String name, List<String> values, String restrs, String tags)
- {
+ private Parameter<?> processDoubleListParameter(String name,
+ List<String> values, String restrs, String tags) {
List<Double> vals = new ArrayList<Double>();
- for(String cur_val: values)
- {
+ for (String cur_val : values) {
vals.add(Double.parseDouble(cur_val));
}
-
- DoubleListParameter ret = new DoubleListParameter(name,vals);
-
+
+ DoubleListParameter ret = new DoubleListParameter(name, vals);
+
Double[] bounds = new Double[2];
- getDoubleBoundsFromRestrictions( restrs, bounds);
+ this.getDoubleBoundsFromRestrictions(restrs, bounds);
ret.setLowerBound(bounds[0]);
ret.setUpperBound(bounds[1]);
-
+
return ret;
}
-
- private void getDoubleBoundsFromRestrictions(String restrs, Double[] bounds)
- {
+ private void getDoubleBoundsFromRestrictions(String restrs, Double[] bounds) {
Double UB = Double.POSITIVE_INFINITY;
Double LB = Double.NEGATIVE_INFINITY;
-
- if(restrs.equals(""))
- {
+
+ if (restrs.equals("")) {
bounds[0] = LB;
bounds[1] = UB;
return;
}
-
+
String[] toks = restrs.split(":");
- if (toks.length != 0)
- {
- if (toks[0].equals(""))
- {
+ if (toks.length != 0) {
+ if (toks[0].equals("")) {
// upper bounded only
double ub;
- try
- {
+ try {
ub = Double.parseDouble(toks[1]);
- }
- catch (NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new RuntimeException(e);
}
UB = ub;
- }
- else
- {
+ } else {
// lower and upper bounded
- if (toks.length == 2)
- {
+ if (toks.length == 2) {
double lb;
double ub;
- try
- {
+ try {
lb = Double.parseDouble(toks[0]);
ub = Double.parseDouble(toks[1]);
- }
- catch (NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new RuntimeException(e);
}
LB = lb;
UB = ub;
- }
- else
- {
+ } else {
// lower bounded only
double lb;
- try
- {
+ try {
lb = Double.parseDouble(toks[0]);
- }
- catch (NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new RuntimeException(e);
}
LB = lb;
@@ -545,87 +493,69 @@ private void getDoubleBoundsFromRestrictions(String restrs, Double[] bounds)
}
}
bounds[0] = LB;
- bounds[1] = UB;
+ bounds[1] = UB;
}
-
- private Parameter<?> processDoubleParameter(String name, String value, String restrs, String tags) throws Exception
- {
+
+ private Parameter<?> processDoubleParameter(String name, String value,
+ String restrs, String tags) throws Exception {
DoubleParameter retd = new DoubleParameter(name, value);
Double[] bounds = new Double[2];
- getDoubleBoundsFromRestrictions( restrs, bounds);
+ this.getDoubleBoundsFromRestrictions(restrs, bounds);
retd.setLowerBound(bounds[0]);
retd.setUpperBound(bounds[1]);
return retd;
}
-
- private static Set<String> tokenSet(String s)
- {
+
+ private static Set<String> tokenSet(String s) {
Set<String> ret = new HashSet<String>();
String[] toks = s.split(",");
- for(String tok: toks)
+ for (String tok : toks) {
ret.add(tok);
+ }
return ret;
}
- private void getIntegerBoundsFromRestrictions(String restrs, Integer[] bounds)
- {
+ private void getIntegerBoundsFromRestrictions(String restrs,
+ Integer[] bounds) {
Integer UB = Integer.MAX_VALUE;
Integer LB = Integer.MIN_VALUE;
-
- if(restrs.equals(""))
- {
+
+ if (restrs.equals("")) {
bounds[0] = LB;
bounds[1] = UB;
return;
}
-
String[] toks = restrs.split(":");
- if (toks.length != 0)
- {
- if (toks[0].equals(""))
- {
+ if (toks.length != 0) {
+ if (toks[0].equals("")) {
// upper bounded only
int ub;
- try
- {
+ try {
ub = Integer.parseInt(toks[1]);
- }
- catch (NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new RuntimeException(e);
}
UB = ub;
- }
- else
- {
+ } else {
// lower and upper bounded
- if (toks.length == 2)
- {
+ if (toks.length == 2) {
int lb;
int ub;
- try
- {
+ try {
lb = Integer.parseInt(toks[0]);
ub = Integer.parseInt(toks[1]);
- }
- catch (NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new RuntimeException(e);
}
LB = lb;
UB = ub;
- }
- else
- {
+ } else {
// lower bounded only
int lb;
- try
- {
+ try {
lb = Integer.parseInt(toks[0]);
- }
- catch (NumberFormatException e)
- {
+ } catch (NumberFormatException e) {
throw new RuntimeException(e);
}
LB = lb;
@@ -635,94 +565,95 @@ private void getIntegerBoundsFromRestrictions(String restrs, Integer[] bounds)
bounds[0] = LB;
bounds[1] = UB;
}
-
- private Parameter<?> processIntParameter(String name, String value, String restrs, String tags) throws Exception
- {
+
+ private Parameter<?> processIntParameter(String name, String value,
+ String restrs, String tags) throws Exception {
IntegerParameter reti = new IntegerParameter(name, value);
Integer[] bounds = new Integer[2];
- getIntegerBoundsFromRestrictions(restrs, bounds);
+ this.getIntegerBoundsFromRestrictions(restrs, bounds);
reti.setLowerBound(bounds[0]);
reti.setUpperBound(bounds[1]);
return reti;
}
- private Parameter<?> processStringParameter(String name, String value, String restrs, String tags) throws Exception
- {
+ private Parameter<?> processStringParameter(String name, String value,
+ String restrs, String tags) throws Exception {
Parameter<?> rets = null;
String[] toks = restrs.split(",");
-
- for(int i=0;i<toks.length;i++)
- {
+
+ for (int i = 0; i < toks.length; i++) {
toks[i] = toks[i].trim();
}
-
- if(restrs.length()>0)
- {
- if( (toks[0].equals("true")&&toks[1].equals("false")) || (toks[0].equals("false")&&toks[1].equals("true")) )
- {
+
+ if (restrs.length() > 0) {
+ if ((toks[0].equals("true") && toks[1].equals("false"))
+ || (toks[0].equals("false") && toks[1].equals("true"))) {
rets = new BoolParameter(name, value);
- }
- else
- {
+ } else {
rets = new StringChoiceParameter(name, toks);
((StringChoiceParameter) rets).setValue(value);
}
- }
- else
- {
+ } else {
rets = new StringParameter(name, value);
}
-
+
return rets;
}
@Override
- public NodeConfiguration read(InputStream xmlstream) throws Exception
- {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
-
- factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource(SchemaProvider.class.getResourceAsStream("CTD.xsd")), new StreamSource(SchemaProvider.class.getResourceAsStream("Param_1_3.xsd"))}));
-
- SAXParser parser = factory.newSAXParser();
-
- SAXReader reader = new SAXReader(parser.getXMLReader());
- reader.setValidation(false);
-
- SimpleErrorHandler errorHandler = new SimpleErrorHandler();
-
- reader.setErrorHandler(errorHandler);
-
- doc = reader.read(xmlstream);
-
- if(!errorHandler.isValid())
- {
- System.err.println(errorHandler.getErrorReport());
- throw new Exception("CTD file is not valid !");
- }
-
- readPorts();
- readParameters();
- readDescription();
- readMapping();
- config.setXml(doc.asXML());
-
- return config;
- }
+ public NodeConfiguration read(InputStream xmlstream)
+ throws CTDNodeConfigurationReaderException {
+ try {
+ SAXParserFactory factory = SAXParserFactory.newInstance();
+ SchemaFactory schemaFactory = SchemaFactory
+ .newInstance("http://www.w3.org/2001/XMLSchema");
+
+ factory.setSchema(schemaFactory.newSchema(new Source[] {
+ new StreamSource(SchemaProvider.class
+ .getResourceAsStream("CTD.xsd")),
+ new StreamSource(SchemaProvider.class
+ .getResourceAsStream("Param_1_3.xsd")) }));
+
+ SAXParser parser = factory.newSAXParser();
+
+ SAXReader reader = new SAXReader(parser.getXMLReader());
+ reader.setValidation(false);
+
+ SimpleErrorHandler errorHandler = new SimpleErrorHandler();
+ reader.setErrorHandler(errorHandler);
- private void readMapping() throws Exception
- {
- Node node = doc.selectSingleNode("/tool/mapping");
- if(node==null&&this.config.getStatus().equals("external"))
- throw new Exception("CTD has no mapping tag and is an external tool");
- if(node==null)
+ this.doc = reader.read(xmlstream);
+
+ if (!errorHandler.isValid()) {
+ System.err.println(errorHandler.getErrorReport());
+ throw new Exception("CTD file is not valid !");
+ }
+
+ this.readPorts();
+ this.readParameters();
+ this.readDescription();
+ this.readMapping();
+ this.config.setXml(this.doc.asXML());
+
+ return this.config;
+ } catch (Exception e) {
+ throw new CTDNodeConfigurationReaderException(e);
+ }
+ }
+
+ private void readMapping() throws Exception {
+ Node node = this.doc.selectSingleNode("/tool/mapping");
+ if (node == null && this.config.getStatus().equals("external"))
+ throw new Exception(
+ "CTD has no mapping tag and is an external tool");
+ if (node == null)
return;
-
- String mapping = node.valueOf("text()");
- if(mapping.equals(""))
+
+ String mapping = node.valueOf("text()");
+ if (mapping.equals(""))
throw new Exception("CTD has an empty mapping tag");
- config.setMapping(mapping);
+ this.config.setMapping(mapping);
}
}
diff --git a/src/org/ballproject/knime/base/config/CTDNodeConfigurationReaderException.java b/src/org/ballproject/knime/base/config/CTDNodeConfigurationReaderException.java
new file mode 100644
index 00000000..565a5cb2
--- /dev/null
+++ b/src/org/ballproject/knime/base/config/CTDNodeConfigurationReaderException.java
@@ -0,0 +1,10 @@
+package org.ballproject.knime.base.config;
+
+public class CTDNodeConfigurationReaderException extends Exception {
+
+ private static final long serialVersionUID = -4982931986389455916L;
+
+ public CTDNodeConfigurationReaderException(Throwable throwable) {
+ super(throwable);
+ }
+}
diff --git a/src/org/ballproject/knime/nodegeneration/KNIMENode.java b/src/org/ballproject/knime/nodegeneration/KNIMENode.java
new file mode 100644
index 00000000..b530564f
--- /dev/null
+++ b/src/org/ballproject/knime/nodegeneration/KNIMENode.java
@@ -0,0 +1,28 @@
+package org.ballproject.knime.nodegeneration;
+
+import java.util.logging.Logger;
+
+public class KNIMENode {
+
+ private static Logger logger = Logger.getLogger(NodeGenerator.class
+ .getCanonicalName());
+
+ public static boolean checkNodeName(String name) {
+ if (!name.matches("[[A-Z]|[a-z]][[0-9]|[A-Z]|[a-z]]+"))
+ return false;
+ return true;
+ }
+
+ public static String fixNodeName(String name) {
+ logger.info("trying to fix node class name " + name);
+ name = name.replace(".", "");
+ name = name.replace("-", "");
+ name = name.replace("_", "");
+ name = name.replace("#", "");
+ name = name.replace("+", "");
+ name = name.replace("$", "");
+ name = name.replace(":", "");
+ logger.info("fixed node name " + name);
+ return name;
+ }
+}
diff --git a/src/org/ballproject/knime/nodegeneration/Main.java b/src/org/ballproject/knime/nodegeneration/Main.java
new file mode 100644
index 00000000..6ee2f6cb
--- /dev/null
+++ b/src/org/ballproject/knime/nodegeneration/Main.java
@@ -0,0 +1,25 @@
+package org.ballproject.knime.nodegeneration;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.logging.Logger;
+
+public class Main {
+
+ private static Logger logger = Logger.getLogger(NodeGenerator.class
+ .getCanonicalName());
+
+ public static void main(String[] args) {
+ File pluginDir = new File((args.length > 0) ? args[0] : ".")
+ .getAbsoluteFile();
+
+ try {
+ NodeGenerator nodeGenerator = new NodeGenerator(pluginDir);
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/src/org/ballproject/knime/nodegeneration/NodeGenerator.java b/src/org/ballproject/knime/nodegeneration/NodeGenerator.java
index 1f3043a2..6967fa00 100644
--- a/src/org/ballproject/knime/nodegeneration/NodeGenerator.java
+++ b/src/org/ballproject/knime/nodegeneration/NodeGenerator.java
@@ -19,13 +19,14 @@
package org.ballproject.knime.nodegeneration;
-
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
+import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@@ -34,12 +35,12 @@
import java.util.Map;
import java.util.Properties;
import java.util.Set;
+import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import org.ballproject.knime.base.config.NodeConfiguration;
import org.ballproject.knime.base.config.CTDNodeConfigurationReader;
+import org.ballproject.knime.base.config.CTDNodeConfigurationReaderException;
+import org.ballproject.knime.base.config.NodeConfiguration;
import org.ballproject.knime.base.mime.MIMEtype;
import org.ballproject.knime.base.parameter.Parameter;
import org.ballproject.knime.base.port.Port;
@@ -47,8 +48,10 @@
import org.ballproject.knime.base.schemas.SchemaValidator;
import org.ballproject.knime.base.util.Helper;
import org.ballproject.knime.base.util.ToolRunner;
+import org.ballproject.knime.nodegeneration.exceptions.DuplicateNodeNameException;
+import org.ballproject.knime.nodegeneration.exceptions.InvalidNodeNameException;
+import org.ballproject.knime.nodegeneration.exceptions.UnknownMimeTypeException;
import org.ballproject.knime.nodegeneration.templates.TemplateResources;
-
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
@@ -57,648 +60,704 @@
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
+import org.eclipse.core.commands.ExecutionException;
import org.jaxen.JaxenException;
import org.jaxen.SimpleNamespaceContext;
import org.jaxen.dom4j.Dom4jXPath;
-public class NodeGenerator
-{
- private static Logger logger = Logger.getLogger(NodeGenerator.class.getCanonicalName());
-
- private static Document plugindoc;
- private static NodeConfiguration config;
-
- private static String _pluginname_;
- private static String _destdir_;
- private static String _destsrcdir_;
- private static String _pluginpackage_;
- private static String _packagedir_;
- private static String _descriptordir_;
- private static String _executabledir_;
- private static String _abspackagedir_;
- private static String _absnodedir_;
- private static String _iconpath_;
- private static String _useini_ = "true";
-
- private static String cur_cat;
- private static String cur_path;
- private static String _package_root_;
- private static String _BINPACKNAME_;
- private static String _payloaddir_;
-
- private static Set<String> ext_tools = new HashSet<String>();
-
- private static Properties props;
-
- public static void assertRestrictedAlphaNumeric(Object obj, String id)
- {
- if(obj==null||obj.toString().equals(""))
- {
- panic(id+" was not properly defined");
+public class NodeGenerator {
+ private static final String PLUGIN_PROPERTIES = "plugin.properties";
+
+ private static Logger logger = Logger.getLogger(NodeGenerator.class
+ .getCanonicalName());
+
+ private String packageName;
+ private String pluginname;
+
+ private File payloadDirectory;
+ private File descriptorDirectory;
+
+ private String nodeRepositoryRoot;
+
+ private Set<String> ext_tools = new HashSet<String>();
+
+ private Properties props;
+
+ public NodeGenerator(File pluginDir) throws IOException,
+ ExecutionException, DocumentException, DuplicateNodeNameException,
+ InvalidNodeNameException, CTDNodeConfigurationReaderException,
+ UnknownMimeTypeException {
+ if (!pluginDir.isDirectory())
+ throw new FileNotFoundException("Path " + pluginDir.getPath()
+ + " is no valid directory.");
+
+ this.payloadDirectory = getPluginDirectory(pluginDir);
+ if (!this.payloadDirectory.isDirectory())
+ throw new FileNotFoundException("Could not find payload directory "
+ + this.payloadDirectory.getPath());
+
+ this.descriptorDirectory = getDescriptorsDirectory(pluginDir);
+ File executablesDirectory = getExecutablesDirectory(pluginDir);
+
+ File propertyFile = new File(pluginDir, PLUGIN_PROPERTIES);
+
+ Properties props = new Properties();
+ try {
+ props.load(new FileInputStream(propertyFile));
+ } catch (FileNotFoundException e) {
+ throw new FileNotFoundException("Could not find property file "
+ + propertyFile.getPath());
+ } catch (IOException e) {
+ throw new IOException("Could not load property file", e);
}
- String re = "^\\w+$";
- if(!obj.toString().matches(re))
- {
- panic(id+" is not a proper alpha numeric value "+obj.toString());
+
+ this.packageName = getPackageName(props);
+ if (this.packageName == null || this.packageName.isEmpty())
+ throw new InvalidParameterException("No package name was specified");
+ if (!isValidPackageName(this.packageName))
+ throw new InvalidParameterException("The given package name \""
+ + this.packageName + "\" is invalid");
+
+ this.pluginname = getPluginName(props, this.packageName);
+ if (this.packageName == null || this.packageName.isEmpty())
+ throw new InvalidParameterException("No plugin name was specified");
+ if (!isPluginNameValid(this.pluginname))
+ throw new InvalidParameterException("The package name \""
+ + this.pluginname
+ + "\" must only contain alpha numeric characters");
+
+ // the root node where to attach the generated nodes
+ this.nodeRepositoryRoot = getNodeRepositoryRoot(props);
+ if (this.nodeRepositoryRoot == null
+ || this.nodeRepositoryRoot.isEmpty())
+ throw new InvalidParameterException(
+ "No node repository root defined");
+ // TODO: validation
+
+ if (this.descriptorDirectory.isDirectory()) {
+ if (executablesDirectory.isDirectory()) {
+ logger.log(
+ Level.WARNING,
+ "Both directories \""
+ + this.descriptorDirectory.getPath()
+ + "\" and \""
+ + executablesDirectory
+ + "\" exists. The latter will be ignored and the provided *.ctd files will be used.");
+ } else {
+
+ }
+ } else {
+ if (!executablesDirectory.isDirectory())
+ throw new FileNotFoundException("Neither the directory \""
+ + this.descriptorDirectory.getPath() + "\" nor \""
+ + executablesDirectory + "\" exists.");
+
+ this.descriptorDirectory = generateDescriptors(
+ executablesDirectory, getCtdWriteSwitch(props));
}
- }
-
- public static void assertDefinition(Object obj, String id)
- {
- if(obj==null||obj.toString().equals(""))
- {
- panic(id+" was not properly defined");
+
+ // e.g. /tmp/327
+ File destinationDirectory = this.getDestinationDirectory();
+
+ // e.g. /tmp/327/src
+ File destinationSourceDirectory = new File(destinationDirectory, "src");
+
+ // e.g. /tmp/327/foo.bar
+ File destinationFQNDirectory = createPackageDirectory(
+ destinationSourceDirectory, this.packageName);
+
+ // e.g. /tmp/327/foo.bar/knime/nodes
+ File destinationFQNNodeDirectory = new File(destinationFQNDirectory,
+ "knime" + File.separator + "nodes");
+
+ File destinationPluginXML = new File(destinationDirectory, "plugin.xml");
+ Document pluginXML = preparePluginXML(destinationDirectory,
+ destinationPluginXML);
+
+ try {
+ installMimeTypes(pluginXML, destinationFQNNodeDirectory, new File(
+ this.descriptorDirectory, "mimetypes.xml"), this.pluginname);
+ } catch (JaxenException e) {
+ throw new DocumentException(e);
}
+
+ Set<String> node_names = new HashSet<String>();
+ Set<String> ext_tools = new HashSet<String>();
+ processDescriptors(node_names, ext_tools, pluginXML,
+ this.descriptorDirectory, this.nodeRepositoryRoot,
+ this.pluginname, destinationFQNNodeDirectory, this.packageName);
+
+ // TODO
+ // this.installIcon();
+
+ fillProperties(props, destinationFQNDirectory);
+
+ post(pluginXML, destinationPluginXML, this.packageName,
+ destinationFQNDirectory, destinationFQNNodeDirectory,
+ this.payloadDirectory, node_names, ext_tools);
+
}
-
- public static void assertValidPackageName(String pname, String id)
- {
- if(pname==null||pname.equals(""))
- {
- panic(id+" is no proper Java package name");
- }
- String re = "^([A-Za-z_]{1}[A-Za-z0-9_]*(\\.[A-Za-z_]{1}[A-Za-z0-9_]*)*)$";
- if(!pname.matches(re))
- panic(id+" is no proper Java package name");
- }
-
- public static void assertDirectoryExistence(String dirname, String id)
- {
- File dir = new File(dirname);
- if ( !(dir.exists() && dir.isDirectory()) )
- {
- panic(dirname+" supplied as "+id+" is no valid directory");
- }
+
+ /**
+ * Returns the directory containing the payload which consists of binaries
+ * for each platform and an optional ini-file.
+ *
+ * @param rootDirectory
+ * @return
+ */
+ private static File getPluginDirectory(File rootDirectory) {
+ File payloadDirectory = new File(rootDirectory, "payload");
+ return payloadDirectory;
}
-
- public static void assertFileExistence(String filename, String id)
- {
- File f = new File(filename);
- if ( !f.exists() )
- {
- panic(filename+" supplied as "+id+" is no valid file");
- }
+
+ /**
+ * Returns the package name the generated plugin uses. (e.g.
+ * org.roettig.foo).
+ *
+ * @param props
+ * @return
+ */
+ private static String getPackageName(Properties props) {
+ return props.getProperty("pluginpackage");
}
-
- public static String makePluginName(String s)
- {
- int idx = s.lastIndexOf(".");
- if(idx==-1)
- return s;
- return s.substring(idx+1);
- }
-
- public static void main(String[] args) throws Exception
- {
- // read in properties for building the plugin
- props = new Properties();
- props.load(new FileInputStream("plugin.properties"));
-
- // ... these are ..
-
- // the directory containing the payload (= ini-file,zip with binaries for each platform)
- _payloaddir_ = props.getProperty("payloaddir");
- assertDefinition(_payloaddir_,"payloaddir");
- assertDirectoryExistence(_payloaddir_,"payloaddir");
-
- // the name of the package (i.e. org.roettig.foo)
- _pluginpackage_ = props.getProperty("pluginpackage");
- assertDefinition(_pluginpackage_,"pluginpackage");
- assertValidPackageName(_pluginpackage_,"pluginpackage");
-
- _pluginname_ = props.getProperty("pluginname", makePluginName(_pluginpackage_));
- assertRestrictedAlphaNumeric(_pluginname_,"pluginname");
-
- // the root node where to attach the generated nodes
- _package_root_ = props.getProperty("package_root");
- assertDefinition(_package_root_,"package_root");
-
- if( ! (_package_root_.equals("community")||_package_root_.equals("chemistry")) )
- panic("invalid package root given :"+_package_root_);
-
- _descriptordir_ = props.getProperty("descriptordir");
-
- _iconpath_ = props.getProperty("icon");
- _useini_ = props.getProperty("useini","true");
-
- // no descriptor directory supplied ...
- if(_descriptordir_==null)
- {
- // .. extract tool descriptor information from executable
- _executabledir_ = props.getProperty("executabledir");
-
- if(_executabledir_==null)
- panic("neither tool descriptors nor executables were supplied");
-
- File exedir = new File(_executabledir_);
-
- if(!exedir.exists()||!exedir.isDirectory())
- panic("supplied executables directory does not exist");
-
- generateDescriptors(props);
- }
-
- _destdir_ = System.getProperty("java.io.tmpdir")+File.separator+"GENERIC_KNIME_NODES_PLUGINSRC";
-
- // the name of the binary package is simply copied from the plugin name
- _BINPACKNAME_ = _pluginpackage_;
- _destsrcdir_ = _destdir_+File.separator+"src";
- _packagedir_ = _pluginpackage_.replace(".","/");
- _abspackagedir_ = _destsrcdir_+File.separator+_packagedir_;
- _absnodedir_ = _abspackagedir_+String.format("%sknime%snodes",File.separator,File.separator);
-
-
- createPackageDirectory();
-
- pre();
-
- installMimeTypes();
-
- processDescriptors();
-
- installIcon();
-
- fillProperties();
-
- post();
-
- }
-
- public static void fillProperties() throws IOException
- {
- Properties p = new Properties();
- p.put("use_ini", props.getProperty("use_ini","true"));
- p.put("ini_switch", props.getProperty("ini_switch","-ini"));
- p.store(new FileOutputStream(_abspackagedir_+File.separator+"knime"+File.separator+"plugin.properties"), null);
- }
-
- public static void installIcon() throws IOException
- {
- if(_iconpath_!=null)
- {
- Node node = plugindoc.selectSingleNode("/plugin/extension[@point='org.knime.product.splashExtension']");
- Element elem = (Element) node;
- elem.addElement("splashExtension").addAttribute("icon", "icons/logo.png").addAttribute("id", "logo");
-
- new File(_destdir_ +File.separator+"icons").mkdirs();
- Helper.copyFile(new File(_iconpath_), new File(_destdir_ +File.separator+"icons"+File.separator+"logo.png"));
- }
-
+ /**
+ * Checks whether a given package name is valid.
+ *
+ * @param packageName
+ * @param id
+ * @return true if package name is valid; false otherwise
+ */
+ public static boolean isValidPackageName(String packageName) {
+ return packageName != null
+ && packageName
+ .matches("^([A-Za-z_]{1}[A-Za-z0-9_]*(\\.[A-Za-z_]{1}[A-Za-z0-9_]*)*)$");
}
- public static void generateDescriptors(Properties props) throws Exception
- {
- String par_switch = props.getProperty("parswitch","-write_par");
- File bindir = new File(_executabledir_+File.separator+"bin");
-
- if(!bindir.exists()||!bindir.isDirectory())
- {
- panic("could not find bin directory with executables at executabledir: "+_executabledir_);
- }
-
- String ttd_dir = System.getProperty("java.io.tmpdir")+File.separator+"GENERIC_KNIME_NODES_TTD";
-
- try
- {
- File outdir = new File(ttd_dir);
- outdir.mkdirs();
- outdir.deleteOnExit();
- }
- catch(Exception e)
- {
- panic("could not create temporary directory "+ttd_dir);
- }
-
- String[] exes = bindir.list();
-
- if(exes.length==0)
- {
- panic("found no executables at "+bindir);
- }
-
- for(String exe: exes)
- {
+ /**
+ * Returns the plugin name.
+ * <p>
+ * If no configuration could be found, the name is created based on the
+ * given package name. e.g. org.roettig.foo will result in foo
+ *
+ * @param packageName
+ * @return
+ */
+ public static String getPluginName(Properties props, String packageName) {
+ String pluginname = props.getProperty("pluginname");
+ if (pluginname != null && !pluginname.isEmpty())
+ return pluginname;
+
+ int idx = packageName.lastIndexOf(".");
+ if (idx == -1)
+ return packageName;
+ return packageName.substring(idx + 1);
+ }
+
+ /**
+ * Checks if the plugin name is valid.
+ *
+ * @param obj
+ * @param id
+ */
+ public static boolean isPluginNameValid(String pluginName) {
+ return pluginName != null && pluginName.matches("^\\w+$");
+ }
+
+ /**
+ * Returns the path where the generated KNIME nodes will reside. e.g.
+ * <code>community/my_nodes</code>
+ *
+ * @param props
+ * @return
+ */
+ private static String getNodeRepositoryRoot(Properties props) {
+ return props.getProperty("package_root");
+ }
+
+ /**
+ * Returns the directory where the Common Tool Descriptors (*.ctd) reside.
+ *
+ * @param props
+ * @return
+ */
+ private static File getDescriptorsDirectory(File rootDirectory) {
+ File descriptorsDirectory = new File(rootDirectory, "descriptors");
+ return descriptorsDirectory;
+ }
+
+ /**
+ * Returns the directory where the tools to generate KNIME nodes from
+ * reside.
+ * <p>
+ * Notice: The tools must support the creation of ctd-files.
+ *
+ * @param props
+ * @return
+ */
+ private static File getExecutablesDirectory(File rootDirectory) {
+ File exectuablesDirectory = new File(rootDirectory, "executables");
+ return exectuablesDirectory;
+ }
+
+ /**
+ * Creates a ctd file for each binary found in the given {@link File
+ * Directory} in a temporary directory by calling each binary with the given
+ * switch (e.g. <code>-ctd-write</code>).
+ *
+ * @param executablesDirectory
+ * @param ctdWriteSwitch
+ * @return the temporary directory in which the ctd files were created
+ * @throws IOException
+ * @throws ExecutionException
+ */
+ public static File generateDescriptors(File executablesDirectory,
+ String ctdWriteSwitch) throws IOException, ExecutionException {
+
+ File tempDirectory = new File(System.getProperty("java.io.tmpdir"),
+ "GKN-descriptors-" + Long.toString(System.nanoTime()));
+ tempDirectory.mkdirs();
+ tempDirectory.deleteOnExit();
+
+ File binDirectory = new File(executablesDirectory, "bin");
+ if (!binDirectory.isDirectory())
+ throw new FileNotFoundException("The bin directory "
+ + binDirectory.getPath() + " is not valid.");
+
+ String[] exes = new File(executablesDirectory, "bin").list();
+
+ if (exes.length == 0)
+ throw new FileNotFoundException(
+ "Could not find any executables in " + executablesDirectory);
+
+ for (String exe : exes) {
ToolRunner tr = new ToolRunner();
- File outfile = File.createTempFile("TTD","");
+ File outfile = File.createTempFile("CTD", "");
outfile.deleteOnExit();
-
- // FixMe: this is so *nix style, wont hurt on windows
+
+ // FIXME: this is so *nix style, wont hurt on windows
// but probably wont help either
- tr.addEnvironmentEntry("LD_LIBRARY_PATH", _executabledir_+File.separator+"lib");
-
- String cmd = _executabledir_+File.separator+"bin"+File.separator+exe+" "+par_switch+" "+outfile.getAbsolutePath();
- tr.run(cmd);
-
- if(tr.getReturnCode()==0)
- {
- Helper.copyFile(outfile,new File(ttd_dir+File.separator+outfile.getName()));
- }
- else
- {
- panic("could not execute tool : "+cmd);
+ tr.addEnvironmentEntry("LD_LIBRARY_PATH", new File(
+ executablesDirectory, "lib").getAbsolutePath());
+
+ String cmd = binDirectory.getAbsolutePath() + File.separator + exe
+ + " " + ctdWriteSwitch + " " + outfile.getAbsolutePath();
+ try {
+ tr.run(cmd);
+
+ if (tr.getReturnCode() != 0) {
+ Helper.copyFile(outfile,
+ new File(tempDirectory, outfile.getName()));
+ } else
+ throw new ExecutionException("Tool \"" + cmd
+ + "\" returned with " + tr.getReturnCode());
+ } catch (Exception e) {
+ throw new ExecutionException("Could not execute tool: " + cmd,
+ e);
}
}
-
- _descriptordir_ = ttd_dir;
- }
-
- private static void createPackageDirectory()
- {
- File packagedir = new File(_destsrcdir_+File.separator+_packagedir_);
- Helper.deleteDirectory(packagedir);
- packagedir.mkdirs();
- }
-
- public static void pre() throws DocumentException, IOException
- {
- Helper.copyStream(TemplateResources.class.getResourceAsStream("plugin.xml.template"),new File(_destdir_ + File.separator+"plugin.xml"));
-
- DOMDocumentFactory factory = new DOMDocumentFactory();
+
+ return tempDirectory;
+ }
+
+ /**
+ * Returns the switch needed to make an executable output a ctd-file.
+ *
+ * @param props
+ * @return
+ */
+ private static String getCtdWriteSwitch(Properties props) {
+ return props.getProperty("parswitch", "-write_par");
+ }
+
+ /**
+ * Returns the {@link File directory} where to put the plugin source in.
+ *
+ * @return
+ */
+ private File getDestinationDirectory() {
+ return new File(System.getProperty("java.io.tmpdir"),
+ "GKN-pluginsource-" + Long.toString(System.nanoTime()));
+ }
+
+ /**
+ * Creates a directory structure representing a package name.
+ * <p>
+ * e.g. <code>foo.bar</code> would result in the directory
+ * <code>foo/bar</code>.
+ *
+ * @param directory
+ * where to create the directory structure in
+ * @param packageName
+ * @return
+ */
+ private static File createPackageDirectory(File directory,
+ String packageName) {
+ File packageDirectory = new File(directory, packageName.replace(".",
+ "/"));
+ Helper.deleteDirectory(packageDirectory);
+ packageDirectory.mkdirs();
+ return packageDirectory;
+ }
+
+ public static void fillProperties(Properties props,
+ File destinationFQNDirectory) throws IOException {
+ Properties p = new Properties();
+ p.put("use_ini", props.getProperty("use_ini", "true"));
+ p.put("ini_switch", props.getProperty("ini_switch", "-ini"));
+ p.store(new FileOutputStream(destinationFQNDirectory + File.separator
+ + "knime" + File.separator + PLUGIN_PROPERTIES), null);
+ }
+
+ // TODO
+ // public void installIcon() throws IOException {
+ // if (this._iconpath_ != null) {
+ // Node node = this.plugindoc
+ // .selectSingleNode("/plugin/extension[@point='org.knime.product.splashExtension']");
+ // Element elem = (Element) node;
+ //
+ // elem.addElement("splashExtension")
+ // .addAttribute("icon", "icons/logo.png")
+ // .addAttribute("id", "logo");
+ //
+ // new File(this._destdir_ + File.separator + "icons").mkdirs();
+ // Helper.copyFile(new File(this._iconpath_), new File(this._destdir_
+ // + File.separator + "icons" + File.separator + "logo.png"));
+ // }
+ //
+ // }
+
+ /**
+ * Prepares a new copy of a template plugin.xml in the given {@link File
+ * directory} and returns its {@link Document} representation.
+ *
+ * @param destinationDirectory
+ * @return
+ * @throws DocumentException
+ * @throws IOException
+ */
+ public static Document preparePluginXML(File destinationDirectory,
+ File destinationPluginXML) throws DocumentException, IOException {
+ Helper.copyStream(TemplateResources.class
+ .getResourceAsStream("plugin.xml.template"),
+ destinationPluginXML);
+
SAXReader reader = new SAXReader();
- reader.setDocumentFactory(factory);
+ reader.setDocumentFactory(new DOMDocumentFactory());
- plugindoc = reader.read(new FileInputStream(new File(_destdir_ + File.separator+"plugin.xml")));
-
+ return reader.read(new FileInputStream(destinationPluginXML));
}
-
- private static void installMimeTypes() throws DocumentException, IOException, JaxenException
- {
- assertFileExistence(_descriptordir_ + File.separator+"mimetypes.xml","mimetypes.xml");
-
-
+
+ /**
+ * TODO
+ *
+ * @param pluginXML
+ * @param destinationFQNNodeDirectory
+ * @param mimetypesXML
+ * @param packageName
+ * @throws DocumentException
+ * @throws IOException
+ * @throws JaxenException
+ */
+ private static void installMimeTypes(Document pluginXML,
+ File destinationFQNNodeDirectory, File mimetypesXML,
+ String packageName) throws DocumentException, IOException,
+ JaxenException {
+ if (!mimetypesXML.isFile() || !mimetypesXML.canRead())
+ throw new IOException("Invalid MIME types file: "
+ + mimetypesXML.getPath());
+
SchemaValidator val = new SchemaValidator();
val.addSchema(SchemaProvider.class.getResourceAsStream("mimetypes.xsd"));
- if(!val.validates(_descriptordir_ + File.separator+"mimetypes.xml"))
- {
- panic("supplied mimetypes.xml does not conform to schema "+val.getErrorReport());
- }
-
-
+ if (!val.validates(mimetypesXML.getPath()))
+ throw new DocumentException("Supplied \"" + mimetypesXML.getPath()
+ + "\" does not conform to schema " + val.getErrorReport());
+
DOMDocumentFactory factory = new DOMDocumentFactory();
SAXReader reader = new SAXReader();
reader.setDocumentFactory(factory);
-
- Document doc = reader.read(new FileInputStream(new File(_descriptordir_ + File.separator+"mimetypes.xml")));
-
- InputStream template = TemplateResources.class.getResourceAsStream("MimeFileCellFactory.template");
-
- TemplateFiller tf = new TemplateFiller();
+
+ Document doc = reader.read(new FileInputStream(mimetypesXML));
+
+ InputStream template = TemplateResources.class
+ .getResourceAsStream("MimeFileCellFactory.template");
+
+ TemplateFiller tf = new TemplateFiller();
tf.read(template);
-
+
String mimetypes_template = "\t\tmimetypes.add(new MIMEType(\"__EXT__\"));\n";
- String mimetypes_code = "";
-
+ String mimetypes_code = "";
+
Set<String> mimetypes = new HashSet<String>();
-
- Map<String,String> map = new HashMap<String,String>();
- map.put( "bp", "http://www.ball-project.org/mimetypes");
-
- Dom4jXPath xpath = new Dom4jXPath( "//bp:mimetype");
- xpath.setNamespaceContext( new SimpleNamespaceContext(map));
+
+ Map<String, String> map = new HashMap<String, String>();
+ map.put("bp", "http://www.ball-project.org/mimetypes"); // TODO
+
+ Dom4jXPath xpath = new Dom4jXPath("//bp:mimetype");
+ xpath.setNamespaceContext(new SimpleNamespaceContext(map));
@SuppressWarnings("unchecked")
List<Node> nodes = xpath.selectNodes(doc);
-
- for(Node node: nodes)
- {
- Element elem = (Element) node;
-
- String name = elem.valueOf("@name");
- String ext = elem.valueOf("@ext");
- //String descr = elem.valueOf("@description");
- //String demangler = elem.valueOf("@demangler");
- String binary = elem.valueOf("@binary");
+
+ for (Node node : nodes) {
+ Element elem = (Element) node;
+
+ String name = elem.valueOf("@name");
+ String ext = elem.valueOf("@ext");
+ // String descr = elem.valueOf("@description");
+ // String demangler = elem.valueOf("@demangler");
+ String binary = elem.valueOf("@binary");
binary = (binary.equals("") ? "false" : binary);
-
- logger.info("read mime type "+name);
-
- if(mimetypes.contains(name))
- {
- warn("skipping duplicate mime type "+name);
+
+ logger.info("read mime type " + name);
+
+ if (mimetypes.contains(name)) {
+ logger.log(Level.WARNING, "skipping duplicate mime type "
+ + name);
}
-
- //createMimeTypeLoader(name, ext);
-
- //String clazz = createMimeCell(name, ext);
- //createMimeValue(name);
-
- ext2type.put(ext.toLowerCase(),name);
- //ext2clazz.put(ext.toLowerCase(),clazz);
-
- String s4 = mimetypes_template.replace("__EXT__", ext.toLowerCase());
+
+ // createMimeTypeLoader(name, ext);
+
+ // String clazz = createMimeCell(name, ext);
+ // createMimeValue(name);
+
+ // ext2clazz.put(ext.toLowerCase(),clazz);
+
+ String s4 = mimetypes_template
+ .replace("__EXT__", ext.toLowerCase());
mimetypes_code += s4;
}
-
+
tf.replace("__MIMETYPES__", mimetypes_code);
- tf.replace("__BASE__", _pluginpackage_);
- tf.write(_absnodedir_ + String.format("%smimetypes%sMimeFileCellFactory.java",File.separator,File.separator));
+ tf.replace("__BASE__", packageName);
+ tf.write(new File(destinationFQNNodeDirectory, "mimetypes"
+ + File.separator + "MimeFileCellFactory.java"));
template.close();
-
- }
-
- private static void processDescriptors() throws Exception
- {
- File files[] = (new File(_descriptordir_)).listFiles();
-
- for (File f : files)
- {
- String filename = f.getName();
-
- if (filename.endsWith(".ctd"))
- {
- logger.info("start processing node "+f);
- processNode(filename, f);
+ }
+
+ private static void processDescriptors(Set<String> node_names,
+ Set<String> ext_tools, Document pluginXML,
+ File descriptorDirectory, String nodeRepositoryRoot,
+ String pluginName, File destinationFQNNodeDirectory,
+ String packageName) throws IOException, DuplicateNodeNameException,
+ InvalidNodeNameException, CTDNodeConfigurationReaderException,
+ UnknownMimeTypeException {
+ Set<String> categories = new HashSet<String>();
+ for (File file : descriptorDirectory.listFiles()) {
+ if (file.getName().endsWith(".ctd")) {
+ logger.info("start processing node " + file);
+ processNode(pluginXML, file, node_names, ext_tools,
+ nodeRepositoryRoot, pluginName,
+ destinationFQNNodeDirectory, categories, packageName);
}
}
}
-
- private static Set<String> node_names = new HashSet<String>();
-
- public static boolean checkNodeName(String name)
- {
- if(!name.matches("[[A-Z]|[a-z]][[0-9]|[A-Z]|[a-z]]+"))
- return false;
- return true;
- }
-
- public static String fixNodeName(String name)
- {
- logger.info("trying to fix node class name "+name);
- name = name.replace(".", "");
- name = name.replace("-", "");
- name = name.replace("_", "");
- name = name.replace("#", "");
- name = name.replace("+", "");
- name = name.replace("$", "");
- name = name.replace(":", "");
- logger.info("fixed node name "+name);
- return name;
- }
-
- public static String combine (String path1, String path2)
- {
- File file1 = new File(path1);
- File file2 = new File(file1, path2);
- return file2.getPath();
- }
-
- public static void processNode(String name, File descriptor) throws Exception
- {
-
- logger.info("## processing Node "+name);
-
+
+ public static void processNode(Document pluginXML, File ctdFile,
+ Set<String> node_names, Set<String> ext_tools,
+ String nodeRepositoryRoot, String pluginName,
+ File destinationFQNNodeDirectory, Set<String> categories,
+ String packageName) throws IOException, DuplicateNodeNameException,
+ InvalidNodeNameException, CTDNodeConfigurationReaderException,
+ UnknownMimeTypeException {
+
+ logger.info("## processing Node " + ctdFile.getName());
+
CTDNodeConfigurationReader reader = new CTDNodeConfigurationReader();
- try
- {
- config = reader.read(new FileInputStream(descriptor));
- }
- catch(Exception e)
- {
- panic(e.getMessage());
- }
-
+ NodeConfiguration config = reader.read(new FileInputStream(ctdFile));
+
String nodeName = config.getName();
-
+
String oldNodeName = null;
-
- if(!checkNodeName(nodeName))
- {
+
+ if (!KNIMENode.checkNodeName(nodeName)) {
oldNodeName = nodeName;
-
+
// we try to fix the nodename
- nodeName = fixNodeName(nodeName);
-
- if(!checkNodeName(nodeName))
- panic("NodeName with invalid name detected "+nodeName);
-
+ nodeName = KNIMENode.fixNodeName(nodeName);
+
+ if (!KNIMENode.checkNodeName(nodeName))
+ throw new InvalidNodeNameException("The node name \""
+ + nodeName + "\" is invalid.");
}
-
- if(oldNodeName==null)
- {
- if(node_names.contains(nodeName))
- {
- warn("duplicate tool detected "+nodeName);
- return;
- }
-
- if(config.getStatus().equals("internal"))
+
+ if (oldNodeName == null) {
+ if (node_names.contains(nodeName))
+ throw new DuplicateNodeNameException(nodeName);
+
+ if (config.getStatus().equals("internal")) {
node_names.add(nodeName);
- else
+ } else {
ext_tools.add(nodeName);
-
- }
- else
- {
- if(node_names.contains(oldNodeName))
- {
- warn("duplicate tool detected "+oldNodeName);
- return;
}
-
- if(config.getStatus().equals("internal"))
+ } else {
+ if (node_names.contains(oldNodeName))
+ throw new DuplicateNodeNameException(nodeName);
+
+ if (config.getStatus().equals("internal")) {
node_names.add(oldNodeName);
- else
+ } else {
ext_tools.add(nodeName);
+ }
}
-
- cur_cat = combine("/"+_package_root_+"/"+_pluginname_,config.getCategory());
-
- cur_path = getPathPrefix(cur_cat);
-
-
- File nodeConfigDir = new File(_absnodedir_ + File.separator + nodeName + File.separator+"config");
+
+ String cur_cat = new File("/" + nodeRepositoryRoot + "/" + pluginName,
+ config.getCategory()).getPath();
+
+ File nodeConfigDir = new File(destinationFQNNodeDirectory
+ + File.separator + nodeName + File.separator + "config");
nodeConfigDir.mkdirs();
- Helper.copyFile(descriptor, new File(_absnodedir_ + File.separator + nodeName + File.separator + "config"+File.separator+"config.xml"));
-
- registerPath(cur_cat);
-
- createFactory(nodeName);
-
- createDialog(nodeName);
-
- createView(nodeName);
-
- createModel(nodeName);
-
- fillMimeTypes();
-
- createXMLDescriptor(nodeName);
-
- writeModel(nodeName);
-
- registerNode( _pluginpackage_ + ".knime.nodes." + nodeName + "." + nodeName + "NodeFactory", cur_cat);
-
- }
-
- /**
- * returns the prefix path of the given path.
- *
- * /foo/bar/baz ---> /foo/bar/
- *
- * @param path
- * @return
- */
- public static String getPathPrefix(String path)
- {
- File pth = new File(path);
- return pth.getParent();
- }
-
- /**
- * returns all prefix paths of a given path.
- *
- * /foo/bar/baz --> [/foo/bar/,/foo/,/]
- *
- * @param path
- * @return
- */
- public static List<String> getPathPrefixes(String path)
- {
- List<String> ret = new ArrayList<String>();
- File pth = new File(path);
- ret.add(path);
- while(pth.getParent()!=null)
- {
- ret.add(pth.getParent());
- pth = pth.getParentFile();
- }
- return ret;
+ Helper.copyFile(ctdFile, new File(destinationFQNNodeDirectory
+ + File.separator + nodeName + File.separator + "config"
+ + File.separator + "config.xml"));
+
+ registerPath(cur_cat, pluginXML, categories);
+
+ createFactory(nodeName, destinationFQNNodeDirectory, packageName);
+
+ createDialog(nodeName, destinationFQNNodeDirectory, packageName);
+
+ createView(nodeName, destinationFQNNodeDirectory, packageName);
+
+ TemplateFiller curmodel_tf = createModel(nodeName,
+ destinationFQNNodeDirectory, packageName);
+
+ fillMimeTypes(config, curmodel_tf);
+
+ TemplateFiller nodeFactoryXML = createXMLDescriptor(nodeName, config);
+ nodeFactoryXML.write(destinationFQNNodeDirectory + "/" + nodeName + "/"
+ + nodeName + "NodeFactory.xml");
+
+ writeModel(nodeName, destinationFQNNodeDirectory, curmodel_tf);
+
+ registerNode(packageName + ".knime.nodes." + nodeName + "." + nodeName
+ + "NodeFactory", cur_cat, pluginXML, categories);
+
}
-
- /**
- * returns the path suffix for a given path.
- *
- * /foo/bar/baz --> baz
- *
- * @param path
- * @return
- */
- public static String getPathSuffix(String path)
- {
- File pth = new File(path);
- return pth.getName();
- }
-
- public static Set<String> categories = new HashSet<String>();
-
- public static void registerPath(String path)
- {
- List<String> prefixes = getPathPrefixes(path);
-
- for(String prefix: prefixes)
- {
- registerPathPrefix(prefix);
+
+ public static void registerPath(String path, Document pluginXML,
+ Set<String> categories) {
+ List<String> prefixes = Utils.getPathPrefixes(path);
+ for (String prefix : prefixes) {
+ registerPathPrefix(prefix, pluginXML, categories);
}
}
-
- public static void registerPathPrefix(String path)
- {
+
+ public static void registerPathPrefix(String path, Document pluginXML,
+ Set<String> categories) {
// do not register any top level or root path
- if(path.equals("/")||new File(path).getParent().equals("/"))
+ if (path.equals("/") || new File(path).getParent().equals("/"))
return;
-
- if(categories.contains(path))
+
+ if (categories.contains(path))
return;
-
+
logger.info("registering path prefix " + path);
-
+
categories.add(path);
-
- String cat_name = getPathSuffix(path);
- String path_prefix = getPathPrefix(path);
-
- Node node = plugindoc.selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.categories']");
-
+
+ String cat_name = Utils.getPathSuffix(path);
+ String path_prefix = Utils.getPathPrefix(path);
+
+ Node node = pluginXML
+ .selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.categories']");
+
Element elem = (Element) node;
- logger.info("name="+cat_name);
-
- elem.addElement("category").addAttribute("description", path).addAttribute("icon", "icons/category.png")
- .addAttribute("path", path_prefix).addAttribute("name", cat_name).addAttribute("level-id", cat_name);
- }
-
- public static void createFactory(String nodeName) throws IOException
- {
- InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeFactory.template");
+ logger.info("name=" + cat_name);
+
+ elem.addElement("category").addAttribute("description", path)
+ .addAttribute("icon", "icons/category.png")
+ .addAttribute("path", path_prefix)
+ .addAttribute("name", cat_name)
+ .addAttribute("level-id", cat_name);
+ }
+
+ public static void createFactory(String nodeName,
+ File destinationFQNNodeDirectory, String packageName)
+ throws IOException {
+ InputStream template = NodeGenerator.class
+ .getResourceAsStream("templates/NodeFactory.template");
TemplateFiller tf = new TemplateFiller();
tf.read(template);
tf.replace("__NODENAME__", nodeName);
- tf.replace("__BASE__", _pluginpackage_);
- tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeFactory.java");
+ tf.replace("__BASE__", packageName);
+ tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + nodeName
+ + "NodeFactory.java");
}
- public static void createDialog(String nodeName) throws IOException
- {
- InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeDialog.template");
+ public static void createDialog(String nodeName,
+ File destinationFQNNodeDirectory, String packageName)
+ throws IOException {
+ InputStream template = NodeGenerator.class
+ .getResourceAsStream("templates/NodeDialog.template");
TemplateFiller tf = new TemplateFiller();
tf.read(template);
tf.replace("__NODENAME__", nodeName);
- tf.replace("__BASE__", _pluginpackage_);
- tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeDialog.java");
+ tf.replace("__BASE__", packageName);
+ tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + nodeName
+ + "NodeDialog.java");
}
- public static String join(Collection<String> col)
- {
+ public static String join(Collection<String> col) {
String ret = "";
- for(String s: col)
- {
- ret += s+",";
+ for (String s : col) {
+ ret += s + ",";
}
- ret = ret.substring(0,ret.length()-1);
+ ret = ret.substring(0, ret.length() - 1);
return ret;
}
-
- public static void createXMLDescriptor(String nodeName) throws IOException
- {
+
+ public static TemplateFiller createXMLDescriptor(String nodeName,
+ NodeConfiguration config) throws IOException {
// ports
String ip = "<inPort index=\"__IDX__\" name=\"__PORTDESCR__\"><![CDATA[__PORTDESCR__ [__MIMETYPE____OPT__]]]></inPort>";
String inports = "";
int idx = 0;
- for (Port port : config.getInputPorts())
- {
+ for (Port port : config.getInputPorts()) {
String ipp = ip;
ipp = ip.replace("__PORTNAME__", port.getName());
ipp = ipp.replace("__PORTDESCR__", port.getDescription());
ipp = ipp.replace("__IDX__", String.format("%d", idx++));
-
+
// fix me
- //ipp = ipp.replace("__MIMETYPE__", port.getMimeTypes().get(0).getExt());
+ // ipp = ipp.replace("__MIMETYPE__",
+ // port.getMimeTypes().get(0).getExt());
List<String> mts = new ArrayList<String>();
- for(MIMEtype mt: port.getMimeTypes())
- {
+ for (MIMEtype mt : port.getMimeTypes()) {
mts.add(mt.getExt());
}
ipp = ipp.replace("__MIMETYPE__", join(mts));
-
- ipp = ipp.replace("__OPT__", (port.isOptional()?",opt.":""));
+
+ ipp = ipp.replace("__OPT__", (port.isOptional() ? ",opt." : ""));
inports += ipp + "\n";
}
String op = "<outPort index=\"__IDX__\" name=\"__PORTDESCR__ [__MIMETYPE__]\"><![CDATA[__PORTDESCR__ [__MIMETYPE__]]]></outPort>";
String outports = "";
idx = 0;
- for (Port port : config.getOutputPorts())
- {
+ for (Port port : config.getOutputPorts()) {
String opp = op;
opp = op.replace("__PORTNAME__", port.getName());
opp = opp.replace("__PORTDESCR__", port.getDescription());
opp = opp.replace("__IDX__", String.format("%d", idx++));
-
+
// fix me
- opp = opp.replace("__MIMETYPE__", port.getMimeTypes().get(0).getExt());
-
+ opp = opp.replace("__MIMETYPE__", port.getMimeTypes().get(0)
+ .getExt());
+
outports += opp + "\n";
}
StringBuffer buf = new StringBuffer();
- for (Parameter<?> p : config.getParameters())
- {
- buf.append("\t\t<option name=\"" + p.getKey() + "\"><![CDATA[" + p.getDescription() + "]]></option>\n");
+ for (Parameter<?> p : config.getParameters()) {
+ buf.append("\t\t<option name=\"" + p.getKey() + "\"><![CDATA["
+ + p.getDescription() + "]]></option>\n");
}
String opts = buf.toString();
- InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeXMLDescriptor.template");
+ InputStream template = NodeGenerator.class
+ .getResourceAsStream("templates/NodeXMLDescriptor.template");
TemplateFiller tf = new TemplateFiller();
tf.read(template);
@@ -710,288 +769,273 @@ public static void createXMLDescriptor(String nodeName) throws IOException
tf.replace("__DESCRIPTION__", config.getDescription());
String pp = prettyPrint(config.getManual());
tf.replace("__MANUAL__", pp);
- if(!config.getDocUrl().equals(""))
- {
- String ahref = "<a href=\""+config.getDocUrl()+"\">Web Documentation for "+nodeName+"</a>";
- tf.replace("__DOCLINK__", ahref);
- }
- else
- {
+ if (!config.getDocUrl().equals("")) {
+ String ahref = "<a href=\"" + config.getDocUrl()
+ + "\">Web Documentation for " + nodeName + "</a>";
+ tf.replace("__DOCLINK__", ahref);
+ } else {
tf.replace("__DOCLINK__", "");
}
- tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeFactory.xml");
-
+ return tf;
}
- private static String prettyPrint(String manual)
- {
- if(manual.equals(""))
+ private static String prettyPrint(String manual) {
+ if (manual.equals(""))
return "";
StringBuffer sb = new StringBuffer();
String[] toks = manual.split("\\n");
- for(String tok: toks)
- {
- sb.append("<p><![CDATA["+tok+"]]></p>");
+ for (String tok : toks) {
+ sb.append("<p><![CDATA[" + tok + "]]></p>");
}
return sb.toString();
}
- public static void createView(String nodeName) throws IOException
- {
- InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeView.template");
+ public static void createView(String nodeName,
+ File destinationFQNNodeDirectory, String packageName)
+ throws IOException {
+ InputStream template = NodeGenerator.class
+ .getResourceAsStream("templates/NodeView.template");
TemplateFiller tf = new TemplateFiller();
tf.read(template);
tf.replace("__NODENAME__", nodeName);
- tf.replace("__BASE__", _pluginpackage_);
- tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeView.java");
+ tf.replace("__BASE__", packageName);
+ tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + nodeName
+ + "NodeView.java");
}
- private static TemplateFiller curmodel_tf = null;
-
- public static void createModel(String nodeName) throws IOException
- {
- InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeModel.template");
- curmodel_tf = new TemplateFiller();
+ public static TemplateFiller createModel(String nodeName,
+ File destinationFQNNodeDirectory, String packageName)
+ throws IOException {
+ InputStream template = NodeGenerator.class
+ .getResourceAsStream("templates/NodeModel.template");
+ TemplateFiller curmodel_tf = new TemplateFiller();
curmodel_tf.read(template);
curmodel_tf.replace("__NODENAME__", nodeName);
- curmodel_tf.replace("__BASE__", _pluginpackage_);
- curmodel_tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeModel.java");
+ curmodel_tf.replace("__BASE__", packageName);
+ curmodel_tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/"
+ + nodeName + "NodeModel.java");
+ return curmodel_tf;
}
- protected static void writeModel(String nodeName) throws IOException
- {
- curmodel_tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeModel.java");
+ protected static void writeModel(String nodeName,
+ File destinationFQNNodeDirectory, TemplateFiller curmodel_tf)
+ throws IOException {
+ curmodel_tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/"
+ + nodeName + "NodeModel.java");
}
-
-
- public static Map<String,String> ext2type = new HashMap<String,String>();
-
- private static void fillMimeTypes() throws IOException
- {
+
+ private static void fillMimeTypes(NodeConfiguration config,
+ TemplateFiller curmodel_tf) throws UnknownMimeTypeException {
String clazzez = "";
- for (Port port : config.getInputPorts())
- {
+ for (Port port : config.getInputPorts()) {
String tmp = "{";
- for(MIMEtype type: port.getMimeTypes())
- {
+ for (MIMEtype type : port.getMimeTypes()) {
String ext = type.getExt().toLowerCase();
- if(ext==null)
- {
- panic("unknown mime type : |"+type.getExt()+"|");
- }
+ if (ext == null)
+ throw new UnknownMimeTypeException(type);
/*
- if(port.isMultiFile())
- tmp += "DataType.getType(ListCell.class, DataType.getType(" + ext + "FileCell.class)),";
- else
- tmp += "DataType.getType(" + ext + "FileCell.class),";
- */
- tmp += "new MIMEType(\""+ext+"\"),";
+ * if(port.isMultiFile()) tmp +=
+ * "DataType.getType(ListCell.class, DataType.getType(" + ext +
+ * "FileCell.class)),"; else tmp += "DataType.getType(" + ext +
+ * "FileCell.class),";
+ */
+ tmp += "new MIMEType(\"" + ext + "\"),";
}
- tmp = tmp.substring(0,tmp.length()-1);
- tmp+="},";
+ tmp = tmp.substring(0, tmp.length() - 1);
+ tmp += "},";
clazzez += tmp;
}
-
- if(!clazzez.equals(""))
- clazzez = clazzez.substring(0,clazzez.length()-1);
-
+
+ if (!clazzez.equals("")) {
+ clazzez = clazzez.substring(0, clazzez.length() - 1);
+ }
+
clazzez += "}";
- createInClazzezModel(clazzez);
-
+ createInClazzezModel(clazzez, curmodel_tf);
+
clazzez = "";
- for (Port port : config.getOutputPorts())
- {
+ for (Port port : config.getOutputPorts()) {
String tmp = "{";
- for(MIMEtype type: port.getMimeTypes())
- {
+ for (MIMEtype type : port.getMimeTypes()) {
String ext = type.getExt().toLowerCase();
- if(ext==null)
- {
- panic("unknown mime type : |"+type.getExt()+"|");
- }
+ if (ext == null)
+ throw new UnknownMimeTypeException(type);
/*
- if(port.isMultiFile())
- tmp += "DataType.getType(ListCell.class, DataType.getType(" + ext + "FileCell.class)),";
- else
- tmp += "DataType.getType(" + ext + "FileCell.class),";
- */
- tmp += "new MIMEType(\""+ext+"\"),";
+ * if(port.isMultiFile()) tmp +=
+ * "DataType.getType(ListCell.class, DataType.getType(" + ext +
+ * "FileCell.class)),"; else tmp += "DataType.getType(" + ext +
+ * "FileCell.class),";
+ */
+ tmp += "new MIMEType(\"" + ext + "\"),";
}
- tmp = tmp.substring(0,tmp.length()-1);
- tmp+="},";
+ tmp = tmp.substring(0, tmp.length() - 1);
+ tmp += "},";
clazzez += tmp;
- }
-
- if(!clazzez.equals(""))
- clazzez = clazzez.substring(0,clazzez.length()-1);
-
+ }
+
+ if (!clazzez.equals("")) {
+ clazzez = clazzez.substring(0, clazzez.length() - 1);
+ }
+
clazzez += "}";
-
- createOutClazzezModel(clazzez);
- }
-
- public static void makeMimeFileCellFactory()
- {
-
-
- }
-
- public static void createInClazzezModel(String clazzez) throws IOException
- {
- if (clazzez.equals(""))
+
+ createOutClazzezModel(clazzez, curmodel_tf);
+ }
+
+ public static void createInClazzezModel(String clazzez,
+ TemplateFiller curmodel_tf) {
+ if (clazzez.equals("")) {
clazzez = "null";
- else
+ } else {
clazzez = clazzez.substring(0, clazzez.length() - 1);
+ }
curmodel_tf.replace("__INCLAZZEZ__", clazzez);
}
- public static void createOutClazzezModel(String clazzez) throws IOException
- {
- if (clazzez.equals(""))
+ public static void createOutClazzezModel(String clazzez,
+ TemplateFiller curmodel_tf) {
+ if (clazzez.equals("")) {
clazzez = "null";
- else
+ } else {
clazzez = clazzez.substring(0, clazzez.length() - 1);
+ }
curmodel_tf.replace("__OUTCLAZZEZ__", clazzez);
}
-
- public static void registerNode(String clazz, String path)
- {
+
+ public static void registerNode(String clazz, String path,
+ Document pluginXML, Set<String> categories) {
logger.info("registering Node " + clazz);
- registerPath(path);
-
- Node node = plugindoc.selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.nodes']");
- Element elem = (Element) node;
+ registerPath(path, pluginXML, categories);
+ Node node = pluginXML
+ .selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.nodes']");
+ Element elem = (Element) node;
- elem.addElement("node").addAttribute("factory-class", clazz).addAttribute("id", clazz).addAttribute("category-path", path);
+ elem.addElement("node").addAttribute("factory-class", clazz)
+ .addAttribute("id", clazz).addAttribute("category-path", path);
}
-
- public static void post() throws IOException
- {
+
+ public static void post(Document pluginXML, File destinationPluginXML,
+ String packageName, File destinationFQNDirectory,
+ File destinationFQNNodeDirectory, File payloadDirectory,
+ Set<String> node_names, Set<String> ext_tools) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
-
- XMLWriter writer = new XMLWriter( new FileWriter(_destdir_ + File.separator+"plugin.xml") , format );
- writer.write( plugindoc );
+ XMLWriter writer = new XMLWriter(new FileWriter(destinationPluginXML),
+ format);
+ writer.write(pluginXML);
writer.close();
-
+
// prepare binary resources
- InputStream template = TemplateResources.class.getResourceAsStream("BinaryResources.template");
- curmodel_tf = new TemplateFiller();
+ InputStream template = TemplateResources.class
+ .getResourceAsStream("BinaryResources.template");
+ TemplateFiller curmodel_tf = new TemplateFiller();
curmodel_tf.read(template);
- curmodel_tf.replace("__BASE__", _pluginpackage_);
- curmodel_tf.replace("__BINPACKNAME__", _BINPACKNAME_);
- curmodel_tf.write(_absnodedir_ + "/binres/BinaryResources.java");
+ curmodel_tf.replace("__BASE__", packageName);
+ curmodel_tf.replace("__BINPACKNAME__", packageName);
+ curmodel_tf.write(new File(destinationFQNNodeDirectory,
+ "/binres/BinaryResources.java"));
template.close();
-
- String pathsep = System.getProperty("file.separator");
-
+
//
- String[] binFiles = new File(_payloaddir_).list();
- for(String filename: binFiles)
- {
+ String[] binFiles = payloadDirectory.list();
+ for (String filename : binFiles) {
// do not copy directories
- if(new File(_payloaddir_+pathsep+filename).isDirectory())
+ if (new File(payloadDirectory, filename).isDirectory()) {
continue;
-
+ }
+
// only copy zip and ini files
- if(filename.toLowerCase().endsWith("zip"))
- {
- Helper.copyFile(new File(_payloaddir_+pathsep+filename),new File(_absnodedir_ +pathsep+"binres"+pathsep+filename));
- verifyZip(_absnodedir_ +pathsep+"binres"+pathsep+filename);
+ if (filename.toLowerCase().endsWith("zip")) {
+ Helper.copyFile(new File(payloadDirectory, filename), new File(
+ destinationFQNNodeDirectory, "binres"
+ + File.pathSeparator + filename));
+ // TODO
+ // verifyZip(destinationFQNNodeDirectory + pathsep + "binres"
+ // + pathsep + filename);
}
- if(filename.toLowerCase().endsWith("ini"))
- {
- Helper.copyFile(new File(_payloaddir_+pathsep+filename),new File(_absnodedir_ +pathsep+"binres"+pathsep+filename));
+ if (filename.toLowerCase().endsWith("ini")) {
+ Helper.copyFile(new File(payloadDirectory, filename), new File(
+ destinationFQNNodeDirectory, "binres"
+ + File.pathSeparator + filename));
}
}
-
- template = TemplateResources.class.getResourceAsStream("PluginActivator.template");
+
+ template = TemplateResources.class
+ .getResourceAsStream("PluginActivator.template");
TemplateFiller tf = new TemplateFiller();
tf.read(template);
- tf.replace("__BASE__", _pluginpackage_);
- tf.replace("__NAME__", _pluginpackage_);
- tf.write(_abspackagedir_ + File.separator+"knime"+File.separator+"PluginActivator.java");
+ tf.replace("__BASE__", packageName);
+ tf.replace("__NAME__", packageName);
+ tf.write(destinationFQNDirectory + File.separator + "knime"
+ + File.separator + "PluginActivator.java");
template.close();
-
- FileWriter ini_writer = new FileWriter(_abspackagedir_ + File.separator+"knime"+File.separator+"ExternalTools.dat");
- for(String ext_tool: ext_tools)
- ini_writer.write(ext_tool+"\n");
- ini_writer.close();
-
- ini_writer = new FileWriter(_abspackagedir_ + File.separator+"knime"+File.separator+"InternalTools.dat");
- for(String int_tool: node_names)
- ini_writer.write(int_tool+"\n");
- ini_writer.close();
- }
-
- public static void verifyZip(String filename)
- {
- boolean ok = false;
-
- Set<String> found_exes = new HashSet<String>();
-
- try
- {
- ZipInputStream zin = new ZipInputStream(new FileInputStream(filename));
- ZipEntry ze = null;
-
- while ((ze = zin.getNextEntry()) != null)
- {
- if (ze.isDirectory())
- {
- // we need a bin directory at the top level
- if(ze.getName().equals("bin/") || ze.getName().equals("bin"))
- {
- ok = true;
- }
-
- }
- else
- {
- File f = new File(ze.getName());
- if((f.getParent()!=null)&&f.getParent().equals("bin"))
- {
- found_exes.add(f.getName());
- }
- }
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
-
- if(!ok)
- {
- panic("binary archive has no toplevel bin directory : "+filename);
+
+ FileWriter ini_writer = new FileWriter(destinationFQNDirectory
+ + File.separator + "knime" + File.separator
+ + "ExternalTools.dat");
+ for (String ext_tool : ext_tools) {
+ ini_writer.write(ext_tool + "\n");
}
-
- for(String nodename: node_names)
- {
- boolean found = false;
- if(found_exes.contains(nodename)||found_exes.contains(nodename+".bin")||found_exes.contains(nodename+".exe"))
- {
- found = true;
- }
- if(!found)
- {
- panic("binary archive has no executable in bin directory for node : "+nodename);
- }
+ ini_writer.close();
+
+ ini_writer = new FileWriter(destinationFQNDirectory + File.separator
+ + "knime" + File.separator + "InternalTools.dat");
+ for (String int_tool : node_names) {
+ ini_writer.write(int_tool + "\n");
}
+ ini_writer.close();
}
-
- public static void panic(String message)
- {
- logger.severe("PANIC - "+message+" - EXITING");
- System.exit(1);
- }
-
- public static void warn(String message)
- {
- logger.warning(message);
- }
+
+ // TODO
+ // public static void verifyZip(String filename) {
+ // boolean ok = false;
+ //
+ // Set<String> found_exes = new HashSet<String>();
+ //
+ // try {
+ // ZipInputStream zin = new ZipInputStream(new FileInputStream(
+ // filename));
+ // ZipEntry ze = null;
+ //
+ // while ((ze = zin.getNextEntry()) != null) {
+ // if (ze.isDirectory()) {
+ // // we need a bin directory at the top level
+ // if (ze.getName().equals("bin/")
+ // || ze.getName().equals("bin")) {
+ // ok = true;
+ // }
+ //
+ // } else {
+ // File f = new File(ze.getName());
+ // if ((f.getParent() != null) && f.getParent().equals("bin")) {
+ // found_exes.add(f.getName());
+ // }
+ // }
+ // }
+ // } catch (Exception e) {
+ // e.printStackTrace();
+ // }
+ //
+ // if (!ok) {
+ // this.panic("binary archive has no toplevel bin directory : "
+ // + filename);
+ // }
+ //
+ // for (String nodename : this.node_names) {
+ // boolean found = false;
+ // if (found_exes.contains(nodename)
+ // || found_exes.contains(nodename + ".bin")
+ // || found_exes.contains(nodename + ".exe")) {
+ // found = true;
+ // }
+ // if (!found) {
+ // this.panic("binary archive has no executable in bin directory for node : "
+ // + nodename);
+ // }
+ // }
+ // }
}
diff --git a/src/org/ballproject/knime/nodegeneration/Utils.java b/src/org/ballproject/knime/nodegeneration/Utils.java
new file mode 100644
index 00000000..18f30acc
--- /dev/null
+++ b/src/org/ballproject/knime/nodegeneration/Utils.java
@@ -0,0 +1,52 @@
+package org.ballproject.knime.nodegeneration;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Utils {
+ /**
+ * returns all prefix paths of a given path.
+ *
+ * /foo/bar/baz --> [/foo/bar/,/foo/,/]
+ *
+ * @param path
+ * @return
+ */
+ public static List<String> getPathPrefixes(String path) {
+ List<String> ret = new ArrayList<String>();
+ File pth = new File(path);
+ ret.add(path);
+ while (pth.getParent() != null) {
+ ret.add(pth.getParent());
+ pth = pth.getParentFile();
+ }
+ return ret;
+ }
+
+ /**
+ * returns the prefix path of the given path.
+ *
+ * /foo/bar/baz ---> /foo/bar/
+ *
+ * @param path
+ * @return
+ */
+ public static String getPathPrefix(String path) {
+ File pth = new File(path);
+ return pth.getParent();
+ }
+
+ /**
+ * returns the path suffix for a given path.
+ *
+ * /foo/bar/baz --> baz
+ *
+ * @param path
+ * @return
+ */
+ public static String getPathSuffix(String path) {
+ File pth = new File(path);
+ return pth.getName();
+ }
+}
diff --git a/src/org/ballproject/knime/nodegeneration/exceptions/DuplicateNodeNameException.java b/src/org/ballproject/knime/nodegeneration/exceptions/DuplicateNodeNameException.java
new file mode 100644
index 00000000..7e1a5dcc
--- /dev/null
+++ b/src/org/ballproject/knime/nodegeneration/exceptions/DuplicateNodeNameException.java
@@ -0,0 +1,10 @@
+package org.ballproject.knime.nodegeneration.exceptions;
+
+public class DuplicateNodeNameException extends Exception {
+
+ private static final long serialVersionUID = 998799239240695103L;
+
+ public DuplicateNodeNameException(String nodeName) {
+ super("Duplicate node name \"" + nodeName + "\" detected.");
+ }
+}
diff --git a/src/org/ballproject/knime/nodegeneration/exceptions/InvalidNodeNameException.java b/src/org/ballproject/knime/nodegeneration/exceptions/InvalidNodeNameException.java
new file mode 100644
index 00000000..ce43462a
--- /dev/null
+++ b/src/org/ballproject/knime/nodegeneration/exceptions/InvalidNodeNameException.java
@@ -0,0 +1,11 @@
+package org.ballproject.knime.nodegeneration.exceptions;
+
+public class InvalidNodeNameException extends Exception {
+
+ private static final long serialVersionUID = -5097765649425062813L;
+
+ public InvalidNodeNameException(String description) {
+ super(description);
+ }
+
+}
diff --git a/src/org/ballproject/knime/nodegeneration/exceptions/UnknownMimeTypeException.java b/src/org/ballproject/knime/nodegeneration/exceptions/UnknownMimeTypeException.java
new file mode 100644
index 00000000..f35b3186
--- /dev/null
+++ b/src/org/ballproject/knime/nodegeneration/exceptions/UnknownMimeTypeException.java
@@ -0,0 +1,12 @@
+package org.ballproject.knime.nodegeneration.exceptions;
+
+import org.ballproject.knime.base.mime.MIMEtype;
+
+public class UnknownMimeTypeException extends Exception {
+
+ private static final long serialVersionUID = 598884824362988075L;
+
+ public UnknownMimeTypeException(MIMEtype type) {
+ super("Unknown MIME type: " + type.getExt());
+ }
+}
|
2f40ce3e2a5e244315c16865967f58930f57cf7c
|
ReactiveX-RxJava
|
Added takeLast to Observable--
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java
index 0df09cb3c7..d234a73ba2 100644
--- a/rxjava-core/src/main/java/rx/Observable.java
+++ b/rxjava-core/src/main/java/rx/Observable.java
@@ -1347,6 +1347,22 @@ public static <T> Observable<T> take(final Observable<T> items, final int num) {
return _create(OperationTake.take(items, num));
}
+ /**
+ * Returns an Observable that emits the last <code>count</code> items emitted by the source
+ * Observable.
+ *
+ * @param items
+ * the source Observable
+ * @param count
+ * the number of items from the end of the sequence emitted by the source
+ * Observable to emit
+ * @return an Observable that only emits the last <code>count</code> items emitted by the source
+ * Observable
+ */
+ public static <T> Observable<T> takeLast(final Observable<T> items, final int count) {
+ return _create(OperationTakeLast.takeLast(items, count));
+ }
+
/**
* Returns an Observable that emits a single item, a list composed of all the items emitted by
* the source Observable.
@@ -2235,6 +2251,20 @@ public Observable<T> take(final int num) {
return take(this, num);
}
+ /**
+ * Returns an Observable that emits the last <code>count</code> items emitted by the source
+ * Observable.
+ *
+ * @param count
+ * the number of items from the end of the sequence emitted by the source
+ * Observable to emit
+ * @return an Observable that only emits the last <code>count</code> items emitted by the source
+ * Observable
+ */
+ public Observable<T> takeLast(final int count) {
+ return takeLast(this, count);
+ }
+
/**
* Returns an Observable that emits a single item, a list composed of all the items emitted by
* the source Observable.
diff --git a/rxjava-core/src/main/java/rx/operators/OperationTakeLast.java b/rxjava-core/src/main/java/rx/operators/OperationTakeLast.java
index a3116dea58..57e336739e 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationTakeLast.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationTakeLast.java
@@ -23,13 +23,14 @@
import rx.util.functions.Func1;
import java.util.Iterator;
-import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
-import java.util.concurrent.atomic.AtomicInteger;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
+/**
+ * Returns a specified number of contiguous elements from the end of an observable sequence.
+ */
public final class OperationTakeLast {
public static <T> Func1<Observer<T>, Subscription> takeLast(final Observable<T> items, final int count) {
|
30f9f278c3430f9e936f566ee8b3394f86f2b01e
|
elasticsearch
|
Added UNICODE_CHARACTER_CLASS support to Regex- flags. This flag is only supported in Java7 and is ignored if set on a java 6- JVM--Closes -2895-
|
a
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/common/regex/Regex.java b/src/main/java/org/elasticsearch/common/regex/Regex.java
index 4a9a772737133..683feeae3c171 100644
--- a/src/main/java/org/elasticsearch/common/regex/Regex.java
+++ b/src/main/java/org/elasticsearch/common/regex/Regex.java
@@ -22,12 +22,20 @@
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.common.Strings;
+import java.util.Locale;
import java.util.regex.Pattern;
/**
*
*/
public class Regex {
+
+ /**
+ * This Regex / {@link Pattern} flag is supported from Java 7 on.
+ * If set on a Java6 JVM the flag will be ignored.
+ *
+ */
+ public static final int UNICODE_CHARACTER_CLASS = 0x100; // supported in JAVA7
/**
* Is the str a simple match pattern.
@@ -107,22 +115,25 @@ public static int flagsFromString(String flags) {
if (s.isEmpty()) {
continue;
}
- if ("CASE_INSENSITIVE".equalsIgnoreCase(s)) {
+ s = s.toUpperCase(Locale.ROOT);
+ if ("CASE_INSENSITIVE".equals(s)) {
pFlags |= Pattern.CASE_INSENSITIVE;
- } else if ("MULTILINE".equalsIgnoreCase(s)) {
+ } else if ("MULTILINE".equals(s)) {
pFlags |= Pattern.MULTILINE;
- } else if ("DOTALL".equalsIgnoreCase(s)) {
+ } else if ("DOTALL".equals(s)) {
pFlags |= Pattern.DOTALL;
- } else if ("UNICODE_CASE".equalsIgnoreCase(s)) {
+ } else if ("UNICODE_CASE".equals(s)) {
pFlags |= Pattern.UNICODE_CASE;
- } else if ("CANON_EQ".equalsIgnoreCase(s)) {
+ } else if ("CANON_EQ".equals(s)) {
pFlags |= Pattern.CANON_EQ;
- } else if ("UNIX_LINES".equalsIgnoreCase(s)) {
+ } else if ("UNIX_LINES".equals(s)) {
pFlags |= Pattern.UNIX_LINES;
- } else if ("LITERAL".equalsIgnoreCase(s)) {
+ } else if ("LITERAL".equals(s)) {
pFlags |= Pattern.LITERAL;
- } else if ("COMMENTS".equalsIgnoreCase(s)) {
+ } else if ("COMMENTS".equals(s)) {
pFlags |= Pattern.COMMENTS;
+ } else if ("UNICODE_CHAR_CLASS".equals(s)) {
+ pFlags |= UNICODE_CHARACTER_CLASS;
} else {
throw new ElasticSearchIllegalArgumentException("Unknown regex flag [" + s + "]");
}
@@ -155,6 +166,9 @@ public static String flagsToString(int flags) {
}
if ((flags & Pattern.COMMENTS) != 0) {
sb.append("COMMENTS|");
+ }
+ if ((flags & UNICODE_CHARACTER_CLASS) != 0) {
+ sb.append("UNICODE_CHAR_CLASS|");
}
return sb.toString();
}
diff --git a/src/test/java/org/elasticsearch/test/unit/common/regex/RegexTests.java b/src/test/java/org/elasticsearch/test/unit/common/regex/RegexTests.java
new file mode 100644
index 0000000000000..2d1bf6f222afc
--- /dev/null
+++ b/src/test/java/org/elasticsearch/test/unit/common/regex/RegexTests.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to ElasticSearch and Shay Banon under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. ElasticSearch 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.elasticsearch.test.unit.common.regex;
+
+import java.util.Random;
+import java.util.regex.Pattern;
+
+import org.elasticsearch.common.regex.Regex;
+import org.testng.annotations.Test;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+public class RegexTests {
+
+ @Test
+ public void testFlags() {
+ String[] supportedFlags = new String[] { "CASE_INSENSITIVE", "MULTILINE", "DOTALL", "UNICODE_CASE", "CANON_EQ", "UNIX_LINES",
+ "LITERAL", "COMMENTS", "UNICODE_CHAR_CLASS" };
+ int[] flags = new int[] { Pattern.CASE_INSENSITIVE, Pattern.MULTILINE, Pattern.DOTALL, Pattern.UNICODE_CASE, Pattern.CANON_EQ,
+ Pattern.UNIX_LINES, Pattern.LITERAL, Pattern.COMMENTS, Regex.UNICODE_CHARACTER_CLASS };
+ long seed = System.currentTimeMillis();
+ Random random = new Random(seed);
+ int num = 10 + random.nextInt(100);
+ for (int i = 0; i < num; i++) {
+ int numFlags = random.nextInt(flags.length+1);
+ int current = 0;
+ StringBuilder builder = new StringBuilder();
+ for (int j = 0; j < numFlags; j++) {
+ int index = random.nextInt(flags.length);
+ current |= flags[index];
+ builder.append(supportedFlags[index]);
+ if (j < numFlags-1) {
+ builder.append("|");
+ }
+ }
+ String flagsToString = Regex.flagsToString(current);
+ assertThat(Regex.flagsFromString(builder.toString()), equalTo(current));
+ assertThat(Regex.flagsFromString(builder.toString()), equalTo(Regex.flagsFromString(flagsToString)));
+ Pattern.compile("\\w\\d{1,2}", current); // accepts the flags?
+ }
+ }
+}
\ No newline at end of file
|
0d1908fbb2a1e5d68b1b38b0feaa1f1a40e76d5b
|
orientdb
|
Fixed a bug on browsing clusters in transaction- as issue https://github.com/tinkerpop/blueprints/issues/312--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java
index eee78457d84..43e1c1231f8 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java
@@ -43,7 +43,7 @@ public ORecordIteratorCluster(final ODatabaseRecord iDatabase, final ODatabaseRe
totalAvailableRecords = database.countClusterElements(current.clusterId);
- txEntries = iDatabase.getTransaction().getRecordEntriesByClusterIds(new int[] { iClusterId });
+ txEntries = iDatabase.getTransaction().getNewRecordEntriesByClusterIds(new int[] { iClusterId });
if (txEntries != null)
// ADJUST TOTAL ELEMENT BASED ON CURRENT TRANSACTION'S ENTRIES
diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorClusters.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorClusters.java
index aea639f5116..c8695a7a50d 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorClusters.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorClusters.java
@@ -367,7 +367,7 @@ protected void config() {
totalAvailableRecords = database.countClusterElements(clusterIds);
- txEntries = database.getTransaction().getRecordEntriesByClusterIds(clusterIds);
+ txEntries = database.getTransaction().getNewRecordEntriesByClusterIds(clusterIds);
if (txEntries != null)
// ADJUST TOTAL ELEMENT BASED ON CURRENT TRANSACTION'S ENTRIES
diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java
index 2e80f344c9e..7bc9a7e4bd4 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java
@@ -63,7 +63,7 @@ public void saveRecord(ORecordInternal<?> iContent, String iClusterName, OPERATI
public List<ORecordOperation> getRecordEntriesByClass(String iClassName);
- public List<ORecordOperation> getRecordEntriesByClusterIds(int[] iIds);
+ public List<ORecordOperation> getNewRecordEntriesByClusterIds(int[] iIds);
public ORecordInternal<?> getRecord(ORID iRid);
diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java
index 08b6f936ec4..c54ddc43dc8 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java
@@ -117,7 +117,7 @@ public List<ORecordOperation> getRecordEntriesByClass(String iClassName) {
return null;
}
- public List<ORecordOperation> getRecordEntriesByClusterIds(int[] iIds) {
+ public List<ORecordOperation> getNewRecordEntriesByClusterIds(int[] iIds) {
return null;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionRealAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionRealAbstract.java
index 047a11ddf76..2994820da20 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionRealAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionRealAbstract.java
@@ -161,19 +161,21 @@ public List<ORecordOperation> getRecordEntriesByClass(final String iClassName) {
/**
* Called by cluster iterator.
*/
- public List<ORecordOperation> getRecordEntriesByClusterIds(final int[] iIds) {
+ public List<ORecordOperation> getNewRecordEntriesByClusterIds(final int[] iIds) {
final List<ORecordOperation> result = new ArrayList<ORecordOperation>();
if (iIds == null)
// RETURN ALL THE RECORDS
for (ORecordOperation entry : recordEntries.values()) {
- result.add(entry);
+ if (entry.type == ORecordOperation.CREATED)
+ result.add(entry);
}
else
// FILTER RECORDS BY ID
for (ORecordOperation entry : recordEntries.values()) {
for (int id : iIds) {
- if (entry.getRecord() != null && entry.getRecord().getIdentity().getClusterId() == id) {
+ if (entry.getRecord() != null && entry.getRecord().getIdentity().getClusterId() == id
+ && entry.type == ORecordOperation.CREATED) {
result.add(entry);
break;
}
|
db57f0af3a110ed418bb0177cbc46ed4c7672c82
|
camel
|
Removed the printStackTrace line in the- CxfWsdlFirstTest--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@665997 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
index cd21176baabe0..0503dcbe21d31 100644
--- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
+++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
@@ -94,7 +94,6 @@ public void testInvokingServiceFromCXFClient() throws Exception {
fail("We expect to get the UnknowPersonFault here");
} catch (UnknownPersonFault fault) {
// We expect to get fault here
- fault.printStackTrace();
}
}
|
10d01bb9da84d588f57a824ef9dc048562af2f7a
|
Mylyn Reviews
|
bug 386204: Allow users to include subtasks in changeset view
Refactored part and introduced a model, which allows including subtasks.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=386204
Change-Id: I94af1aa42624b69f280d8dca54c8020f877a9f45
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java
index b1787d9b..2ca7ca10 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java
@@ -14,25 +14,37 @@
import java.util.List;
import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.ToolBarManager;
+import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.mylyn.internal.tasks.ui.editors.Messages;
+import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.ITaskContainer;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
import org.eclipse.mylyn.versions.core.ChangeSet;
import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping;
import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet;
+import org.eclipse.mylyn.versions.tasks.ui.internal.IChangesetModel;
+import org.eclipse.mylyn.versions.tasks.ui.internal.IncludeSubTasksAction;
+import org.eclipse.mylyn.versions.tasks.ui.internal.TaskChangesetLabelProvider;
+import org.eclipse.mylyn.versions.tasks.ui.internal.TaskVersionsUiPlugin;
import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
+import org.eclipse.ui.forms.events.HyperlinkAdapter;
+import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
@@ -43,40 +55,8 @@
*/
@SuppressWarnings("restriction")
public class ChangesetPart extends AbstractTaskEditorPart {
- private static final class TaskChangesetLabelProvider implements
- ITableLabelProvider {
- public void addListener(ILabelProviderListener listener) {
- }
-
- public void dispose() {
- }
-
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- public void removeListener(ILabelProviderListener listener) {
- }
-
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
- public String getColumnText(Object element, int columnIndex) {
- TaskChangeSet cs = ((TaskChangeSet) element);
- switch (columnIndex) {
- case 0:
- return cs.getChangeset().getId();
- case 1:
- return cs.getChangeset().getMessage();
- case 2:
- return cs.getChangeset().getAuthor().getEmail();
- case 3:
- return cs.getChangeset().getDate().toString();
- }
- return element.toString() + " " + columnIndex;
- }
- }
+ private TableViewer table;
+ private ChangesetModel model = new ChangesetModel();
public ChangesetPart() {
setPartName("Changeset");
@@ -87,7 +67,7 @@ public ChangesetPart() {
public void createControl(Composite parent, FormToolkit toolkit) {
Section createSection = createSection(parent, toolkit);
Composite composite = createContentComposite(toolkit, createSection);
-
+
createTable(composite);
}
@@ -113,7 +93,7 @@ private Section createSection(Composite parent, FormToolkit toolkit) {
}
private void createTable(Composite composite) {
- TableViewer table = new TableViewer(composite);
+ table = new TableViewer(composite);
table.getTable().setLinesVisible(true);
table.getTable().setHeaderVisible(true);
addColumn(table, "Id");
@@ -122,11 +102,22 @@ private void createTable(Composite composite) {
addColumn(table, "Date");
table.setContentProvider(ArrayContentProvider.getInstance());
table.setLabelProvider(new TaskChangesetLabelProvider());
- table.setInput(getInput());
+ refreshInput();
+ registerContextMenu(table);
+ }
+
+ @Override
+ protected void fillToolBar(ToolBarManager toolBarManager) {
+ super.fillToolBar(toolBarManager);
+ toolBarManager.add(new IncludeSubTasksAction(model));
+ }
+
+ private void registerContextMenu(TableViewer table) {
MenuManager menuManager = new MenuManager();
menuManager.setRemoveAllWhenShown(true);
getTaskEditorPage().getEditorSite().registerContextMenu(
- "org.eclipse.mylyn.versions.changesets", menuManager, table, true);
+ "org.eclipse.mylyn.versions.changesets", menuManager, table,
+ true);
Menu menu = menuManager.createContextMenu(table.getControl());
table.getTable().setMenu(menu);
}
@@ -138,40 +129,88 @@ private void addColumn(TableViewer table, String name) {
tableViewerColumn.getColumn().setWidth(100);
}
- private List<TaskChangeSet> getInput() {
- int score = Integer.MIN_VALUE;
+ private AbstractChangesetMappingProvider determineBestProvider(
+ final ITask task) {
AbstractChangesetMappingProvider bestProvider = null;
- final ITask task = getModel().getTask();
-
+ int score = Integer.MIN_VALUE;
for (AbstractChangesetMappingProvider mappingProvider : TaskChangesetUtil
.getMappingProviders()) {
- if (score < mappingProvider.getScoreFor(task))
- ;
- {
+ if (score < mappingProvider.getScoreFor(task)) {
bestProvider = mappingProvider;
}
}
- final List<TaskChangeSet> changesets = new ArrayList<TaskChangeSet>();
- try {
+ return bestProvider;
+ }
- IChangeSetMapping changesetsMapping = new IChangeSetMapping() {
+ private IChangeSetMapping createChangeSetMapping(final ITask task,
+ final List<TaskChangeSet> changesets) {
+ return new IChangeSetMapping() {
- public ITask getTask() {
- return task;
- }
+ public ITask getTask() {
+ return task;
+ }
+
+ public void addChangeSet(ChangeSet changeset) {
+ changesets.add(new TaskChangeSet(task, changeset));
+ }
+ };
+ }
+
+ private void refreshInput() {
+ table.setInput(model.getInput());
+ }
+
+ private class ChangesetModel implements IChangesetModel {
+
+ private boolean includeSubTasks;
- public void addChangeSet(ChangeSet changeset) {
- changesets.add(new TaskChangeSet(task, changeset));
+ public boolean isIncludeSubTasks() {
+ return includeSubTasks;
+ }
+
+ public void setIncludeSubTasks(boolean includeSubTasks) {
+ boolean isChanged = this.includeSubTasks ^ includeSubTasks;
+ this.includeSubTasks = includeSubTasks;
+ if (isChanged) {
+ refreshInput();
+ }
+ }
+
+ public List<TaskChangeSet> getInput() {
+ final ITask task = getModel().getTask();
+
+ AbstractChangesetMappingProvider bestProvider = determineBestProvider(task);
+ final List<TaskChangeSet> changesets = new ArrayList<TaskChangeSet>();
+
+ final List<IChangeSetMapping> changesetsMapping = new ArrayList<IChangeSetMapping>();
+ changesetsMapping.add(createChangeSetMapping(task, changesets));
+ ;
+ if (includeSubTasks) {
+ if (task instanceof ITaskContainer) {
+ ITaskContainer taskContainer = (ITaskContainer) task;
+ for (ITask subTask : taskContainer.getChildren()) {
+ changesetsMapping.add(createChangeSetMapping(subTask,
+ changesets));
+ }
}
- };
- // FIXME progress monitor
- bestProvider.getChangesetsForTask(changesetsMapping,
- new NullProgressMonitor());
- } catch (CoreException e) {
- // FIXME Auto-generated catch block
- e.printStackTrace();
+ }
+ final AbstractChangesetMappingProvider provider = bestProvider;
+ BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
+
+ public void run() {
+ try {
+ for (IChangeSetMapping csm : changesetsMapping) {
+ provider.getChangesetsForTask(csm,
+ new NullProgressMonitor());
+ }
+ } catch (CoreException e) {
+ getTaskEditorPage().getTaskEditor().setMessage("An exception occurred " + e.getMessage(), IMessageProvider.ERROR);
+ }
+ }
+
+ });
+
+ return changesets;
}
- return changesets;
}
-
}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java
new file mode 100644
index 00000000..8839451c
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java
@@ -0,0 +1,18 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.ui.internal;
+
+/**
+ * @author Kilian Matt
+ */
+public interface IChangesetModel {
+ public void setIncludeSubTasks(boolean includeSubTasks);
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java
new file mode 100644
index 00000000..1ae383c8
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.ui.internal;
+
+import org.eclipse.jface.action.Action;
+import org.eclipse.mylyn.tasks.ui.TasksUiImages;
+import org.eclipse.swt.widgets.Event;
+
+/**
+ * @author Kilian Matt
+ */
+public class IncludeSubTasksAction extends Action {
+ private IChangesetModel model;
+
+ public IncludeSubTasksAction(IChangesetModel model) {
+ super("Include subtasks",AS_CHECK_BOX);
+ setImageDescriptor(TasksUiImages.TASK_NEW_SUB);
+ this.model = model;
+ }
+
+ public void run() {
+ model.setIncludeSubTasks(isChecked());
+ }
+
+ public void runWithEvent(Event event) {
+ model.setIncludeSubTasks(isChecked());
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java
new file mode 100644
index 00000000..966afc90
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.ui.internal;
+
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * @author Kilian Matt
+ */
+public class TaskChangesetLabelProvider implements ITableLabelProvider {
+ public void addListener(ILabelProviderListener listener) {
+ }
+
+ public void dispose() {
+ }
+
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ public void removeListener(ILabelProviderListener listener) {
+ }
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ return null;
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ TaskChangeSet cs = ((TaskChangeSet) element);
+ switch (columnIndex) {
+ case 0:
+ return cs.getChangeset().getId();
+ case 1:
+ return cs.getChangeset().getMessage();
+ case 2:
+ return cs.getChangeset().getAuthor().getEmail();
+ case 3:
+ return cs.getChangeset().getDate().toString();
+ }
+ return element.toString() + " " + columnIndex;
+ }
+}
|
497c7441ad1370b383d3c00c614d32dec4ef1952
|
Delta Spike
|
DELTASPIKE-277 fix JsfMessageProducer type detection
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/message/JsfMessageProducer.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/message/JsfMessageProducer.java
index 6dc58b8a7..2a26c82d4 100644
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/message/JsfMessageProducer.java
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/message/JsfMessageProducer.java
@@ -23,6 +23,9 @@
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
import org.apache.deltaspike.core.util.ReflectionUtils;
import org.apache.deltaspike.jsf.message.JsfMessage;
@@ -36,13 +39,24 @@ public class JsfMessageProducer
@Dependent
public JsfMessage createJsfMessage(InjectionPoint injectionPoint)
{
- return createJsfMessageFor(injectionPoint, ReflectionUtils.getRawType(injectionPoint.getType()));
+ if (! (injectionPoint.getType() instanceof ParameterizedType))
+ {
+ throw new IllegalArgumentException("JsfMessage must be used as generic type");
+ }
+ ParameterizedType paramType = (ParameterizedType) injectionPoint.getType();
+ Type[] actualTypes = paramType.getActualTypeArguments();
+ if (actualTypes.length != 1)
+ {
+ throw new IllegalArgumentException("JsfMessage must have the MessageBundle as generic type parameter");
+ }
+
+ return createJsfMessageFor(injectionPoint, actualTypes[0]);
}
- private JsfMessage createJsfMessageFor(InjectionPoint injectionPoint, Class<Object> rawType)
+ private JsfMessage createJsfMessageFor(InjectionPoint injectionPoint, Type rawType)
{
//X TODO check if the JsfMessage should get injected into a UIComponent and use #getClientId()
- return new DefaultJsfMessage(rawType, null);
+ return new DefaultJsfMessage((Class) rawType, null);
}
}
diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/beans/BackingBean.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/beans/ViewScopedBackingBean.java
similarity index 95%
rename from deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/beans/BackingBean.java
rename to deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/beans/ViewScopedBackingBean.java
index cf6eb6cea..cb59e88b5 100644
--- a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/beans/BackingBean.java
+++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/view/beans/ViewScopedBackingBean.java
@@ -27,7 +27,7 @@
*/
@ViewScoped
@Named("viewScopedBean")
-public class BackingBean implements Serializable
+public class ViewScopedBackingBean implements Serializable
{
private int i = 0;
|
dc9563874163393853426a050003de459a86f048
|
kotlin
|
Method cache for ClassDescriptorSerializer--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/tests/org/jetbrains/jet/test/util/NamespaceComparator.java b/compiler/tests/org/jetbrains/jet/test/util/NamespaceComparator.java
index 0f7ad6edcbf3f..96435ae1283ad 100644
--- a/compiler/tests/org/jetbrains/jet/test/util/NamespaceComparator.java
+++ b/compiler/tests/org/jetbrains/jet/test/util/NamespaceComparator.java
@@ -728,12 +728,18 @@ public void serialize(ClassDescriptor klass) {
}
}
+ private static final MethodCache CLASS_OBJECT_SERIALIZER_METHOD_CACHE = new MethodCache(ClassObjectSerializer.class);
private class ClassObjectSerializer extends FullContentSerialier {
private ClassObjectSerializer(StringBuilder sb) {
super(sb);
}
+ @Override
+ protected MethodCache doGetMethodCache() {
+ return CLASS_OBJECT_SERIALIZER_METHOD_CACHE;
+ }
+
@Override
public void serialize(ClassKind kind) {
assert kind == ClassKind.OBJECT : "Must be called for class objects only";
|
d7929a40521731c53f510996bf9918ff3b158e3d
|
Delta Spike
|
DELTASPIKE-378 add ProjectStageAware property handling
Main entry point for this feature is
ConfigResolver#getProjectStageAwarePropertyValue
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java
index 43bb6602f..05cbc59df 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java
@@ -31,9 +31,11 @@
import javax.enterprise.inject.Typed;
+import org.apache.deltaspike.core.api.projectstage.ProjectStage;
import org.apache.deltaspike.core.spi.config.ConfigSource;
import org.apache.deltaspike.core.spi.config.ConfigSourceProvider;
import org.apache.deltaspike.core.util.ClassUtils;
+import org.apache.deltaspike.core.util.ProjectStageProducer;
import org.apache.deltaspike.core.util.ServiceUtils;
/**
@@ -56,6 +58,8 @@ public final class ConfigResolver
private static Map<ClassLoader, ConfigSource[]> configSources
= new ConcurrentHashMap<ClassLoader, ConfigSource[]>();
+ private static volatile ProjectStage projectStage = null;
+
private ConfigResolver()
{
// this is a utility class which doesn't get instantiated.
@@ -146,6 +150,35 @@ public static String getPropertyValue(String key)
return null;
}
+ /**
+ * <p>Search for the configured value in all {@link ConfigSource}s and take the
+ * current {@link org.apache.deltaspike.core.api.projectstage.ProjectStage}
+ * into account.</p>
+ *
+ * <p>It first will search if there is a configured value of the given key prefixed
+ * with the current ProjectStage (e.g. 'myproject.myconfig.Production') and if this didn't
+ * find anything it will lookup the given key without any prefix.</p>
+ *
+ * <p><b>Attention</b> This method must only be used after all ConfigSources
+ * got registered and it also must not be used to determine the ProjectStage itself.</p>
+ * @param key
+ * @param defaultValue
+ * @return the configured value or if non found the defaultValue
+ *
+ */
+ public static String getProjectStageAwarePropertyValue(String key, String defaultValue)
+ {
+ ProjectStage ps = getProjectStage();
+
+ String value = getPropertyValue(key + '.' + ps, defaultValue);
+ if (value == null)
+ {
+ value = getPropertyValue(key, defaultValue);
+ }
+
+ return value;
+ }
+
/**
* Resolve all values for the given key, from all registered ConfigSources ordered by their
* ordinal value in ascending ways. If more {@link ConfigSource}s have the same ordinal, their
@@ -264,4 +297,17 @@ public int compare(ConfigSource configSource1, ConfigSource configSource2)
return configSources;
}
+ private static ProjectStage getProjectStage()
+ {
+ if (projectStage == null)
+ {
+ synchronized (ConfigResolver.class)
+ {
+ projectStage = ProjectStageProducer.getInstance().getProjectStage();
+ }
+ }
+
+ return projectStage;
+ }
+
}
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java
index ba4ac6b28..f2e39bf53 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java
@@ -47,6 +47,7 @@
* }
* </pre>
*
+ * <p>Please note that there can only be one ProjectStage per EAR.</p>
*/
@ApplicationScoped
public class ProjectStageProducer implements Serializable
diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java
index 809ccc1df..70c00e802 100644
--- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java
+++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java
@@ -19,6 +19,8 @@
package org.apache.deltaspike.test.api.config;
import org.apache.deltaspike.core.api.config.ConfigResolver;
+import org.apache.deltaspike.core.api.projectstage.ProjectStage;
+import org.apache.deltaspike.core.util.ProjectStageProducer;
import org.junit.Assert;
import org.junit.Test;
@@ -50,4 +52,12 @@ public void testStandaloneConfigSource()
Assert.assertNull(ConfigResolver.getPropertyValue("notexisting"));
Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey"));
}
+
+ @Test
+ public void testGetProjectStageAwarePropertyValue()
+ {
+ ProjectStageProducer.setProjectStage(ProjectStage.UnitTest);
+ Assert.assertNull(ConfigResolver.getProjectStageAwarePropertyValue("notexisting", null));
+ Assert.assertEquals("unittestvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey", null));
+ }
}
diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java
index 581c837e3..ed9dc8667 100644
--- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java
+++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java
@@ -33,6 +33,15 @@ public class TestConfigSource implements ConfigSource
private int ordinal = 700;
+ private Map<String, String> props = new HashMap<String, String>();
+
+
+ public TestConfigSource()
+ {
+ props.put("testkey", "testvalue");
+ props.put("testkey.UnitTest", "unittestvalue");
+ }
+
@Override
public String getConfigName()
{
@@ -48,15 +57,13 @@ public int getOrdinal()
@Override
public String getPropertyValue(String key)
{
- return "testkey".equals(key) ? "testvalue" : null;
+ return props.get(key);
}
@Override
public Map<String, String> getProperties()
{
- Map<String, String> map = new HashMap<String, String>();
- map.put("testkey", "testvalue");
- return map;
+ return props;
}
@Override
|
1927f040774aa75d2dfe1d95fae9b43ee821361b
|
hbase
|
HBASE-13958 RESTApiClusterManager calls kill()- instead of suspend() and resume()--
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-it/src/test/java/org/apache/hadoop/hbase/RESTApiClusterManager.java b/hbase-it/src/test/java/org/apache/hadoop/hbase/RESTApiClusterManager.java
index 28fac4ee2bf2..9ea126a0af90 100644
--- a/hbase-it/src/test/java/org/apache/hadoop/hbase/RESTApiClusterManager.java
+++ b/hbase-it/src/test/java/org/apache/hadoop/hbase/RESTApiClusterManager.java
@@ -158,12 +158,12 @@ public void kill(ServiceType service, String hostname, int port) throws IOExcept
@Override
public void suspend(ServiceType service, String hostname, int port) throws IOException {
- hBaseClusterManager.kill(service, hostname, port);
+ hBaseClusterManager.suspend(service, hostname, port);
}
@Override
public void resume(ServiceType service, String hostname, int port) throws IOException {
- hBaseClusterManager.kill(service, hostname, port);
+ hBaseClusterManager.resume(service, hostname, port);
}
|
32510df2df13cdf6a03ead228a2b4f2c6be67b6b
|
drools
|
fix incremental compilation when updating a- kiemodule without changing the release id (for snaphots)--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java
index 2a670144eeb..9162fbd3ed8 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java
@@ -73,7 +73,11 @@ public void updateToVersion(ReleaseId newReleaseId) {
throw new UnsupportedOperationException( "It is not possible to update a classpath container to a new version." );
}
ReleaseId currentReleaseId = kProject.getGAV();
- InternalKieModule currentKM = (InternalKieModule) kr.getKieModule( currentReleaseId );
+
+ // if the new and the current release are equal (a snapshot) check if there is an older version with the same releaseId
+ InternalKieModule currentKM = currentReleaseId.equals( newReleaseId ) && !currentReleaseId.equals(kr.getDefaultReleaseId()) ?
+ (InternalKieModule) ((KieRepositoryImpl)kr).getOldKieModule( currentReleaseId ) :
+ (InternalKieModule) kr.getKieModule( currentReleaseId );
InternalKieModule newKM = (InternalKieModule) kr.getKieModule( newReleaseId );
ChangeSetBuilder csb = new ChangeSetBuilder();
diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieRepositoryImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieRepositoryImpl.java
index 85ffd7a9701..50f6c5c7173 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieRepositoryImpl.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieRepositoryImpl.java
@@ -70,10 +70,13 @@ public KieModule getKieModule(ReleaseId releaseId) {
return getKieModule(releaseId, null);
}
- public KieModule getKieModule(ReleaseId releaseId, byte[] pomXml) {
- VersionRange versionRange = new VersionRange(releaseId.getVersion());
+ KieModule getOldKieModule(ReleaseId releaseId) {
+ KieModule kieModule = kieModuleRepo.loadOldAndRemove(releaseId);
+ return kieModule != null ? kieModule : getKieModule(releaseId);
+ }
- KieModule kieModule = kieModuleRepo.load(releaseId, versionRange);
+ public KieModule getKieModule(ReleaseId releaseId, byte[] pomXml) {
+ KieModule kieModule = kieModuleRepo.load(releaseId);
if ( kieModule == null ) {
log.debug( "KieModule Lookup. ReleaseId {} was not in cache, checking classpath",
releaseId.toExternalForm() );
@@ -188,6 +191,7 @@ public KieModule getKieModule(Resource resource) {
private static class KieModuleRepo {
private final Map<String, TreeMap<ComparableVersion, KieModule>> kieModules = new HashMap<String, TreeMap<ComparableVersion, KieModule>>();
+ private final Map<ReleaseId, KieModule> oldKieModules = new HashMap<ReleaseId, KieModule>();
void store(KieModule kieModule) {
ReleaseId releaseId = kieModule.getReleaseId();
@@ -198,7 +202,19 @@ void store(KieModule kieModule) {
artifactMap = new TreeMap<ComparableVersion, KieModule>();
kieModules.put(ga, artifactMap);
}
- artifactMap.put(new ComparableVersion(releaseId.getVersion()), kieModule);
+ ComparableVersion comparableVersion = new ComparableVersion(releaseId.getVersion());
+ if (oldKieModules.get(releaseId) == null) {
+ oldKieModules.put(releaseId, artifactMap.get(comparableVersion));
+ }
+ artifactMap.put(comparableVersion, kieModule);
+ }
+
+ private KieModule loadOldAndRemove(ReleaseId releaseId) {
+ return oldKieModules.remove(releaseId);
+ }
+
+ KieModule load(ReleaseId releaseId) {
+ return load(releaseId, new VersionRange(releaseId.getVersion()));
}
KieModule load(ReleaseId releaseId, VersionRange versionRange) {
|
b0d00c5b3003a233c793a0f092f15358530a0acb
|
orientdb
|
Implemented new commands: - truncate cluster -- truncate class--
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/tools/src/main/java/com/orientechnologies/orient/console/OConsoleDatabaseApp.java b/tools/src/main/java/com/orientechnologies/orient/console/OConsoleDatabaseApp.java
index b64c9f90d29..bbd44e84cc6 100644
--- a/tools/src/main/java/com/orientechnologies/orient/console/OConsoleDatabaseApp.java
+++ b/tools/src/main/java/com/orientechnologies/orient/console/OConsoleDatabaseApp.java
@@ -177,10 +177,14 @@ public void createDatabase(
@ConsoleCommand(description = "Create a new cluster in the current database. The cluster can be physical or logical.")
public void createCluster(
@ConsoleParameter(name = "cluster-name", description = "The name of the cluster to create") String iClusterName,
- @ConsoleParameter(name = "cluster-type", description = "Cluster type: 'physical' or 'logical'") String iClusterType) {
+ @ConsoleParameter(name = "cluster-type", description = "Cluster type: 'physical' or 'logical'") String iClusterType,
+ @ConsoleParameter(name = "position", description = "cluster id to replace an empty position or 'append' to append at the end") String iPosition) {
checkCurrentDatabase();
- out.println("Creating cluster [" + iClusterName + "] of type '" + iClusterType + "' in database " + currentDatabaseName + "...");
+ final int position = iPosition.toUpperCase().equals("append") ? -1 : Integer.parseInt(iPosition);
+
+ out.println("Creating cluster [" + iClusterName + "] of type '" + iClusterType + "' in database " + currentDatabaseName
+ + (position == -1 ? " as last one" : " in place of #" + position) + "...");
int clusterId = iClusterType.equalsIgnoreCase("physical") ? currentDatabase.addPhysicalCluster(iClusterName, iClusterName, -1)
: currentDatabase.addLogicalCluster(iClusterName, currentDatabase.getClusterIdByName(OStorage.CLUSTER_INTERNAL_NAME));
@@ -226,7 +230,7 @@ public void truncateCluster(
cluster.truncate();
- out.println("Truncated " + recs + "records from cluster [" + iClusterName + "] in database " + currentDatabaseName);
+ out.println("Truncated " + recs + " records from cluster [" + iClusterName + "] in database " + currentDatabaseName);
} catch (Exception e) {
out.println("ERROR: " + e.toString());
}
@@ -245,7 +249,7 @@ public void truncateClass(
cls.truncate();
- out.println("Truncated " + recs + "records from class [" + iClassName + "] in database " + currentDatabaseName);
+ out.println("Truncated " + recs + " records from class [" + iClassName + "] in database " + currentDatabaseName);
} catch (Exception e) {
out.println("ERROR: " + e.toString());
}
|
b8acac413b1c85a29a86026b984591fdc9c333fa
|
camel
|
CAMEL-2510 Fixed the issue of Mixing jetty/http- in a route screws up the URI used by HttpClient--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@917529 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpProducerHelper.java b/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpProducerHelper.java
index bc7b7c9e42b24..e553352cdafd2 100644
--- a/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpProducerHelper.java
+++ b/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpProducerHelper.java
@@ -16,7 +16,11 @@
*/
package org.apache.camel.component.http.helper;
+import java.net.URI;
+import java.net.URISyntaxException;
+
import org.apache.camel.Exchange;
+import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.http.HttpEndpoint;
import org.apache.camel.component.http.HttpMethods;
@@ -47,18 +51,44 @@ public static String createURL(Exchange exchange, HttpEndpoint endpoint) {
}
// append HTTP_PATH to HTTP_URI if it is provided in the header
- // when the endpoint is not working as a bridge
String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class);
if (path != null) {
- // make sure that there is exactly one "/" between HTTP_URI and
- // HTTP_PATH
- if (!uri.endsWith("/")) {
- uri = uri + "/";
- }
if (path.startsWith("/")) {
- path = path.substring(1);
+ URI baseURI;
+ String baseURIString = exchange.getIn().getHeader(Exchange.HTTP_BASE_URI, String.class);
+ try {
+ if (baseURIString == null) {
+ if (exchange.getFromEndpoint() != null) {
+ baseURIString = exchange.getFromEndpoint().getEndpointUri();
+ } else {
+ // will set a default one for it
+ baseURIString = "/";
+ }
+ }
+ baseURI = new URI(baseURIString);
+ String basePath = baseURI.getPath();
+ if (path.startsWith(basePath)) {
+ path = path.substring(basePath.length());
+ if (path.startsWith("/")) {
+ path = path.substring(1);
+ }
+ } else {
+ throw new RuntimeCamelException("Can't anylze the Exchange.HTTP_PATH header, due to: can't find the right HTTP_BASE_URI");
+ }
+ } catch (Throwable t) {
+ throw new RuntimeCamelException("Can't anylze the Exchange.HTTP_PATH header, due to: "
+ + t.getMessage(), t);
+ }
+
+ }
+ if (path.length() > 0) {
+ // make sure that there is exactly one "/" between HTTP_URI and
+ // HTTP_PATH
+ if (!uri.endsWith("/")) {
+ uri = uri + "/";
+ }
+ uri = uri.concat(path);
}
- uri = uri.concat(path);
}
return uri;
diff --git a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeRouteTest.java b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeRouteTest.java
index beeda57af817e..8b24da62d2501 100644
--- a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeRouteTest.java
+++ b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeRouteTest.java
@@ -31,7 +31,7 @@ public void testHttpClient() throws Exception {
String response = template.requestBodyAndHeader("http://localhost:9090/test/hello", new ByteArrayInputStream("This is a test".getBytes()), "Content-Type", "application/xml", String.class);
- assertEquals("Get a wrong response", "/test/hello", response);
+ assertEquals("Get a wrong response", "/", response);
response = template.requestBody("http://localhost:9080/hello/world", "hello", String.class);
diff --git a/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpTest.java b/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpTest.java
new file mode 100644
index 0000000000000..0931cc819cad3
--- /dev/null
+++ b/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpTest.java
@@ -0,0 +1,86 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.itest.issues;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.builder.xml.Namespaces;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * @version $Revision$
+ */
+public class JettyHttpTest extends CamelTestSupport {
+
+ private String targetProducerUri = "http://localhost:8542/someservice?bridgeEndpoint=true&throwExceptionOnFailure=false";
+ private String targetConsumerUri = "jetty:http://localhost:8542/someservice?matchOnUriPrefix=true";
+ private String sourceUri = "jetty:http://localhost:6323/myservice?matchOnUriPrefix=true";
+ private String sourceProducerUri = "http://localhost:6323/myservice";
+
+ @Test
+ public void testGetRootPath() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("Hi! /someservice");
+
+ template.sendBody("direct:root", "");
+
+ assertMockEndpointsSatisfied();
+ }
+
+ @Test
+ public void testGetWithRelativePath() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("Hi! /someservice/relative");
+
+ template.sendBody("direct:relative", "");
+ assertMockEndpointsSatisfied();
+
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+
+ from(targetConsumerUri)
+ .process(new Processor() {
+ public void process(Exchange exchange) throws Exception {
+ String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class);
+ exchange.getOut().setBody("Hi! " + path);
+ }
+ });
+
+ from(sourceUri)
+ .to(targetProducerUri);
+
+ from("direct:root")
+ .to(sourceProducerUri)
+ .to("mock:result");
+
+ from("direct:relative")
+ .to(sourceProducerUri + "/relative")
+ .to("mock:result");
+
+ }
+ };
+ }
+}
|
0fa50b7ec172424f1e4d34ccd5698533748e0a3a
|
dustin$java-memcached-client
|
Add visibility into operations (status).
This commit allows the functionality for users to issue requests
and then check to see whether or not they succeeded. They can also
now access the error message that the server sends back to them
so they can see why the server rejected their request. Operation
status's also take into account operation timeouts and exceptions
so if an operation times out the operation says so. Also if an
exception is thrown while processing the operation the operation
status reports the message from that exception.
Change-Id: I62af7450cf6cd1c9d1bf171e5063b3d8a1c919ce
Reviewed-on: http://review.couchbase.org/7044
Reviewed-by: Michael Wiederhold <[email protected]>
Tested-by: Michael Wiederhold <[email protected]>
|
p
|
https://github.com/dustin/java-memcached-client
|
diff --git a/src/main/java/net/spy/memcached/MemcachedClient.java b/src/main/java/net/spy/memcached/MemcachedClient.java
index 1b425526e..bf6542bbf 100644
--- a/src/main/java/net/spy/memcached/MemcachedClient.java
+++ b/src/main/java/net/spy/memcached/MemcachedClient.java
@@ -429,7 +429,7 @@ private CountDownLatch broadcastOp(BroadcastOpFactory of,
return conn.broadcastOperation(of, nodes);
}
- private <T> Future<Boolean> asyncStore(StoreType storeType, String key,
+ private <T> OperationFuture<Boolean> asyncStore(StoreType storeType, String key,
int exp, T value, Transcoder<T> tc) {
CachedData co=tc.encode(value);
final CountDownLatch latch=new CountDownLatch(1);
@@ -438,7 +438,7 @@ private <T> Future<Boolean> asyncStore(StoreType storeType, String key,
Operation op=opFact.store(storeType, key, co.getFlags(),
exp, co.getData(), new OperationCallback() {
public void receivedStatus(OperationStatus val) {
- rv.set(val.isSuccess());
+ rv.set(val.isSuccess(), val);
}
public void complete() {
latch.countDown();
@@ -448,12 +448,12 @@ public void complete() {
return rv;
}
- private Future<Boolean> asyncStore(StoreType storeType,
+ private OperationFuture<Boolean> asyncStore(StoreType storeType,
String key, int exp, Object value) {
return asyncStore(storeType, key, exp, value, transcoder);
}
- private <T> Future<Boolean> asyncCat(
+ private <T> OperationFuture<Boolean> asyncCat(
ConcatenationType catType, long cas, String key,
T value, Transcoder<T> tc) {
CachedData co=tc.encode(value);
@@ -463,7 +463,7 @@ private <T> Future<Boolean> asyncCat(
Operation op=opFact.cat(catType, cas, key, co.getData(),
new OperationCallback() {
public void receivedStatus(OperationStatus val) {
- rv.set(val.isSuccess());
+ rv.set(val.isSuccess(), val);
}
public void complete() {
latch.countDown();
@@ -484,7 +484,7 @@ public void complete() {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<Boolean> touch(final String key, final int exp) {
+ public <T> OperationFuture<Boolean> touch(final String key, final int exp) {
return touch(key, exp, transcoder);
}
@@ -499,7 +499,7 @@ public <T> Future<Boolean> touch(final String key, final int exp) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<Boolean> touch(final String key, final int exp,
+ public <T> OperationFuture<Boolean> touch(final String key, final int exp,
final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(latch,
@@ -507,7 +507,7 @@ public <T> Future<Boolean> touch(final String key, final int exp,
Operation op=opFact.touch(key, exp, new OperationCallback() {
public void receivedStatus(OperationStatus status) {
- rv.set(status.isSuccess());
+ rv.set(status.isSuccess(), status);
}
public void complete() {
latch.countDown();
@@ -531,7 +531,7 @@ public void complete() {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Boolean> append(long cas, String key, Object val) {
+ public OperationFuture<Boolean> append(long cas, String key, Object val) {
return append(cas, key, val, transcoder);
}
@@ -550,7 +550,7 @@ public Future<Boolean> append(long cas, String key, Object val) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<Boolean> append(long cas, String key, T val,
+ public <T> OperationFuture<Boolean> append(long cas, String key, T val,
Transcoder<T> tc) {
return asyncCat(ConcatenationType.append, cas, key, val, tc);
}
@@ -568,7 +568,7 @@ public <T> Future<Boolean> append(long cas, String key, T val,
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Boolean> prepend(long cas, String key, Object val) {
+ public OperationFuture<Boolean> prepend(long cas, String key, Object val) {
return prepend(cas, key, val, transcoder);
}
@@ -587,7 +587,7 @@ public Future<Boolean> prepend(long cas, String key, Object val) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<Boolean> prepend(long cas, String key, T val,
+ public <T> OperationFuture<Boolean> prepend(long cas, String key, T val,
Transcoder<T> tc) {
return asyncCat(ConcatenationType.prepend, cas, key, val, tc);
}
@@ -632,7 +632,7 @@ public <T> Future<CASResponse> asyncCAS(String key, long casId, int exp, T value
co.getData(), new OperationCallback() {
public void receivedStatus(OperationStatus val) {
if(val instanceof CASOperationStatus) {
- rv.set(((CASOperationStatus)val).getCASResponse());
+ rv.set(((CASOperationStatus)val).getCASResponse(), val);
} else if(val instanceof CancelledOperationStatus) {
// Cancelled, ignore and let it float up
} else {
@@ -758,7 +758,7 @@ public CASResponse cas(String key, long casId, Object value) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<Boolean> add(String key, int exp, T o, Transcoder<T> tc) {
+ public <T> OperationFuture<Boolean> add(String key, int exp, T o, Transcoder<T> tc) {
return asyncStore(StoreType.add, key, exp, o, tc);
}
@@ -793,7 +793,7 @@ public <T> Future<Boolean> add(String key, int exp, T o, Transcoder<T> tc) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Boolean> add(String key, int exp, Object o) {
+ public OperationFuture<Boolean> add(String key, int exp, Object o) {
return asyncStore(StoreType.add, key, exp, o, transcoder);
}
@@ -829,7 +829,7 @@ public Future<Boolean> add(String key, int exp, Object o) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<Boolean> set(String key, int exp, T o, Transcoder<T> tc) {
+ public <T> OperationFuture<Boolean> set(String key, int exp, T o, Transcoder<T> tc) {
return asyncStore(StoreType.set, key, exp, o, tc);
}
@@ -864,7 +864,7 @@ public <T> Future<Boolean> set(String key, int exp, T o, Transcoder<T> tc) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Boolean> set(String key, int exp, Object o) {
+ public OperationFuture<Boolean> set(String key, int exp, Object o) {
return asyncStore(StoreType.set, key, exp, o, transcoder);
}
@@ -901,7 +901,7 @@ public Future<Boolean> set(String key, int exp, Object o) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<Boolean> replace(String key, int exp, T o,
+ public <T> OperationFuture<Boolean> replace(String key, int exp, T o,
Transcoder<T> tc) {
return asyncStore(StoreType.replace, key, exp, o, tc);
}
@@ -937,7 +937,7 @@ public <T> Future<Boolean> replace(String key, int exp, T o,
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Boolean> replace(String key, int exp, Object o) {
+ public OperationFuture<Boolean> replace(String key, int exp, Object o) {
return asyncStore(StoreType.replace, key, exp, o, transcoder);
}
@@ -951,7 +951,7 @@ public Future<Boolean> replace(String key, int exp, Object o) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<T> asyncGet(final String key, final Transcoder<T> tc) {
+ public <T> GetFuture<T> asyncGet(final String key, final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final GetFuture<T> rv=new GetFuture<T>(latch, operationTimeout);
@@ -960,7 +960,7 @@ public <T> Future<T> asyncGet(final String key, final Transcoder<T> tc) {
new GetOperation.Callback() {
private Future<T> val=null;
public void receivedStatus(OperationStatus status) {
- rv.set(val);
+ rv.set(val, status);
}
public void gotData(String k, int flags, byte[] data) {
assert key.equals(k) : "Wrong key returned";
@@ -984,7 +984,7 @@ public void complete() {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Object> asyncGet(final String key) {
+ public GetFuture<Object> asyncGet(final String key) {
return asyncGet(key, transcoder);
}
@@ -998,7 +998,7 @@ public Future<Object> asyncGet(final String key) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<CASValue<T>> asyncGets(final String key,
+ public <T> OperationFuture<CASValue<T>> asyncGets(final String key,
final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
@@ -1009,7 +1009,7 @@ public <T> Future<CASValue<T>> asyncGets(final String key,
new GetsOperation.Callback() {
private CASValue<T> val=null;
public void receivedStatus(OperationStatus status) {
- rv.set(val);
+ rv.set(val, status);
}
public void gotData(String k, int flags, long cas, byte[] data) {
assert key.equals(k) : "Wrong key returned";
@@ -1034,7 +1034,7 @@ public void complete() {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<CASValue<Object>> asyncGets(final String key) {
+ public OperationFuture<CASValue<Object>> asyncGets(final String key) {
return asyncGets(key, transcoder);
}
@@ -1168,7 +1168,7 @@ public Object get(String key) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<CASValue<T>> asyncGetAndLock(final String key, int exp,
+ public <T> OperationFuture<CASValue<T>> asyncGetAndLock(final String key, int exp,
final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<CASValue<T>> rv=
@@ -1178,7 +1178,7 @@ public <T> Future<CASValue<T>> asyncGetAndLock(final String key, int exp,
new GetlOperation.Callback() {
private CASValue<T> val=null;
public void receivedStatus(OperationStatus status) {
- rv.set(val);
+ rv.set(val, status);
}
public void gotData(String k, int flags, long cas, byte[] data) {
assert key.equals(k) : "Wrong key returned";
@@ -1205,7 +1205,7 @@ public void complete() {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<CASValue<Object>> asyncGetAndLock(final String key, int exp) {
+ public OperationFuture<CASValue<Object>> asyncGetAndLock(final String key, int exp) {
return asyncGetAndLock(key, exp, transcoder);
}
@@ -1268,10 +1268,12 @@ public <T> BulkFuture<Map<String, T>> asyncGetBulk(Collection<String> keys,
final CountDownLatch latch=new CountDownLatch(chunks.size());
final Collection<Operation> ops=new ArrayList<Operation>(chunks.size());
+ final BulkGetFuture<T> rv = new BulkGetFuture<T>(m, ops, latch);
GetOperation.Callback cb=new GetOperation.Callback() {
@SuppressWarnings("synthetic-access")
public void receivedStatus(OperationStatus status) {
+ rv.setStatus(status);
if(!status.isSuccess()) {
getLogger().warn("Unsuccessful get: %s", status);
}
@@ -1300,7 +1302,7 @@ public void complete() {
assert mops.size() == chunks.size();
checkState();
conn.addOperations(mops);
- return new BulkGetFuture<T>(m, ops, latch);
+ return rv;
}
/**
@@ -1367,7 +1369,7 @@ public BulkFuture<Map<String, Object>> asyncGetBulk(String... keys) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<CASValue<Object>> asyncGetAndTouch(final String key, final int exp) {
+ public OperationFuture<CASValue<Object>> asyncGetAndTouch(final String key, final int exp) {
return asyncGetAndTouch(key, exp, transcoder);
}
@@ -1381,7 +1383,7 @@ public Future<CASValue<Object>> asyncGetAndTouch(final String key, final int exp
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public <T> Future<CASValue<T>> asyncGetAndTouch(final String key, final int exp,
+ public <T> OperationFuture<CASValue<T>> asyncGetAndTouch(final String key, final int exp,
final Transcoder<T> tc) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<CASValue<T>> rv=new OperationFuture<CASValue<T>>(latch,
@@ -1390,7 +1392,7 @@ public <T> Future<CASValue<T>> asyncGetAndTouch(final String key, final int exp,
Operation op=opFact.getAndTouch(key, exp, new GetAndTouchOperation.Callback() {
private CASValue<T> val=null;
public void receivedStatus(OperationStatus status) {
- rv.set(val);
+ rv.set(val, status);
}
public void complete() {
latch.countDown();
@@ -1739,7 +1741,7 @@ private long mutateWithDefault(Mutator t, String key,
return rv;
}
- private Future<Long> asyncMutate(Mutator m, String key, int by, long def,
+ private OperationFuture<Long> asyncMutate(Mutator m, String key, int by, long def,
int exp) {
final CountDownLatch latch = new CountDownLatch(1);
final OperationFuture<Long> rv = new OperationFuture<Long>(
@@ -1747,7 +1749,7 @@ private Future<Long> asyncMutate(Mutator m, String key, int by, long def,
Operation op = addOp(key, opFact.mutate(m, key, by, def, exp,
new OperationCallback() {
public void receivedStatus(OperationStatus s) {
- rv.set(new Long(s.isSuccess() ? s.getMessage() : "-1"));
+ rv.set(new Long(s.isSuccess() ? s.getMessage() : "-1"), s);
}
public void complete() {
latch.countDown();
@@ -1767,7 +1769,7 @@ public void complete() {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Long> asyncIncr(String key, int by) {
+ public OperationFuture<Long> asyncIncr(String key, int by) {
return asyncMutate(Mutator.incr, key, by, 0, -1);
}
@@ -1781,7 +1783,7 @@ public Future<Long> asyncIncr(String key, int by) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Long> asyncDecr(String key, int by) {
+ public OperationFuture<Long> asyncDecr(String key, int by) {
return asyncMutate(Mutator.decr, key, by, 0, -1);
}
@@ -1837,7 +1839,7 @@ public long decr(String key, int by, long def) {
* @deprecated Hold values are no longer honored.
*/
@Deprecated
- public Future<Boolean> delete(String key, int hold) {
+ public OperationFuture<Boolean> delete(String key, int hold) {
return delete(key);
}
@@ -1849,14 +1851,14 @@ public Future<Boolean> delete(String key, int hold) {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Boolean> delete(String key) {
+ public OperationFuture<Boolean> delete(String key) {
final CountDownLatch latch=new CountDownLatch(1);
final OperationFuture<Boolean> rv=new OperationFuture<Boolean>(latch,
operationTimeout);
DeleteOperation op=opFact.delete(key,
new OperationCallback() {
public void receivedStatus(OperationStatus s) {
- rv.set(s.isSuccess());
+ rv.set(s.isSuccess(), s);
}
public void complete() {
latch.countDown();
@@ -1873,7 +1875,7 @@ public void complete() {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Boolean> flush(final int delay) {
+ public OperationFuture<Boolean> flush(final int delay) {
final AtomicReference<Boolean> flushResult=
new AtomicReference<Boolean>(null);
final ConcurrentLinkedQueue<Operation> ops=
@@ -1891,6 +1893,7 @@ public void complete() {
ops.add(op);
return op;
}});
+
return new OperationFuture<Boolean>(blatch, flushResult,
operationTimeout) {
@Override
@@ -1903,6 +1906,12 @@ public boolean cancel(boolean ign) {
return rv;
}
@Override
+ public Boolean get(long duration, TimeUnit units) throws InterruptedException,
+ TimeoutException, ExecutionException {
+ status = new OperationStatus(true, "OK");
+ return super.get(duration, units);
+ }
+ @Override
public boolean isCancelled() {
boolean rv=false;
for(Operation op : ops) {
@@ -1927,7 +1936,7 @@ public boolean isDone() {
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
- public Future<Boolean> flush() {
+ public OperationFuture<Boolean> flush() {
return flush(-1);
}
diff --git a/src/main/java/net/spy/memcached/internal/BulkFuture.java b/src/main/java/net/spy/memcached/internal/BulkFuture.java
index b1c1e1232..d5c647192 100644
--- a/src/main/java/net/spy/memcached/internal/BulkFuture.java
+++ b/src/main/java/net/spy/memcached/internal/BulkFuture.java
@@ -4,6 +4,8 @@
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import net.spy.memcached.ops.OperationStatus;
+
/**
* Additional flexibility for asyncGetBulk
*
@@ -44,4 +46,11 @@ public interface BulkFuture<V> extends Future<V> {
public V getSome(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException;
+ /**
+ * Gets the status of the operation upon completion.
+ *
+ * @return the operation status.
+ */
+ public OperationStatus getStatus();
+
}
diff --git a/src/main/java/net/spy/memcached/internal/BulkGetFuture.java b/src/main/java/net/spy/memcached/internal/BulkGetFuture.java
index 3bcc4ee73..d7c46160a 100644
--- a/src/main/java/net/spy/memcached/internal/BulkGetFuture.java
+++ b/src/main/java/net/spy/memcached/internal/BulkGetFuture.java
@@ -14,6 +14,7 @@
import net.spy.memcached.compat.log.LoggerFactory;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationState;
+import net.spy.memcached.ops.OperationStatus;
/**
* Future for handling results from bulk gets.
@@ -26,6 +27,7 @@ public class BulkGetFuture<T> implements BulkFuture<Map<String, T>> {
private final Map<String, Future<T>> rvMap;
private final Collection<Operation> ops;
private final CountDownLatch latch;
+ private OperationStatus status;
private boolean cancelled=false;
private boolean timeout = false;
@@ -35,6 +37,7 @@ public BulkGetFuture(Map<String, Future<T>> m,
rvMap = m;
ops = getOps;
latch=l;
+ status = null;
}
public boolean cancel(boolean ign) {
@@ -47,6 +50,7 @@ public boolean cancel(boolean ign) {
v.cancel(ign);
}
cancelled=true;
+ status = new OperationStatus(false, "Cancelled");
return rv;
}
@@ -89,6 +93,7 @@ public Map<String, T> get(long to, TimeUnit unit)
Map<String, T> ret = internalGet(to, unit, timedoutOps);
if (timedoutOps.size() > 0) {
this.timeout = true;
+ status = new OperationStatus(false, "Timed out");
throw new CheckedOperationTimeoutException("Operation timed out.",
timedoutOps);
}
@@ -121,9 +126,11 @@ private Map<String, T> internalGet(long to, TimeUnit unit,
}
for (Operation op : ops) {
if (op.isCancelled()) {
+ status = new OperationStatus(false, "Cancelled");
throw new ExecutionException(new RuntimeException("Cancelled"));
}
if (op.hasErrored()) {
+ status = new OperationStatus(false, op.getException().getMessage());
throw new ExecutionException(op.getException());
}
}
@@ -134,6 +141,24 @@ private Map<String, T> internalGet(long to, TimeUnit unit,
return m;
}
+ public OperationStatus getStatus() {
+ if (status == null) {
+ try {
+ get();
+ } catch (InterruptedException e) {
+ status = new OperationStatus(false, "Interrupted");
+ Thread.currentThread().interrupt();
+ } catch (ExecutionException e) {
+ return status;
+ }
+ }
+ return status;
+ }
+
+ public void setStatus(OperationStatus s) {
+ status = s;
+ }
+
public boolean isCancelled() {
return cancelled;
}
diff --git a/src/main/java/net/spy/memcached/internal/GetFuture.java b/src/main/java/net/spy/memcached/internal/GetFuture.java
index de750544a..8cab34b00 100644
--- a/src/main/java/net/spy/memcached/internal/GetFuture.java
+++ b/src/main/java/net/spy/memcached/internal/GetFuture.java
@@ -7,6 +7,7 @@
import java.util.concurrent.TimeoutException;
import net.spy.memcached.ops.Operation;
+import net.spy.memcached.ops.OperationStatus;
/**
* Future returned for GET operations.
@@ -38,8 +39,12 @@ public T get(long duration, TimeUnit units)
return v == null ? null : v.get();
}
- public void set(Future<T> d) {
- rv.set(d);
+ public OperationStatus getStatus() {
+ return rv.getStatus();
+ }
+
+ public void set(Future<T> d, OperationStatus s) {
+ rv.set(d, s);
}
public void setOperation(Operation to) {
diff --git a/src/main/java/net/spy/memcached/internal/OperationFuture.java b/src/main/java/net/spy/memcached/internal/OperationFuture.java
index e2c8c5efd..5075f49ee 100644
--- a/src/main/java/net/spy/memcached/internal/OperationFuture.java
+++ b/src/main/java/net/spy/memcached/internal/OperationFuture.java
@@ -10,6 +10,7 @@
import net.spy.memcached.MemcachedConnection;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationState;
+import net.spy.memcached.ops.OperationStatus;
/**
* Managed future for operations.
@@ -22,6 +23,7 @@ public class OperationFuture<T> implements Future<T> {
private final CountDownLatch latch;
private final AtomicReference<T> objRef;
+ protected OperationStatus status;
private final long timeout;
private Operation op;
@@ -34,6 +36,7 @@ public OperationFuture(CountDownLatch l, AtomicReference<T> oref,
super();
latch=l;
objRef=oref;
+ status = null;
timeout = opTimeout;
}
@@ -49,6 +52,7 @@ public T get() throws InterruptedException, ExecutionException {
try {
return get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
+ status = new OperationStatus(false, "Timed out");
throw new RuntimeException(
"Timed out waiting for operation", e);
}
@@ -62,6 +66,7 @@ public T get(long duration, TimeUnit units)
if (op != null) { // op can be null on a flush
op.timeOut();
}
+ status = new OperationStatus(false, "Timed out");
throw new CheckedOperationTimeoutException(
"Timed out waiting for operation", op);
} else {
@@ -69,20 +74,37 @@ public T get(long duration, TimeUnit units)
MemcachedConnection.opSucceeded(op);
}
if(op != null && op.hasErrored()) {
+ status = new OperationStatus(false, op.getException().getMessage());
throw new ExecutionException(op.getException());
}
if(isCancelled()) {
throw new ExecutionException(new RuntimeException("Cancelled"));
}
if(op != null && op.isTimedOut()) {
+ status = new OperationStatus(false, "Timed out");
throw new ExecutionException(new CheckedOperationTimeoutException("Operation timed out.", op));
}
return objRef.get();
}
- public void set(T o) {
+ public OperationStatus getStatus() {
+ if (status == null) {
+ try {
+ get();
+ } catch (InterruptedException e) {
+ status = new OperationStatus(false, "Interrupted");
+ Thread.currentThread().isInterrupted();
+ } catch (ExecutionException e) {
+
+ }
+ }
+ return status;
+ }
+
+ public void set(T o, OperationStatus s) {
objRef.set(o);
+ status = s;
}
public void setOperation(Operation to) {
diff --git a/src/test/java/net/spy/memcached/ProtocolBaseCase.java b/src/test/java/net/spy/memcached/ProtocolBaseCase.java
index d885f9572..983404a83 100644
--- a/src/test/java/net/spy/memcached/ProtocolBaseCase.java
+++ b/src/test/java/net/spy/memcached/ProtocolBaseCase.java
@@ -15,6 +15,9 @@
import java.util.concurrent.TimeUnit;
import net.spy.memcached.compat.SyncThread;
+import net.spy.memcached.internal.BulkFuture;
+import net.spy.memcached.internal.GetFuture;
+import net.spy.memcached.internal.OperationFuture;
import net.spy.memcached.ops.OperationErrorType;
import net.spy.memcached.ops.OperationException;
import net.spy.memcached.transcoders.SerializingTranscoder;
@@ -91,14 +94,16 @@ public void testGetStatsCacheDump() throws Exception {
public void testDelayedFlush() throws Exception {
assertNull(client.get("test1"));
- client.set("test1", 5, "test1value");
- client.set("test2", 5, "test2value");
+ assert client.set("test1", 5, "test1value").getStatus().isSuccess();
+ assert client.set("test2", 5, "test2value").getStatus().isSuccess();
assertEquals("test1value", client.get("test1"));
assertEquals("test2value", client.get("test2"));
- client.flush(2);
+ assert client.flush(2).getStatus().isSuccess();
Thread.sleep(2100);
assertNull(client.get("test1"));
assertNull(client.get("test2"));
+ assert !client.asyncGet("test1").getStatus().isSuccess();
+ assert !client.asyncGet("test2").getStatus().isSuccess();
}
public void testNoop() {
@@ -118,7 +123,7 @@ public void testSimpleGet() throws Exception {
public void testSimpleCASGets() throws Exception {
assertNull(client.gets("test1"));
- client.set("test1", 5, "test1value");
+ assert client.set("test1", 5, "test1value").getStatus().isSuccess();
assertEquals("test1value", client.gets("test1").getValue());
}
@@ -165,7 +170,7 @@ public void testReallyLongCASId() throws Exception {
public void testExtendedUTF8Key() throws Exception {
String key="\u2013\u00ba\u2013\u220f\u2014\u00c4";
assertNull(client.get(key));
- client.set(key, 5, "test1value");
+ assert client.set(key, 5, "test1value").getStatus().isSuccess();
assertEquals("test1value", client.get(key));
}
@@ -240,7 +245,7 @@ public void testParallelSetGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
for(int i=0; i<10; i++) {
- client.set("test" + i, 5, "value" + i);
+ assert client.set("test" + i, 5, "value" + i).getStatus().isSuccess();
assertEquals("value" + i, client.get("test" + i));
}
for(int i=0; i<10; i++) {
@@ -255,7 +260,7 @@ public void testParallelSetMultiGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
for(int i=0; i<10; i++) {
- client.set("test" + i, 5, "value" + i);
+ assert client.set("test" + i, 5, "value" + i).getStatus().isSuccess();
assertEquals("value" + i, client.get("test" + i));
}
Map<String, Object> m=client.getBulk("test0", "test1", "test2",
@@ -272,7 +277,7 @@ public Boolean call() throws Exception {
public void testParallelSetAutoMultiGet() throws Throwable {
int cnt=SyncThread.getDistinctResultCount(10, new Callable<Boolean>(){
public Boolean call() throws Exception {
- client.set("testparallel", 5, "parallelvalue");
+ assert client.set("testparallel", 5, "parallelvalue").getStatus().isSuccess();
for(int i=0; i<10; i++) {
assertEquals("parallelvalue", client.get("testparallel"));
}
@@ -283,9 +288,12 @@ public Boolean call() throws Exception {
public void testAdd() throws Exception {
assertNull(client.get("test1"));
+ assert !client.asyncGet("test1").getStatus().isSuccess();
assertTrue(client.set("test1", 5, "test1value").get());
assertEquals("test1value", client.get("test1"));
+ assert client.asyncGet("test1").getStatus().isSuccess();
assertFalse(client.add("test1", 5, "ignoredvalue").get());
+ assert !client.add("test1", 5, "ignoredvalue").getStatus().isSuccess();
// Should return the original value
assertEquals("test1value", client.get("test1"));
}
@@ -293,9 +301,11 @@ public void testAdd() throws Exception {
public void testAddWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertNull(client.get("test1", t));
+ assert !client.asyncGet("test1", t).getStatus().isSuccess();
assertTrue(client.set("test1", 5, "test1value", t).get());
assertEquals("test1value", client.get("test1", t));
assertFalse(client.add("test1", 5, "ignoredvalue", t).get());
+ assert !client.add("test1", 5, "ignoredvalue", t).getStatus().isSuccess();
// Should return the original value
assertEquals("test1value", client.get("test1", t));
}
@@ -330,6 +340,7 @@ public void testReplaceNotSerializable() throws Exception {
public void testUpdate() throws Exception {
assertNull(client.get("test1"));
client.replace("test1", 5, "test1value");
+ assert !client.replace("test1", 5, "test1value").getStatus().isSuccess();
assertNull(client.get("test1"));
}
@@ -337,6 +348,7 @@ public void testUpdateWithTranscoder() throws Exception {
Transcoder<String> t=new TestTranscoder();
assertNull(client.get("test1", t));
client.replace("test1", 5, "test1value", t);
+ assert !client.replace("test1", 5, "test1value", t).getStatus().isSuccess();
assertNull(client.get("test1", t));
}
@@ -367,6 +379,7 @@ public void testGetBulk() throws Exception {
client.set("test1", 5, "val1");
client.set("test2", 5, "val2");
Map<String, Object> vals=client.getBulk(keys);
+ assert client.asyncGetBulk(keys).getStatus().isSuccess();
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
@@ -377,6 +390,7 @@ public void testGetBulkVararg() throws Exception {
client.set("test1", 5, "val1");
client.set("test2", 5, "val2");
Map<String, Object> vals=client.getBulk("test1", "test2", "test3");
+ assert client.asyncGetBulk("test1", "test2", "test3").getStatus().isSuccess();
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
@@ -388,6 +402,7 @@ public void testGetBulkVarargWithTranscoder() throws Exception {
client.set("test1", 5, "val1", t);
client.set("test2", 5, "val2", t);
Map<String, String> vals=client.getBulk(t, "test1", "test2", "test3");
+ assert client.asyncGetBulk(t, "test1", "test2", "test3").getStatus().isSuccess();
assertEquals(2, vals.size());
assertEquals("val1", vals.get("test1"));
assertEquals("val2", vals.get("test2"));
@@ -398,8 +413,9 @@ public void testAsyncGetBulkVarargWithTranscoder() throws Exception {
assertEquals(0, client.getBulk(t, "test1", "test2", "test3").size());
client.set("test1", 5, "val1", t);
client.set("test2", 5, "val2", t);
- Future<Map<String, String>> vals=client.asyncGetBulk(t,
+ BulkFuture<Map<String, String>> vals=client.asyncGetBulk(t,
"test1", "test2", "test3");
+ assert vals.getStatus().isSuccess();
assertEquals(2, vals.get().size());
assertEquals("val1", vals.get().get("test1"));
assertEquals("val2", vals.get().get("test2"));
@@ -471,7 +487,9 @@ public void testGetVersions() throws Exception {
public void testNonexistentMutate() throws Exception {
assertEquals(-1, client.incr("nonexistent", 1));
+ assert !client.asyncIncr("nonexistent", 1).getStatus().isSuccess();
assertEquals(-1, client.decr("nonexistent", 1));
+ assert !client.asyncDecr("nonexistent", 1).getStatus().isSuccess();
}
public void testMutateWithDefault() throws Exception {
@@ -488,6 +506,7 @@ public void testMutateWithDefaultAndExp() throws Exception {
assertEquals(9, client.decr("mtest2", 1, 9, 1));
Thread.sleep(2000);
assertNull(client.get("mtest"));
+ assert ! client.asyncGet("mtest").getStatus().isSuccess();
}
public void testAsyncIncrement() throws Exception {
@@ -528,7 +547,7 @@ public void testImmediateDelete() throws Exception {
assertNull(client.get("test1"));
client.set("test1", 5, "test1value");
assertEquals("test1value", client.get("test1"));
- client.delete("test1");
+ assert client.delete("test1").getStatus().isSuccess();
assertNull(client.get("test1"));
}
@@ -593,12 +612,15 @@ public int getTimeoutExceptionThreshold() {
assert set == true;
int i = 0;
+ GetFuture<Object> g = null;
try {
for(i = 0; i < 1000000; i++) {
- client.get(key);
+ g = client.asyncGet(key);
+ g.get();
}
throw new Exception("Didn't get a timeout.");
- } catch(RuntimeException e) {
+ } catch(Exception e) {
+ assert !g.getStatus().isSuccess();
System.out.println("Got a timeout at iteration " + i + ".");
}
Thread.sleep(100); // let whatever caused the timeout to pass
@@ -741,13 +763,15 @@ public void testABunchOfCancelledOperations() throws Exception {
futures.add(client.set(k, 5, "xval"));
futures.add(client.asyncGet(k));
}
- Future<Boolean> sf=client.set(k, 5, "myxval");
- Future<Object> gf=client.asyncGet(k);
+ OperationFuture<Boolean> sf=client.set(k, 5, "myxval");
+ GetFuture<Object> gf=client.asyncGet(k);
for(Future<?> f : futures) {
f.cancel(true);
}
assertTrue(sf.get());
+ assert sf.getStatus().isSuccess();
assertEquals("myxval", gf.get());
+ assert gf.getStatus().isSuccess();
}
public void testUTF8Key() throws Exception {
@@ -801,14 +825,18 @@ public void testUTF8Value() throws Exception {
public void testAppend() throws Exception {
final String key="append.key";
assertTrue(client.set(key, 5, "test").get());
- assertTrue(client.append(0, key, "es").get());
+ OperationFuture<Boolean> op = client.append(0, key, "es");
+ assertTrue(op.get());
+ assert op.getStatus().isSuccess();
assertEquals("testes", client.get(key));
}
public void testPrepend() throws Exception {
final String key="prepend.key";
assertTrue(client.set(key, 5, "test").get());
- assertTrue(client.prepend(0, key, "es").get());
+ OperationFuture<Boolean> op = client.prepend(0, key, "es");
+ assertTrue(op.get());
+ assert op.getStatus().isSuccess();
assertEquals("estest", client.get(key));
}
|
e0f983040c7680fce1b2c3b662ebad63a01e8d31
|
drools
|
[BZ-980385] fix comparison of 2 timer nodes--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java
index 44a10b5a584..9cbb49c0720 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java
@@ -2170,4 +2170,39 @@ public void testAddSameResourceTwice() {
assertTrue(kbuilder.hasResults(ResultSeverity.INFO, ResultSeverity.WARNING, ResultSeverity.ERROR));
}
+ @Test
+ public void testTwoTimers() {
+ // BZ-980385
+ String str =
+ "import java.util.Date\n" +
+ "import java.util.List\n" +
+ "\n" +
+ "global List dates\n" +
+ "\n" +
+ "rule \"intervalRule\"\n" +
+ " timer(int: 200ms 100ms)\n" +
+ "when\n" +
+ " String(this == \"intervalRule\")\n" +
+ "then\n" +
+ " Date date = new Date();\n" +
+ " dates.add(date);\n" +
+ "end\n" +
+ "\n" +
+ "\n" +
+ "// this rule stops timer\n" +
+ "rule \"stopIntervalRule\"\n" +
+ " timer(int: 320ms)\n" +
+ "when\n" +
+ " $s : String(this == \"intervalRule\")\n" +
+ "then\n" +
+ " retract($s);\n" +
+ "end\n";
+
+ KieServices ks = KieServices.Factory.get();
+
+ KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str );
+ assertEquals(0, ks.newKieBuilder( kfs ).buildAll().getResults().getMessages().size());
+
+ KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
+ }
}
\ No newline at end of file
diff --git a/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java b/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java
index 7259b924e9c..cab2d915de6 100644
--- a/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java
+++ b/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java
@@ -149,11 +149,12 @@ public String toString() {
public int hashCode() {
int hash = this.leftInput.hashCode() ^ this.timer.hashCode();
- for (int i = 0; i < calendarNames.length; i++) {
- hash = hash ^ calendarNames[i].hashCode();
+ if (calendarNames != null) {
+ for (int i = 0; i < calendarNames.length; i++) {
+ hash = hash ^ calendarNames[i].hashCode();
+ }
}
return hash;
-
}
public boolean equals(final Object object) {
@@ -167,14 +168,16 @@ public boolean equals(final Object object) {
final TimerNode other = (TimerNode) object;
- if (other.getCalendarNames().length != calendarNames.length) {
- return false;
- }
-
- for (int i = 0; i < calendarNames.length; i++) {
- if (!other.getCalendarNames()[i].equals(calendarNames[i])) {
+ if (calendarNames != null) {
+ if (other.getCalendarNames() == null || other.getCalendarNames().length != calendarNames.length) {
return false;
}
+
+ for (int i = 0; i < calendarNames.length; i++) {
+ if (!other.getCalendarNames()[i].equals(calendarNames[i])) {
+ return false;
+ }
+ }
}
if ( declarations != null ) {
|
43052179c2d568930f98894dfd5ea30f2a1a2ad6
|
arquillian$arquillian-graphene
|
ARQGRA-170: static contexts merged and added support for multiple browsers
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/configuration/ResourceTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/configuration/ResourceTestCase.java
similarity index 92%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/configuration/ResourceTestCase.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/configuration/ResourceTestCase.java
index 366d88036..0f501c6c3 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/configuration/ResourceTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/configuration/ResourceTestCase.java
@@ -19,8 +19,9 @@
* 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.arquillian.graphene.configuration;
+package org.jboss.arquillian.graphene.ftest.configuration;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Assert;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneIntegrationTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneHtmlUnitDriverIntegrationTestCase.java
similarity index 72%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneIntegrationTestCase.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneHtmlUnitDriverIntegrationTestCase.java
index be1b7dea2..a575242d4 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneIntegrationTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneHtmlUnitDriverIntegrationTestCase.java
@@ -16,27 +16,31 @@
*/
package org.jboss.arquillian.graphene.ftest.drone;
+import org.jboss.arquillian.drone.api.annotation.Default;
import static org.junit.Assert.assertTrue;
import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.Graphene;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.htmlunit.HtmlUnitDriver;
/**
* @author Lukas Fryc
+ * @author Jan Papousek
*/
@RunWith(Arquillian.class)
-public class GrapheneDroneIntegrationTestCase {
+public class GrapheneDroneHtmlUnitDriverIntegrationTestCase {
@Drone
- WebDriver browser;
+ HtmlUnitDriver browser;
@Test
public void created_instance_should_be_instance_of_requested_driver() {
- assertTrue("browser must be WebDriver", browser instanceof WebDriver);
+ assertTrue("browser must be HtmlUnitDriver", browser instanceof HtmlUnitDriver);
}
@Test
@@ -48,4 +52,9 @@ public void created_instance_should_be_instance_of_GrapheneProxyInstance() {
public void created_instance_should_be_able_to_navigate_to_some_page() {
browser.navigate().to("http://127.0.0.1:14444");
}
+
+ @Test
+ public void context_instance_should_be_instance_of_GrapheneProxyInstance() {
+ assertTrue("context browser must be proxy", browser instanceof GrapheneProxyInstance);
+ }
}
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneWebDriverIntegrationTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneWebDriverIntegrationTestCase.java
new file mode 100644
index 000000000..75b3f6b12
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/drone/GrapheneDroneWebDriverIntegrationTestCase.java
@@ -0,0 +1,70 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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.jboss.arquillian.graphene.ftest.drone;
+
+import org.jboss.arquillian.drone.api.annotation.Default;
+import static org.junit.Assert.assertTrue;
+
+import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.Graphene;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
+import org.jboss.arquillian.junit.Arquillian;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.WebDriver;
+
+/**
+ * @author Lukas Fryc
+ * @author Jan Papousek
+ */
+@RunWith(Arquillian.class)
+public class GrapheneDroneWebDriverIntegrationTestCase {
+
+ @Drone
+ WebDriver browser;
+
+ @Test
+ public void created_instance_should_be_instance_of_requested_driver() {
+ assertTrue("browser must be WebDriver", browser instanceof WebDriver);
+ }
+
+ @Test
+ public void created_instance_should_be_instance_of_GrapheneProxyInstance() {
+ assertTrue("browser must be proxy", browser instanceof GrapheneProxyInstance);
+ }
+
+ @Test
+ public void created_instance_should_be_able_to_navigate_to_some_page() {
+ browser.navigate().to("http://127.0.0.1:14444");
+ }
+
+ @Test
+ public void context_instance_should_be_instance_of_requested_driver() {
+ assertTrue("context browser must be WebDriver", GrapheneContext.getContextFor(Default.class).getWebDriver() instanceof WebDriver);
+ }
+
+ @Test
+ public void context_instance_should_be_instance_of_GrapheneProxyInstance() {
+ assertTrue("context browser must be proxy", browser instanceof GrapheneProxyInstance);
+ }
+
+ @Test
+ public void context_instance_should_be_able_to_navigate_to_some_page() {
+ GrapheneContext.getContextFor(Default.class).getWebDriver().navigate().to("http://127.0.0.1:14444");
+ }
+}
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/AbstractTest.java
similarity index 84%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractTest.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/AbstractTest.java
index ced5996c5..06eefaefc 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractTest.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/AbstractTest.java
@@ -1,9 +1,9 @@
-package org.jboss.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import java.net.URL;
import org.jboss.arquillian.drone.api.annotation.Drone;
-import org.jboss.arquillian.graphene.enricher.page.AbstractPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.AbstractPage;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.openqa.selenium.WebDriver;
@@ -17,16 +17,16 @@ public abstract class AbstractTest<T extends AbstractPage, E> {
@Page
protected E anotherPageWithGenericType;
-
+
@Drone
protected WebDriver selenium;
-
+
public void loadPage() {
URL page = this.getClass().getClassLoader()
.getResource("org/jboss/arquillian/graphene/ftest/pageFragmentsEnricher/sample.html");
selenium.get(page.toExternalForm());
}
-
-
+
+
}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/MoreSpecificAbstractTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/MoreSpecificAbstractTest.java
similarity index 57%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/MoreSpecificAbstractTest.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/MoreSpecificAbstractTest.java
index da7eb8c4f..42d07543d 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/MoreSpecificAbstractTest.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/MoreSpecificAbstractTest.java
@@ -1,6 +1,6 @@
-package org.jboss.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
-import org.jboss.arquillian.graphene.enricher.page.AbstractPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.AbstractPage;
/**
* @author <a href="mailto:[email protected]">Juraj Huska</a>
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java
similarity index 79%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java
index 200be2794..470318a94 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestDroneIntegrationWhenDroneIsUsedInTest.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import java.net.URL;
import junit.framework.Assert;
@@ -54,29 +54,33 @@ public void loadPage(WebDriver browser) {
@Test
public void testDronePageNotNull() {
- Assert.assertNotNull(page.browser);
+ Assert.assertNotNull(page.getBrowser());
}
@Test
public void testDronePageFragmentNotNull() {
- Assert.assertNotNull(pageFragment.browser);
+ Assert.assertNotNull(pageFragment.getBrowser());
}
@Test
public void testDronePageTitle() {
- loadPage(page.browser);
- Assert.assertEquals("Sample Page", page.browser.getTitle());
+ loadPage(page.getBrowser());
+ Assert.assertEquals("Sample Page", page.getBrowser().getTitle());
}
@Test
public void testDronePageFragmentTitle() {
- loadPage(pageFragment.browser);
- Assert.assertEquals("Sample Page", pageFragment.browser.getTitle());
+ loadPage(pageFragment.getBrowser());
+ Assert.assertEquals("Sample Page", pageFragment.getBrowser().getTitle());
}
public static class DronePage {
@Drone
private WebDriver browser;
+
+ public WebDriver getBrowser() {
+ return browser;
+ }
}
public static class DronePageFragment {
@@ -87,6 +91,14 @@ public static class DronePageFragment {
@FindBy(tagName="span")
private WebElement span;
+ public WebDriver getBrowser() {
+ return browser;
+ }
+
+ public WebElement getSpan() {
+ return span;
+ }
+
}
}
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestEnrichingContainerElement.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestEnrichingContainerElement.java
similarity index 82%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestEnrichingContainerElement.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestEnrichingContainerElement.java
index d7de4599d..9210299ef 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestEnrichingContainerElement.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestEnrichingContainerElement.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertEquals;
@@ -27,8 +27,8 @@
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.enricher.findby.FindBy;
-import org.jboss.arquillian.graphene.enricher.page.fragment.Panel;
-import org.jboss.arquillian.graphene.enricher.page.fragment.TabPanel;
+import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.Panel;
+import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.TabPanel;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Before;
import org.junit.Test;
@@ -59,16 +59,20 @@ public void loadPage() {
public void testTabPanelSwitching() {
Panel tab3 = tabPanel.switchTo(2);
ContentOfTab content = tab3.getContent(ContentOfTab.class);
- assertEquals("The tab panel was not switched to third tab correctly!", "Content of the tab 3", content.text.getText());
-
+ assertEquals("The tab panel was not switched to third tab correctly!", "Content of the tab 3", content.getText().getText());
+
Panel tab1 = tabPanel.switchTo(0);
content = tab1.getContent(ContentOfTab.class);
- assertEquals("The tab panel was not switched to first tab correctly!", "Content of the tab 1", content.text.getText());
+ assertEquals("The tab panel was not switched to first tab correctly!", "Content of the tab 1", content.getText().getText());
}
- private static class ContentOfTab {
+ public static class ContentOfTab {
@FindBy(className = "tab-text")
- public WebElement text;
+ private WebElement text;
+
+ public WebElement getText() {
+ return text;
+ }
}
}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestFindByLongLocatingMethod.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestFindByLongLocatingMethod.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestFindByLongLocatingMethod.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestFindByLongLocatingMethod.java
index 7d31ed79b..a6e152a6b 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestFindByLongLocatingMethod.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestFindByLongLocatingMethod.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestHandlingOfStaleElements.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestHandlingOfStaleElements.java
similarity index 90%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestHandlingOfStaleElements.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestHandlingOfStaleElements.java
index dc9a8cbec..aa6880e11 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestHandlingOfStaleElements.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestHandlingOfStaleElements.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.fail;
@@ -113,24 +113,24 @@ public void testListOfElements() throws Exception {
@Test
public void testPageFragment() throws Exception {
- pageFragment.root.isDisplayed();
+ pageFragment.getRoot().isDisplayed();
pageFragment.makeStale();
- pageFragment.root.isDisplayed();
+ pageFragment.getRoot().isDisplayed();
}
@Test
public void testPageFragmentWithStaleRoot() {
- rootPageFragment.inStale.isDisplayed();
+ rootPageFragment.getInStale().isDisplayed();
pageFragment.makeStale();
- rootPageFragment.inStale.isDisplayed();
+ rootPageFragment.getInStale().isDisplayed();
}
@Test
public void testListOfPageFragments() throws Exception {
StaleElementPageFragment pf = pageFragments.get(0);
- pf.root.isDisplayed();
+ pf.getRoot().isDisplayed();
pf.makeStale();
- pf.root.isDisplayed();
+ pf.getRoot().isDisplayed();
}
public static class StaleElementPageFragment {
@@ -138,8 +138,6 @@ public static class StaleElementPageFragment {
@Root
private WebElement root;
- @FindBy(className = "stale")
- private WebElement stale;
@FindBy(className = "make-stale")
private WebElement makeStale;
@@ -147,6 +145,10 @@ public void makeStale() {
makeStale.click();
}
+ public WebElement getRoot() {
+ return root;
+ }
+
}
public static class StaleRootPageFragment {
@@ -154,6 +156,9 @@ public static class StaleRootPageFragment {
@FindBy(className = "in-stale")
private WebElement inStale;
+ public WebElement getInStale() {
+ return inStale;
+ }
}
}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeEmptyFindBy.java
similarity index 79%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeEmptyFindBy.java
index 9c9409e79..5ab17d3b8 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeEmptyFindBy.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeEmptyFindBy.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -28,7 +28,6 @@
import java.util.List;
import org.jboss.arquillian.drone.api.annotation.Drone;
-import org.jboss.arquillian.graphene.enricher.findby.FindBy;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Before;
@@ -36,6 +35,7 @@
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.Select;
/**
@@ -91,24 +91,42 @@ public void testSelectById() {
@Test
public void testSeleniumFindBy() {
- checkPageFragmentById(pageObjectWithSeleniumFindBys.spanFragment);
- checkSelectById(pageObjectWithSeleniumFindBys.selectElement);
- checkWebElementById(pageObjectWithSeleniumFindBys.divWebElement);
- checkWebElementByName(pageObjectWithSeleniumFindBys.nameOfInputElement);
+ checkPageFragmentById(pageObjectWithSeleniumFindBys.getSpanFragment());
+ checkSelectById(pageObjectWithSeleniumFindBys.getSelectElement());
+ checkWebElementById(pageObjectWithSeleniumFindBys.getDivWebElement());
+ checkWebElementByName(pageObjectWithSeleniumFindBys.getNameOfInputElement());
}
public class PageObject {
@org.openqa.selenium.support.FindBy
- public WebElement divWebElement;
+ private WebElement divWebElement;
@org.openqa.selenium.support.FindBy
- public SpanFragment spanFragment;
+ private SpanFragment spanFragment;
@org.openqa.selenium.support.FindBy
- public Select selectElement;
+ private Select selectElement;
@org.openqa.selenium.support.FindBy
- public WebElement nameOfInputElement;
+ private WebElement nameOfInputElement;
+
+ public WebElement getDivWebElement() {
+ return divWebElement;
+ }
+
+ public WebElement getNameOfInputElement() {
+ return nameOfInputElement;
+ }
+
+ public Select getSelectElement() {
+ return selectElement;
+ }
+
+ public SpanFragment getSpanFragment() {
+ return spanFragment;
+ }
+
+
}
public class SpanFragment {
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeFindBys.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeFindBys.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeFindBys.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeFindBys.java
index c5824e9f8..70c9684bc 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeFindBys.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeFindBys.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeNestedPageFragments.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeNestedPageFragments.java
similarity index 97%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeNestedPageFragments.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeNestedPageFragments.java
index cb2f0cc47..e080912da 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializeNestedPageFragments.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializeNestedPageFragments.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertNotNull;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects1.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects1.java
similarity index 84%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects1.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects1.java
index c18600b9d..54ec0d3b1 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects1.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects1.java
@@ -1,9 +1,9 @@
-package org.jboss.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertEquals;
-import org.jboss.arquillian.graphene.enricher.page.TestPage;
-import org.jboss.arquillian.graphene.enricher.page.TestPage2;
+import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage2;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects2.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects2.java
similarity index 84%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects2.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects2.java
index edbb6bedb..6459f6012 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects2.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects2.java
@@ -1,9 +1,9 @@
-package org.jboss.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertEquals;
-import org.jboss.arquillian.graphene.enricher.page.TestPage;
-import org.jboss.arquillian.graphene.enricher.page.TestPage2;
+import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage2;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects3.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects3.java
similarity index 93%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects3.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects3.java
index 996b52eb6..2bab3421c 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects3.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects3.java
@@ -19,12 +19,12 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertEquals;
-import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
-import org.jboss.arquillian.graphene.enricher.page.TestPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects4.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects4.java
similarity index 93%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects4.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects4.java
index 120a9a208..96b7c59ab 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingGenericPageObjects4.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingGenericPageObjects4.java
@@ -19,10 +19,10 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
-import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
-import org.jboss.arquillian.graphene.enricher.page.TestPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.jboss.arquillian.junit.Arquillian;
import static org.junit.Assert.assertEquals;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingNestedPageObjects.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingNestedPageObjects.java
similarity index 97%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingNestedPageObjects.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingNestedPageObjects.java
index 1648bf9b2..9ab0117bf 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingNestedPageObjects.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingNestedPageObjects.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertNotNull;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingPageFragments.java
similarity index 91%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingPageFragments.java
index a35255793..ae5f56496 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestInitializingPageFragments.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestInitializingPageFragments.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -29,16 +29,15 @@
import java.util.List;
import org.jboss.arquillian.drone.api.annotation.Drone;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
-import org.jboss.arquillian.graphene.enricher.page.EmbeddedPage;
-import org.jboss.arquillian.graphene.enricher.page.TestPage;
-import org.jboss.arquillian.graphene.enricher.page.fragment.PageFragmentWithEmbeddedAnotherPageFragmentStub;
+import org.jboss.arquillian.graphene.Graphene;
+import org.jboss.arquillian.graphene.ftest.enricher.page.EmbeddedPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.TestPage;
+import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub;
+import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.PageFragmentWithEmbeddedAnotherPageFragmentStub;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.openqa.selenium.HasInputDevices;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
@@ -139,8 +138,7 @@ public void testInitializeListOfWebElementsInjectedToPageObject() {
public void testSupportForAdvancedActions() {
loadPage();
- WebDriver driver = GrapheneContext.getProxyForInterfaces(HasInputDevices.class);
- Actions builder = new Actions(driver);
+ Actions builder = new Actions(selenium);
// following tests usage of Actions with injected plain WebElement
builder.click(input);
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentList.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageFragmentList.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentList.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageFragmentList.java
index f075d1920..a66ab0241 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestPageFragmentList.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageFragmentList.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import java.net.URL;
import java.util.List;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestSamplePageFragment.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestSamplePageFragment.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestSamplePageFragment.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestSamplePageFragment.java
index 72b89e7a2..298c5a88e 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestSamplePageFragment.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestSamplePageFragment.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import java.net.URL;
import junit.framework.Assert;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementWrapper.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestWebElementWrapper.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementWrapper.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestWebElementWrapper.java
index cd99ff77a..2861ffe57 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementWrapper.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestWebElementWrapper.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher;
+package org.jboss.arquillian.graphene.ftest.enricher;
import java.net.URL;
import junit.framework.Assert;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/AbstractPage.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/AbstractPage.java
similarity index 84%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/AbstractPage.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/AbstractPage.java
index 2d21e86c4..c171e2aa7 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/AbstractPage.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/AbstractPage.java
@@ -1,4 +1,4 @@
-package org.jboss.arquillian.graphene.enricher.page;
+package org.jboss.arquillian.graphene.ftest.enricher.page;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
@@ -7,7 +7,7 @@ public class AbstractPage {
@FindBy(xpath = "//input")
private WebElement input;
-
+
public WebElement getInput() {
return input;
}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/EmbeddedPage.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/EmbeddedPage.java
similarity index 86%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/EmbeddedPage.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/EmbeddedPage.java
index 69524ccf0..03b9b13fd 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/EmbeddedPage.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/EmbeddedPage.java
@@ -1,4 +1,4 @@
-package org.jboss.arquillian.graphene.enricher.page;
+package org.jboss.arquillian.graphene.ftest.enricher.page;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
@@ -6,7 +6,7 @@
public class EmbeddedPage {
public static final String EXPECTED_TEXT_OF_EMBEDDED_ELEM = "This is embedded element";
-
+
@FindBy(id="embeddedElement")
private WebElement embeddedElement;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage.java
similarity index 94%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage.java
index 10bef196a..4760b18ef 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage.java
@@ -19,11 +19,11 @@
* 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.arquillian.graphene.enricher.page;
+package org.jboss.arquillian.graphene.ftest.enricher.page;
import java.util.List;
-import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
+import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage2.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage2.java
similarity index 89%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage2.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage2.java
index 4817060d7..24e08e84c 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/TestPage2.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/TestPage2.java
@@ -1,6 +1,6 @@
-package org.jboss.arquillian.graphene.enricher.page;
+package org.jboss.arquillian.graphene.ftest.enricher.page;
-import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
+import org.jboss.arquillian.graphene.ftest.enricher.page.fragment.AbstractPageFragmentStub;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/AbstractPageFragmentStub.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/AbstractPageFragmentStub.java
new file mode 100644
index 000000000..6483d550e
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/AbstractPageFragmentStub.java
@@ -0,0 +1,179 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.ftest.enricher.page.fragment;
+
+import java.util.List;
+
+import org.jboss.arquillian.graphene.spi.annotations.Root;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.FindBy;
+
+/**
+ *
+ * @author <a href="mailto:[email protected]">Juraj Huska</a>
+ *
+ */
+public class AbstractPageFragmentStub {
+
+ @Root
+ private WebElement root;
+
+ @FindBy(className = "classNameRef")
+ private WebElement locatorRefByClassName;
+
+ @FindBy(name = "nameRef")
+ private WebElement locatorRefByName;
+
+ @FindBy(id = "idRef")
+ private WebElement locatorRefById;
+
+ @FindBy(tagName = "tagNameRef")
+ private WebElement locatorRefByTagName;
+
+ @FindBy(linkText = "linkTextRef")
+ private WebElement locatorRefByLinkText;
+
+ @FindBy(partialLinkText = "partiaLinkTextRef")
+ private WebElement locatorRefByPartialLinkText;
+
+ @FindBy(xpath = "//div[@class='refByXpath']")
+ private WebElement locatorRefByXPath;
+
+ @FindBy(css = "cssSelectorRef")
+ private WebElement locatorRefByCssSelector;
+
+ @FindBy(className="spans")
+ private List<WebElement> spansInPageFragment;
+
+ public String invokeMethodOnRoot() {
+ return root.getText();
+ }
+
+ public String invokeMethodOnElementRefByClass() {
+ return this.locatorRefByClassName.getText();
+ }
+
+ public String invokeMethodOnElementRefById() {
+ return this.locatorRefById.getText();
+ }
+
+ public String invokeMethodOnElementRefByCSS() {
+ return this.locatorRefByCssSelector.getText();
+ }
+
+ public String invokeMethodOnElementRefByName() {
+ return this.locatorRefByName.getText();
+ }
+
+ public String invokeMethodOnElementRefByTagName() {
+ return locatorRefByTagName.getAttribute("id");
+ }
+
+ public String invokeMethodOnElementRefByXpath() {
+ return this.locatorRefByXPath.getText();
+ }
+
+ public String invokeMethodOnElementRefByLinkText() {
+ return this.locatorRefByLinkText.getText();
+ }
+
+ public String invokeMethodOnElementRefByPartialLinkText() {
+ return this.locatorRefByPartialLinkText.getText();
+ }
+
+ public WebElement getRootProxy() {
+ return this.root;
+ }
+
+ public WebElement getLocatorRefByClassName() {
+ return locatorRefByClassName;
+ }
+
+ public void setLocatorRefByClassName(WebElement locatorRefByClassName) {
+ this.locatorRefByClassName = locatorRefByClassName;
+ }
+
+ public WebElement getLocatorRefByName() {
+ return locatorRefByName;
+ }
+
+ public void setLocatorRefByName(WebElement locatorRefByName) {
+ this.locatorRefByName = locatorRefByName;
+ }
+
+ public WebElement getLocatorRefById() {
+ return locatorRefById;
+ }
+
+ public void setLocatorRefById(WebElement locatorRefById) {
+ this.locatorRefById = locatorRefById;
+ }
+
+ public WebElement getLocatorRefByTagName() {
+ return locatorRefByTagName;
+ }
+
+ public void setLocatorRefByTagName(WebElement locatorRefByTagName) {
+ this.locatorRefByTagName = locatorRefByTagName;
+ }
+
+ public WebElement getLocatorRefByLinkText() {
+ return locatorRefByLinkText;
+ }
+
+ public void setLocatorRefByLinkText(WebElement locatorRefByLinkText) {
+ this.locatorRefByLinkText = locatorRefByLinkText;
+ }
+
+ public WebElement getLocatorRefByPartialLinkText() {
+ return locatorRefByPartialLinkText;
+ }
+
+ public void setLocatorRefByPartialLinkText(WebElement locatorRefByPartialLinkText) {
+ this.locatorRefByPartialLinkText = locatorRefByPartialLinkText;
+ }
+
+ public WebElement getLocatorRefByXPath() {
+ return locatorRefByXPath;
+ }
+
+ public void setLocatorRefByXPath(WebElement locatorRefByXPath) {
+ this.locatorRefByXPath = locatorRefByXPath;
+ }
+
+ public WebElement getLocatorRefByCssSelector() {
+ return locatorRefByCssSelector;
+ }
+
+ public void setLocatorRefByCssSelector(WebElement locatorRefByCssSelector) {
+ this.locatorRefByCssSelector = locatorRefByCssSelector;
+ }
+
+ public List<WebElement> getSpansInPageFragment() {
+ return spansInPageFragment;
+ }
+
+ public void setSpans(List<WebElement> divs) {
+ this.spansInPageFragment = divs;
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java
similarity index 92%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java
index 3069bddeb..9c4364359 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/PageFragmentWithEmbeddedAnotherPageFragmentStub.java
@@ -19,9 +19,8 @@
* 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.arquillian.graphene.enricher.page.fragment;
+package org.jboss.arquillian.graphene.ftest.enricher.page.fragment;
-import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
import org.jboss.arquillian.graphene.spi.annotations.Root;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/Panel.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/Panel.java
similarity index 95%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/Panel.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/Panel.java
index 7cf2fb168..456979235 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/Panel.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/Panel.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher.page.fragment;
+package org.jboss.arquillian.graphene.ftest.enricher.page.fragment;
import org.jboss.arquillian.graphene.component.object.api.switchable.ComponentContainer;
import org.jboss.arquillian.graphene.enricher.PageFragmentEnricher;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/TabPanel.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/TabPanel.java
similarity index 97%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/TabPanel.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/TabPanel.java
index e672b5db2..d2e6243e6 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/enricher/page/fragment/TabPanel.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/page/fragment/TabPanel.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.enricher.page.fragment;
+package org.jboss.arquillian.graphene.ftest.enricher.page.fragment;
import static org.jboss.arquillian.graphene.Graphene.guardAjax;
import static org.jboss.arquillian.graphene.Graphene.guardHttp;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/GuardsTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/GuardsTestCase.java
index dbdfff847..13f581c5a 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/GuardsTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/GuardsTestCase.java
@@ -30,7 +30,6 @@
import java.net.URL;
import org.jboss.arquillian.drone.api.annotation.Drone;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.jboss.arquillian.graphene.guard.RequestGuardException;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Assert;
@@ -152,9 +151,9 @@ public static interface Activity {
public void perform() throws Exception;
}
- public static class XhrAndRelocationActivity implements Activity {
+ public class XhrAndRelocationActivity implements Activity {
+ @Override
public void perform() throws Exception {
- WebDriver browser = GrapheneContext.getProxy();
browser.findElement(By.id("xhr")).click();
String url = browser.getCurrentUrl().replace("sample1", "sample2");
Thread.sleep(200);
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/RequestGuardTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/RequestGuardTestCase.java
index d6e05732a..deacdcdab 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/RequestGuardTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/guard/RequestGuardTestCase.java
@@ -25,8 +25,10 @@
import static org.junit.Assert.assertEquals;
import java.net.URL;
+import org.jboss.arquillian.drone.api.annotation.Default;
import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.guard.RequestGuard;
import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory;
import org.jboss.arquillian.graphene.page.RequestType;
@@ -62,7 +64,7 @@ public void loadPage() {
@Test
public void testXhr() throws InterruptedException {
- RequestGuard guard = JSInterfaceFactory.create(RequestGuard.class);
+ RequestGuard guard = JSInterfaceFactory.create(GrapheneContext.getContextFor(Default.class), RequestGuard.class);
assertEquals(RequestType.HTTP, guard.getRequestType());
guard.clearRequestDone();
assertEquals(RequestType.NONE, guard.getRequestType());
@@ -73,7 +75,7 @@ public void testXhr() throws InterruptedException {
@Test
public void testHttp() {
- RequestGuard guard = JSInterfaceFactory.create(RequestGuard.class);
+ RequestGuard guard = JSInterfaceFactory.create(GrapheneContext.getContextFor(Default.class), RequestGuard.class);
assertEquals(RequestType.HTTP, guard.getRequestType());
guard.clearRequestDone();
assertEquals(RequestType.NONE, guard.getRequestType());
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java
index fa5a46a41..ae06df593 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java
@@ -3,7 +3,7 @@
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.EventContext;
import org.jboss.arquillian.core.spi.LoadableExtension;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
+import org.jboss.arquillian.drone.api.annotation.Default;
import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.jboss.arquillian.graphene.proxy.Interceptor;
import org.jboss.arquillian.graphene.proxy.InvocationContext;
@@ -24,7 +24,7 @@ public void register_interceptor(@Observes EventContext<Test> ctx) {
try {
Test event = ctx.getEvent();
if (event.getTestClass().getJavaClass() == TestInterceptorRegistration.class) {
- WebDriver browser = GrapheneContext.getProxy();
+ WebDriver browser = org.jboss.arquillian.graphene.GrapheneContext.getContextFor(Default.class).getWebDriver();
((GrapheneProxyInstance) browser).registerInterceptor(new Interceptor() {
@Override
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/issues/ARQGRA269TestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/issues/ARQGRA269TestCase.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/issues/ARQGRA269TestCase.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/issues/ARQGRA269TestCase.java
index f9e3822a5..6d1245b32 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/issues/ARQGRA269TestCase.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/issues/ARQGRA269TestCase.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.issues;
+package org.jboss.arquillian.graphene.ftest.issues;
import java.net.URL;
import junit.framework.Assert;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/JavaScriptPageExtensionTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/JavaScriptPageExtensionTestCase.java
index ec779cbbe..bc565069c 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/JavaScriptPageExtensionTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/JavaScriptPageExtensionTestCase.java
@@ -25,11 +25,14 @@
import java.util.List;
import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.Graphene;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.javascript.Dependency;
import org.jboss.arquillian.graphene.javascript.InstallableJavaScript;
import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory;
import org.jboss.arquillian.graphene.javascript.JavaScript;
import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@@ -47,6 +50,9 @@ public class JavaScriptPageExtensionTestCase {
@Drone
private WebDriver browser;
+ @ArquillianResource
+ private GrapheneContext context;
+
public void loadPage() {
URL page = this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/javascript/sample.html");
browser.navigate().to(page);
@@ -55,7 +61,7 @@ public void loadPage() {
@Test
public void testWithoutSources() {
loadPage();
- Document document = JSInterfaceFactory.create(Document.class);
+ Document document = JSInterfaceFactory.create(context, Document.class);
List<WebElement> elements = document.getElementsByTagName("html");
Assert.assertNotNull(elements);
Assert.assertEquals(1, elements.size());
@@ -65,27 +71,27 @@ public void testWithoutSources() {
public void testWithSources() {
loadPage();
- HelloWorld helloWorld = JSInterfaceFactory.create(HelloWorld.class);
+ HelloWorld helloWorld = JSInterfaceFactory.create(context, HelloWorld.class);
Assert.assertEquals("Hello World!", helloWorld.hello());
}
@Test
public void testWithInterfaceDependencies() {
loadPage();
- HelloWorld2 helloWorld = JSInterfaceFactory.create(HelloWorld2.class);
+ HelloWorld2 helloWorld = JSInterfaceFactory.create(context, HelloWorld2.class);
Assert.assertEquals("Hello World!", helloWorld.hello());
}
@Test(expected=IllegalArgumentException.class)
public void testWithoutSourceAndWithInterfaceDependencies() {
loadPage();
- JSInterfaceFactory.create(Document2.class).getTitle();
+ JSInterfaceFactory.create(context, Document2.class).getTitle();
}
@Test
public void testAbstractClass() {
loadPage();
- Document3 document = JSInterfaceFactory.create(Document3.class);
+ Document3 document = JSInterfaceFactory.create(context, Document3.class);
Assert.assertEquals(browser.findElement(By.tagName("h1")), document.getHeader());
}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/TestCustomJSInterface.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/TestCustomJSInterface.java
index 09a004724..b8945b013 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/TestCustomJSInterface.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/javascript/TestCustomJSInterface.java
@@ -22,9 +22,12 @@
import java.util.List;
import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.Graphene;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory;
import org.jboss.arquillian.graphene.javascript.JavaScript;
import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
@@ -38,12 +41,15 @@ public class TestCustomJSInterface {
@Drone
WebDriver browser;
-
+
+ @ArquillianResource
+ private GrapheneContext context;
+
@Test
public void test() {
browser.navigate().to("http://127.0.0.1:4444");
-
- Document document = JSInterfaceFactory.create(Document.class);
+
+ Document document = JSInterfaceFactory.create(context, Document.class);
List<WebElement> elements = document.getElementsByTagName("html");
assertNotNull(elements);
assertEquals(1, elements.size());
@@ -51,9 +57,9 @@ public void test() {
@JavaScript("document")
public static interface Document {
-
+
String getTitle();
-
+
List<WebElement> getElementsByTagName(String tagName);
}
}
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/PageExtensionTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/PageExtensionTestCase.java
index 371a2a1e0..b9810a2d9 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/PageExtensionTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/page/extension/PageExtensionTestCase.java
@@ -32,11 +32,13 @@
import junit.framework.Assert;
import org.jboss.arquillian.drone.api.annotation.Drone;
-import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext;
+import org.jboss.arquillian.graphene.Graphene;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistry;
import org.jboss.arquillian.graphene.spi.javascript.JavaScript;
import org.jboss.arquillian.graphene.spi.page.PageExtension;
import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
@@ -51,6 +53,9 @@ public class PageExtensionTestCase {
@Drone
private WebDriver browser;
+ @ArquillianResource
+ private GrapheneContext context;
+
public void loadPage() {
URL page = this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/page/extension/sample.html");
browser.get(page.toString());
@@ -65,10 +70,10 @@ public void testCorrectInstallation() {
when(pageExtensionMock.getInstallationDetectionScript()).thenReturn(JavaScript.fromString("return (typeof Document.Graphene != 'undefined');"));
when(pageExtensionMock.getRequired()).thenReturn(Collections.EMPTY_LIST);
// registry
- PageExtensionRegistry registry = GraphenePageExtensionsContext.getRegistryProxy();
+ PageExtensionRegistry registry = context.getPageExtensionRegistry();
registry.register(pageExtensionMock);
// test
- GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).install();
+ context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).install();
}
@Test(expected=IllegalStateException.class)
@@ -80,10 +85,10 @@ public void testIncorrectInstallation() {
when(pageExtensionMock.getInstallationDetectionScript()).thenReturn(JavaScript.fromString("return (typeof Graphene != 'undefined');"));
when(pageExtensionMock.getRequired()).thenReturn(Collections.EMPTY_LIST);
// registry
- PageExtensionRegistry registry = GraphenePageExtensionsContext.getRegistryProxy();
+ PageExtensionRegistry registry = context.getPageExtensionRegistry();
registry.register(pageExtensionMock);
// test
- GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).install();
+ context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).install();
}
@Test
@@ -97,13 +102,13 @@ public void testInstallationWithRequirements() {
requirements.add(SimplePageExtension.class.getName());
when(pageExtensionMock.getRequired()).thenReturn(requirements);
// registry
- PageExtensionRegistry registry = GraphenePageExtensionsContext.getRegistryProxy();
+ PageExtensionRegistry registry = context.getPageExtensionRegistry();
registry.register(new SimplePageExtension());
registry.register(pageExtensionMock);
// test
- GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).install();
- Assert.assertTrue(GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(SimplePageExtension.class.getName()).isInstalled());
- Assert.assertTrue(GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).isInstalled());
+ context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).install();
+ Assert.assertTrue(context.getPageExtensionInstallatorProvider().installator(SimplePageExtension.class.getName()).isInstalled());
+ Assert.assertTrue(context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).isInstalled());
}
@Test(expected=IllegalStateException.class)
@@ -119,13 +124,13 @@ public void testInstallationWithCyclicRequirements() {
requirements.add(CyclicPageExtension2.class.getName());
when(pageExtensionMock.getRequired()).thenReturn(requirements);
// registry
- PageExtensionRegistry registry = GraphenePageExtensionsContext.getRegistryProxy();
+ PageExtensionRegistry registry = context.getPageExtensionRegistry();
registry.register(new SimplePageExtension());
registry.register(pageExtensionMock);
registry.register(new CyclicPageExtension1());
registry.register(new CyclicPageExtension2());
// test
- GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(pageExtensionMock.getName()).install();
+ context.getPageExtensionInstallatorProvider().installator(pageExtensionMock.getName()).install();
}
private static class SimplePageExtension implements PageExtension {
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/AbstractParallelTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/AbstractParallelTest.java
new file mode 100644
index 000000000..48a0ffcae
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/AbstractParallelTest.java
@@ -0,0 +1,64 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.ftest.parallel;
+
+import java.util.List;
+import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.javascript.JavaScript;
+import org.jboss.arquillian.junit.Arquillian;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+import qualifier.Browser1;
+import qualifier.Browser2;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+@RunWith(Arquillian.class)
+public abstract class AbstractParallelTest {
+
+ @Browser1
+ @Drone
+ protected WebDriver browser1;
+
+ @Browser2
+ @Drone
+ protected WebDriver browser2;
+
+ @Drone
+ protected WebDriver browserDefault;
+
+ public void loadPage() {
+ browser1.get(this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/parallel/one.html").toString());
+ browser2.get(this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/parallel/two.html").toString());
+ browserDefault.get(this.getClass().getClassLoader().getResource("org/jboss/arquillian/graphene/ftest/parallel/default.html").toString());
+ }
+
+ @JavaScript("document")
+ public static interface Document {
+
+ List<WebElement> getElementsByTagName(String tagName);
+
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestGraphene.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestGraphene.java
new file mode 100644
index 000000000..0fd5429eb
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestGraphene.java
@@ -0,0 +1,142 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.ftest.parallel;
+
+import org.jboss.arquillian.graphene.Graphene;
+import org.jboss.arquillian.graphene.spi.annotations.Page;
+import org.junit.Test;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.FindBy;
+import qualifier.Browser1;
+import qualifier.Browser2;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+public class TestGraphene extends AbstractParallelTest {
+
+ @Browser1
+ @FindBy(tagName="h1")
+ private WebElement header1;
+
+ @Browser2
+ @FindBy(tagName="h1")
+ private WebElement header2;
+
+ @FindBy(tagName="h1")
+ private WebElement headerDefault;
+
+ @Page
+ @Browser1
+ private SimplePage page1;
+
+ @Page
+ @Browser2
+ private SimplePage page2;
+
+ @Page
+ private SimplePage pageDefault;
+
+
+ @Test
+ public void testWaitWithElements() {
+ loadPage();
+
+ Graphene.waitGui()
+ .until()
+ .element(header1)
+ .text()
+ .equalTo("Page 1");
+
+ Graphene.waitGui()
+ .until()
+ .element(header2)
+ .text()
+ .equalTo("Page 2");
+
+ Graphene.waitGui()
+ .until()
+ .element(headerDefault)
+ .text()
+ .equalTo("Page Default");
+ }
+
+ @Test
+ public void testWaitWithBys() {
+ loadPage();
+
+ Graphene.waitGui(browser1)
+ .until()
+ .element(By.tagName("h1"))
+ .text()
+ .equalTo("Page 1");
+
+ Graphene.waitGui(browser2)
+ .until()
+ .element(By.tagName("h1"))
+ .text()
+ .equalTo("Page 2");
+
+ Graphene.waitGui(browserDefault)
+ .until()
+ .element(By.tagName("h1"))
+ .text()
+ .equalTo("Page Default");
+ }
+
+ @Test
+ public void testGuardHttp() {
+ loadPage();
+
+ Graphene.guardHttp(page1).http();
+ Graphene.guardHttp(page2).http();
+ Graphene.guardHttp(pageDefault).http();
+ }
+
+ @Test
+ public void testGuardXhr() {
+ loadPage();
+
+ Graphene.guardXhr(page1).xhr();
+ Graphene.guardXhr(page2).xhr();
+ Graphene.guardXhr(pageDefault).xhr();
+ }
+
+ public static class SimplePage {
+
+ @FindBy
+ private WebElement http;
+
+ @FindBy
+ private WebElement xhr;
+
+ public void http() {
+ http.click();
+ }
+
+ public void xhr() {
+ xhr.click();
+ }
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestInterceptors.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestInterceptors.java
new file mode 100644
index 000000000..1e86343c4
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestInterceptors.java
@@ -0,0 +1,90 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.ftest.parallel;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import junit.framework.Assert;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
+import org.jboss.arquillian.graphene.proxy.Interceptor;
+import org.jboss.arquillian.graphene.proxy.InvocationContext;
+import org.jboss.arquillian.test.api.ArquillianResource;
+import org.junit.Before;
+import org.junit.Test;
+import qualifier.Browser1;
+import qualifier.Browser2;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+public class TestInterceptors extends AbstractParallelTest {
+
+ @Browser1
+ @ArquillianResource
+ private GrapheneContext context1;
+
+ @Browser2
+ @ArquillianResource
+ private GrapheneContext context2;
+
+ @ArquillianResource
+ private GrapheneContext contextDefault;
+
+ private AtomicInteger counter1 = new AtomicInteger();
+ private AtomicInteger counter2 = new AtomicInteger();
+ private AtomicInteger counterDefault = new AtomicInteger();
+
+ @Before
+ public void resetCounters() {
+ this.counter1.set(0);
+ this.counter2.set(0);
+ this.counterDefault.set(0);
+ }
+
+ @Test
+ public void testContextVsDrone() {
+ loadPage();
+
+ ((GrapheneProxyInstance) browser1).registerInterceptor(createInterceptor(counter1));
+ ((GrapheneProxyInstance) browser2).registerInterceptor(createInterceptor(counter2));
+ ((GrapheneProxyInstance) browserDefault).registerInterceptor(createInterceptor(counterDefault));
+
+ context1.getWebDriver().getTitle();
+ context2.getWebDriver().getTitle();
+ contextDefault.getWebDriver().getTitle();
+
+ Assert.assertEquals(1, counter1.get());
+ Assert.assertEquals(1, counter2.get());
+ Assert.assertEquals(1, counterDefault.get());
+ }
+
+ protected Interceptor createInterceptor(final AtomicInteger counter) {
+ return new Interceptor() {
+ @Override
+ public Object intercept(InvocationContext context) throws Throwable {
+ counter.incrementAndGet();
+ return context.invoke();
+ }
+ };
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageFragments.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageFragments.java
new file mode 100644
index 000000000..1cd9bf5f8
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageFragments.java
@@ -0,0 +1,178 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.ftest.parallel;
+
+import junit.framework.Assert;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.javascript.JavaScript;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.arquillian.test.api.ArquillianResource;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.JavascriptExecutor;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.FindBy;
+import qualifier.Browser1;
+import qualifier.Browser2;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+@RunWith(Arquillian.class)
+public class TestPageFragments extends AbstractParallelTest {
+
+ @Browser1
+ @FindBy(tagName="body")
+ private PageFragment pageFragment1;
+
+ @Browser2
+ @FindBy(tagName="body")
+ private PageFragment pageFragment2;
+
+ @FindBy(tagName="body")
+ private PageFragment pageFragmentDefault;
+
+ @Test
+ public void testNotNull() {
+ Assert.assertNotNull(pageFragment1);
+ Assert.assertNotNull(pageFragment2);
+ Assert.assertNotNull(pageFragmentDefault);
+ }
+
+ @Test
+ public void testHeadersViaAttributes() {
+ loadPage();
+
+ Assert.assertNotNull(pageFragment1.header);
+ Assert.assertNotNull(pageFragment1.header);
+ Assert.assertNotNull(pageFragmentDefault.header);
+
+ Assert.assertEquals("Page 1", pageFragment1.header.getText().trim());
+ Assert.assertEquals("Page 2", pageFragment2.header.getText().trim());
+ Assert.assertEquals("Page Default", pageFragmentDefault.header.getText().trim());
+ }
+
+ @Test
+ public void testHeadersViaMethod() {
+ loadPage();
+
+ Assert.assertNotNull(pageFragment1.header());
+ Assert.assertNotNull(pageFragment2.header());
+ Assert.assertNotNull(pageFragmentDefault.header());
+
+ Assert.assertEquals("Page 1", pageFragment1.header().getText().trim());
+ Assert.assertEquals("Page 2", pageFragment2.header().getText().trim());
+ Assert.assertEquals("Page Default", pageFragmentDefault.header().getText().trim());
+ }
+
+ @Test
+ public void testDroneInPageFragments() {
+ loadPage();
+
+ String url1 = browser1.getCurrentUrl();
+ String url2 = browser2.getCurrentUrl();
+ String urlDefault = browserDefault.getCurrentUrl();
+
+ Assert.assertNotNull(pageFragment1.browser());
+ Assert.assertNotNull(pageFragment2.browser());
+ Assert.assertNotNull(pageFragmentDefault.browser());
+
+ Assert.assertEquals(url1, pageFragment1.getCurrentURL());
+ Assert.assertEquals(url2, pageFragment2.getCurrentURL());
+ Assert.assertEquals(urlDefault, pageFragmentDefault.getCurrentURL());
+ }
+
+ @Test
+ public void testJavaScriptInterfaceInPageFragments() {
+ loadPage();
+ Assert.assertEquals("Page 1", pageFragment1.getHeaderTextViaJavaScriptInterface().trim());
+ Assert.assertEquals("Page 2", pageFragment2.getHeaderTextViaJavaScriptInterface().trim());
+ Assert.assertEquals("Page Default", pageFragmentDefault.getHeaderTextViaJavaScriptInterface().trim());
+ }
+
+ @Test
+ public void testJavaScriptExecutorInPageFragments() {
+ loadPage();
+ Assert.assertEquals("Page 1", pageFragment1.getTitleViaJavaScriptExecutor().trim());
+ Assert.assertEquals("Page 2", pageFragment2.getTitleViaJavaScriptExecutor().trim());
+ Assert.assertEquals("Page Default", pageFragmentDefault.getTitleViaJavaScriptExecutor().trim());
+ }
+
+ @Test
+ public void testJavaScriptExecutorInvocation() {
+ loadPage();
+ }
+
+ @Test
+ public void testGrapheneContextQualifier() {
+ Assert.assertEquals(Browser1.class, pageFragment1.getQualifier());
+ Assert.assertEquals(Browser2.class, pageFragment2.getQualifier());
+ Assert.assertEquals(Default.class, pageFragmentDefault.getQualifier());
+ }
+
+ public static class PageFragment {
+
+ @JavaScript
+ private Document document;
+
+ @Drone
+ private WebDriver browser;
+
+ @FindBy(tagName="h1")
+ private WebElement header;
+
+ @ArquillianResource
+ private JavascriptExecutor javascriptExecutor;
+
+ @ArquillianResource
+ private GrapheneContext context;
+
+ public String getCurrentURL() {
+ return browser.getCurrentUrl();
+ }
+
+ public String getHeaderTextViaJavaScriptInterface() {
+ return document.getElementsByTagName("h1").get(0).getText().trim();
+ }
+
+ public Class<?> getQualifier() {
+ return context.getQualifier();
+ }
+
+ public String getTitleViaJavaScriptExecutor() {
+ return (String) javascriptExecutor.executeScript("return document.title");
+ }
+
+ public WebElement header() {
+ return header;
+ }
+
+ public WebDriver browser() {
+ return browser;
+ }
+
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageObjects.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageObjects.java
new file mode 100644
index 000000000..d7a73cd87
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestPageObjects.java
@@ -0,0 +1,174 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.ftest.parallel;
+
+import junit.framework.Assert;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.javascript.JavaScript;
+import org.jboss.arquillian.graphene.spi.annotations.Page;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.arquillian.test.api.ArquillianResource;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.JavascriptExecutor;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.FindBy;
+import qualifier.Browser1;
+import qualifier.Browser2;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+@RunWith(Arquillian.class)
+public class TestPageObjects extends AbstractParallelTest {
+
+ @Page
+ @Browser1
+ private SimplePage page1;
+
+ @Page
+ @Browser2
+ private SimplePage page2;
+
+ @Page
+ private SimplePage pageDefault;
+
+ @Test
+ public void testNotNull() {
+ Assert.assertNotNull(page1);
+ Assert.assertNotNull(page2);
+ Assert.assertNotNull(pageDefault);
+ }
+
+ @Test
+ public void testHeadersViaAttributes() {
+ loadPage();
+
+ Assert.assertNotNull(page1.header);
+ Assert.assertNotNull(page2.header);
+ Assert.assertNotNull(pageDefault.header);
+
+ Assert.assertEquals("Page 1", page1.header.getText().trim());
+ Assert.assertEquals("Page 2", page2.header.getText().trim());
+ Assert.assertEquals("Page Default", pageDefault.header.getText().trim());
+ }
+
+ @Test
+ public void testHeadersViaMethod() {
+ loadPage();
+
+ Assert.assertNotNull(page1.header());
+ Assert.assertNotNull(page2.header());
+ Assert.assertNotNull(pageDefault.header());
+
+ Assert.assertEquals("Page 1", page1.header().getText().trim());
+ Assert.assertEquals("Page 2", page2.header().getText().trim());
+ Assert.assertEquals("Page Default", pageDefault.header().getText().trim());
+ }
+
+ @Test
+ public void testDroneInPageObjects() {
+ loadPage();
+
+ String url1 = browser1.getCurrentUrl();
+ String url2 = browser2.getCurrentUrl();
+ String urlDefault = browserDefault.getCurrentUrl();
+
+ Assert.assertNotNull(page1.browser());
+ Assert.assertNotNull(page2.browser());
+ Assert.assertNotNull(pageDefault.browser());
+
+ Assert.assertEquals(url1, page1.getCurrentURL());
+ Assert.assertEquals(url2, page2.getCurrentURL());
+ Assert.assertEquals(urlDefault, pageDefault.getCurrentURL());
+ }
+
+ @Test
+ public void testJavaScriptInterfaceInPageObjects() {
+ loadPage();
+ Assert.assertEquals("Page 1", page1.getHeaderTextViaJavaScriptInterface().trim());
+ Assert.assertEquals("Page 2", page2.getHeaderTextViaJavaScriptInterface().trim());
+ Assert.assertEquals("Page Default", pageDefault.getHeaderTextViaJavaScriptInterface().trim());
+ }
+
+ @Test
+ public void testJavaScriptExecutorInPageObjects() {
+ loadPage();
+
+ Assert.assertEquals("Page 1", page1.getTitleViaJavaScriptExecutor().trim());
+ Assert.assertEquals("Page 2", page2.getTitleViaJavaScriptExecutor().trim());
+ Assert.assertEquals("Page Default", pageDefault.getTitleViaJavaScriptExecutor().trim());
+ }
+
+ @Test
+ public void testGrapheneContextQualifier() {
+ Assert.assertEquals(Browser1.class, page1.getQualifier());
+ Assert.assertEquals(Browser2.class, page2.getQualifier());
+ Assert.assertEquals(Default.class, pageDefault.getQualifier());
+ }
+
+ public static class SimplePage {
+
+ @FindBy(tagName="h1")
+ private WebElement header;
+
+ @JavaScript
+ private Document document;
+
+ @ArquillianResource
+ private JavascriptExecutor javascriptExecutor;
+
+ @ArquillianResource
+ private GrapheneContext context;
+
+ @Drone
+ private WebDriver browser;
+
+ public String getCurrentURL() {
+ return browser.getCurrentUrl();
+ }
+
+ public String getTitleViaJavaScriptExecutor() {
+ return (String) javascriptExecutor.executeScript("return document.title");
+ }
+
+ public String getHeaderTextViaJavaScriptInterface() {
+ return document.getElementsByTagName("h1").get(0).getText().trim();
+ }
+
+ public Class<?> getQualifier() {
+ return context.getQualifier();
+ }
+
+ public WebElement header() {
+ return header;
+ }
+
+ public WebDriver browser() {
+ return browser;
+ }
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestTestClass.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestTestClass.java
new file mode 100644
index 000000000..06ac92c37
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/parallel/TestTestClass.java
@@ -0,0 +1,142 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.ftest.parallel;
+
+import junit.framework.Assert;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.javascript.JavaScript;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.arquillian.test.api.ArquillianResource;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.By;
+import org.openqa.selenium.JavascriptExecutor;
+import org.openqa.selenium.WebElement;
+import qualifier.Browser1;
+import qualifier.Browser2;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+@RunWith(Arquillian.class)
+public class TestTestClass extends AbstractParallelTest {
+
+ @Browser1
+ @JavaScript
+ private Document document1;
+
+ @Browser2
+ @JavaScript
+ private Document document2;
+
+ @JavaScript
+ private Document documentDefault;
+
+ @Browser1
+ @ArquillianResource
+ private JavascriptExecutor javaScriptExecutor1;
+
+ @Browser2
+ @ArquillianResource
+ private JavascriptExecutor javaScriptExecutor2;
+
+ @ArquillianResource
+ private JavascriptExecutor javaScriptExecutorDefault;
+
+ @Browser1
+ @ArquillianResource
+ private GrapheneContext context1;
+
+ @Browser2
+ @ArquillianResource
+ private GrapheneContext context2;
+
+ @ArquillianResource
+ private GrapheneContext contextDefault;
+
+ @Test
+ public void testJavaScriptNotNull() {
+ Assert.assertNotNull(document1);
+ Assert.assertNotNull(document2);
+ Assert.assertNotNull(documentDefault);
+ }
+
+ @Test
+ public void testDroneNotNull() {
+ Assert.assertNotNull(browser1);
+ Assert.assertNotNull(browser2);
+ Assert.assertNotNull(browserDefault);
+ }
+
+ @Test
+ public void testArquillianResourcesNotNull() {
+ Assert.assertNotNull(javaScriptExecutor1);
+ Assert.assertNotNull(javaScriptExecutor2);
+ Assert.assertNotNull(javaScriptExecutorDefault);
+ }
+
+ @Test
+ public void testJavaScriptInterfaceInvocation() {
+ loadPage();
+ Assert.assertEquals(1, document1.getElementsByTagName("h1").size());
+ Assert.assertEquals(1, document2.getElementsByTagName("h1").size());
+ Assert.assertEquals(1, documentDefault.getElementsByTagName("h1").size());
+ Assert.assertEquals("Page 1", document1.getElementsByTagName("h1").get(0).getText());
+ Assert.assertEquals("Page 2", document2.getElementsByTagName("h1").get(0).getText());
+ Assert.assertEquals("Page Default", documentDefault.getElementsByTagName("h1").get(0).getText());
+ }
+
+ @Test
+ public void testJavaScriptExecutorInvocation() {
+ loadPage();
+
+ String title1 = (String) javaScriptExecutor1.executeScript("return document.title");
+ String title2 = (String) javaScriptExecutor2.executeScript("return document.title");
+ String titleDefault = (String) javaScriptExecutorDefault.executeScript("return document.title");
+
+ Assert.assertEquals("Page 1", title1);
+ Assert.assertEquals("Page 2", title2);
+ Assert.assertEquals("Page Default", titleDefault);
+ }
+
+ @Test
+ public void testOpenPage() {
+ loadPage();
+ WebElement header1 = browser1.findElement(By.tagName("h1"));
+ WebElement header2 = browser2.findElement(By.tagName("h1"));
+ WebElement headerDefault = browserDefault.findElement(By.tagName("h1"));
+ Assert.assertNotNull(header1);
+ Assert.assertNotNull(header2);
+ Assert.assertNotNull(headerDefault);
+ Assert.assertEquals("Page 1", header1.getText().trim());
+ Assert.assertEquals("Page 2", header2.getText().trim());
+ Assert.assertEquals("Page Default", headerDefault.getText().trim());
+ }
+
+ @Test
+ public void testGrapheneContextQualifier() {
+ Assert.assertEquals(Browser1.class, context1.getQualifier());
+ Assert.assertEquals(Browser2.class, context2.getQualifier());
+ Assert.assertEquals(Default.class, contextDefault.getQualifier());
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/webdriver/FindElementTestCase.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/webdriver/FindElementTestCase.java
similarity index 99%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/webdriver/FindElementTestCase.java
rename to graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/webdriver/FindElementTestCase.java
index 25cb725fc..ace21e4e9 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/webdriver/FindElementTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/webdriver/FindElementTestCase.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.webdriver;
+package org.jboss.arquillian.graphene.ftest.webdriver;
import java.net.URL;
import org.jboss.arquillian.drone.api.annotation.Drone;
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser1.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser1.java
new file mode 100644
index 000000000..30e54e10a
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser1.java
@@ -0,0 +1,35 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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 qualifier;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import org.jboss.arquillian.drone.api.annotation.Qualifier;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ ElementType.FIELD, ElementType.PARAMETER })
+@Qualifier
+public @interface Browser1 {
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser2.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser2.java
new file mode 100644
index 000000000..dc43f8b89
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/qualifier/Browser2.java
@@ -0,0 +1,34 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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 qualifier;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import org.jboss.arquillian.drone.api.annotation.Qualifier;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ ElementType.FIELD, ElementType.PARAMETER })
+@Qualifier
+public @interface Browser2 {
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/default.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/default.html
new file mode 100644
index 000000000..01663a6ac
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/default.html
@@ -0,0 +1,41 @@
+<html>
+ <head>
+ <title>Page Default</title>
+ <script>
+ var XMLHttpArray = [
+ function() {return new XMLHttpRequest()},
+ function() {return new ActiveXObject("Msxml2.XMLHTTP")},
+ function() {return new ActiveXObject("Msxml2.XMLHTTP")},
+ function() {return new ActiveXObject("Microsoft.XMLHTTP")}
+ ];
+ function createXMLHTTPObject(){
+ var xmlhttp = false;
+ for(var i=0; i<XMLHttpArray.length; i++){
+ try{
+ xmlhttp = XMLHttpArray[i]();
+ }catch(e){
+ continue;
+ }
+ break;
+ }
+ return xmlhttp;
+ }
+ function MakeRequst(){
+ var xmlhttp = createXMLHTTPObject();
+ xmlhttp.onreadystatechange = function() {
+ if(this.readyState == 4) {
+ callback();
+ }
+ }
+ xmlhttp.open("get", "ourside.html", true);
+ xmlhttp.send();
+ return true;
+ }
+ </script>
+ </head>
+ <body>
+ <h1>Page Default</h1>
+ <a href="outside.html" id="http">HTTP request</a><br/>
+ <a href="#" id="xhr" onclick="MakeRequst()">XHR request</a>
+ </body>
+</html>
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/one.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/one.html
new file mode 100644
index 000000000..c4708b6b1
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/one.html
@@ -0,0 +1,41 @@
+<html>
+ <head>
+ <title>Page 1</title>
+ <script>
+ var XMLHttpArray = [
+ function() {return new XMLHttpRequest()},
+ function() {return new ActiveXObject("Msxml2.XMLHTTP")},
+ function() {return new ActiveXObject("Msxml2.XMLHTTP")},
+ function() {return new ActiveXObject("Microsoft.XMLHTTP")}
+ ];
+ function createXMLHTTPObject(){
+ var xmlhttp = false;
+ for(var i=0; i<XMLHttpArray.length; i++){
+ try{
+ xmlhttp = XMLHttpArray[i]();
+ }catch(e){
+ continue;
+ }
+ break;
+ }
+ return xmlhttp;
+ }
+ function MakeRequst(){
+ var xmlhttp = createXMLHTTPObject();
+ xmlhttp.onreadystatechange = function() {
+ if(this.readyState == 4) {
+ callback();
+ }
+ }
+ xmlhttp.open("get", "ourside.html", true);
+ xmlhttp.send();
+ return true;
+ }
+ </script>
+ </head>
+ <body>
+ <h1>Page 1</h1>
+ <a href="outside.html" id="http">HTTP request</a><br/>
+ <a href="#" id="xhr" onclick="MakeRequst()">XHR request</a>
+ </body>
+</html>
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/outside.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/outside.html
new file mode 100644
index 000000000..e69de29bb
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/two.html b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/two.html
new file mode 100644
index 000000000..e3ab0378f
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/org/jboss/arquillian/graphene/ftest/parallel/two.html
@@ -0,0 +1,41 @@
+<html>
+ <head>
+ <title>Page 2</title>
+ <script>
+ var XMLHttpArray = [
+ function() {return new XMLHttpRequest()},
+ function() {return new ActiveXObject("Msxml2.XMLHTTP")},
+ function() {return new ActiveXObject("Msxml2.XMLHTTP")},
+ function() {return new ActiveXObject("Microsoft.XMLHTTP")}
+ ];
+ function createXMLHTTPObject(){
+ var xmlhttp = false;
+ for(var i=0; i<XMLHttpArray.length; i++){
+ try{
+ xmlhttp = XMLHttpArray[i]();
+ }catch(e){
+ continue;
+ }
+ break;
+ }
+ return xmlhttp;
+ }
+ function MakeRequst(){
+ var xmlhttp = createXMLHTTPObject();
+ xmlhttp.onreadystatechange = function() {
+ if(this.readyState == 4) {
+ callback();
+ }
+ }
+ xmlhttp.open("get", "ourside.html", true);
+ xmlhttp.send();
+ return true;
+ }
+ </script>
+ </head>
+ <body>
+ <h1>Page 2</h1>
+ <a href="outside.html" id="http">HTTP request</a><br/>
+ <a href="#" id="xhr" onclick="MakeRequst()">XHR request</a>
+ </body>
+</html>
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/pom.xml b/graphene-webdriver/graphene-webdriver-impl/pom.xml
index 9e6b5872e..0e55e7cb2 100644
--- a/graphene-webdriver/graphene-webdriver-impl/pom.xml
+++ b/graphene-webdriver/graphene-webdriver-impl/pom.xml
@@ -37,6 +37,11 @@
<artifactId>selenium-support</artifactId>
<scope>provided</scope>
</dependency>
+ <!-- Arquillian Drone -->
+ <dependency>
+ <groupId>org.jboss.arquillian.extension</groupId>
+ <artifactId>arquillian-drone-impl</artifactId>
+ </dependency>
<!-- Runtime Dependencies -->
<dependency>
@@ -76,7 +81,7 @@
<groupId>org.jboss.arquillian.config</groupId>
<artifactId>arquillian-config-api</artifactId>
</dependency>
-
+
<dependency>
<groupId>org.jboss.arquillian.core</groupId>
<artifactId>arquillian-core-impl-base</artifactId>
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserActions.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserActions.java
new file mode 100644
index 000000000..a83647dc0
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserActions.java
@@ -0,0 +1,95 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Callable;
+
+/**
+ * This class provides a way to perform actions dependent on browser context.
+ *
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ * @see BrowserLocal
+ */
+public class BrowserActions {
+
+ Map<BrowserLocal, Object> browserLocals = new HashMap<BrowserLocal, Object>();
+
+ private final String name;
+
+ private static ThreadLocal<BrowserActions> currentBrowserActions = new ThreadLocal<BrowserActions>();
+ private static ThreadLocal<BrowserActions> lastBrowserActions = new ThreadLocal<BrowserActions>();
+
+ public BrowserActions(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Performs the given action in a context associated to this browser actions.
+ *
+ * @param <T> return type of the given action
+ * @param action action to be invoked in the context
+ * @return value returned by the given action
+ * @throws Exception
+ */
+ public <T> T performAction(Callable<T> action) throws Exception {
+ if (currentBrowserActions.get() != null && currentBrowserActions.get() != this) {
+ throw new IllegalStateException("There is an browser interleaving of " + currentBrowserActions().getName() + " and " + this.getName() + ".");
+ }
+ currentBrowserActions.set(this);
+ lastBrowserActions.set(this);
+ try {
+ return action.call();
+ } finally {
+ currentBrowserActions.set(null);
+ }
+ }
+
+ /**
+ * @return browser actions associated to the current browser context.
+ * @throws IllegalStateException if there is no active browser context available
+ */
+ public static BrowserActions currentBrowserActions() {
+ BrowserActions browserActions = currentBrowserActions.get();
+ if (browserActions == null) {
+ throw new IllegalStateException("There are no active browser actions available.");
+ }
+ return browserActions;
+ }
+
+ /**
+ * Get the browser actions associated to the last active browser context.
+ * @return the last active browser context of null, if it is not available
+ */
+ public static BrowserActions lastBrowserActions() {
+ return lastBrowserActions.get();
+ }
+
+ /**
+ * @return name of the browser context
+ */
+ public String getName() {
+ return name;
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserLocal.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserLocal.java
new file mode 100644
index 000000000..c065e1943
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/BrowserLocal.java
@@ -0,0 +1,136 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene;
+
+/**
+ * This class provides browser-local variables. These variables differ from
+ * their normal counterparts in that each browser context that accesses one (via its
+ * <tt>get</tt> or <tt>set</tt> method) has its own, independently initialized
+ * copy of the variable. <tt>BrowserLocal</tt> instances are typically private
+ * static fields in classes that wish to associate state with a browser context.
+ *
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ * @see ThreadLocal
+ * @see BrowserActions
+ */
+public class BrowserLocal<T> {
+
+ /**
+ * Returns the value in the current browser context's copy of this
+ * browser-local variable. If the variable has no value for the
+ * current browser context, it is first initialized to the value returned
+ * by an invocation of the {@link #initialValue} method.
+ *
+ * @return the current browser context's value of this browser-local
+ * @throws IllegalStateException if there is no active browser context
+ */
+ public T get() {
+ BrowserActions browser = BrowserActions.currentBrowserActions();
+ T result = (T) browser.browserLocals.get(this);
+ if (result == null) {
+ T init = initialValue();
+ if (init != null) {
+ browser.browserLocals.put(this, init);
+ return init;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Returns the value in the last browser context's copy of this
+ * browser-local variable. If the variable has no value for the
+ * last browser context, it is first initialized to the value returned
+ * by an invocation of the {@link #initialValue} method.
+ *
+ * <p>If the last browser context is not available, null is returned.
+ *
+ * @return the last browser context's value of this browser-local
+ */
+ public T getLast() {
+ BrowserActions browser = BrowserActions.lastBrowserActions();
+ if (browser == null) {
+ return null;
+ }
+ T result = (T) browser.browserLocals.get(this);
+ if (result == null) {
+ T init = initialValue();
+ if (init != null) {
+ browser.browserLocals.put(this, init);
+ return init;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Returns the current browser context's "initial value" for this
+ * browser-local variable. This method will be invoked the first
+ * time a browser context accesses the variable with the {@link #get}
+ * method, unless the browser context previously invoked the {@link #set}
+ * method, in which case the <tt>initialValue</tt> method will not
+ * be invoked for the browser context. Normally, this method is invoked at
+ * most once per browser context, but it may be invoked again in case of
+ * subsequent invocations of {@link #remove} followed by {@link #get}.
+ *
+ * <p>This implementation simply returns <tt>null</tt>; if the
+ * programmer desires browser-local variables to have an initial
+ * value other than <tt>null</tt>, <tt>BrowserLocal</tt> must be
+ * subclassed, and this method overridden. Typically, an
+ * anonymous inner class will be used.
+ *
+ * @return the initial value for this browser-local
+ */
+ protected T initialValue() {
+ return null;
+ }
+
+ /**
+ * Removes the current browser context's value for this browser-local
+ * variable. If this browser-local variable is subsequently
+ * {@linkplain #get read} by the current browser context, its value will be
+ * reinitialized by invoking its {@link #initialValue} method,
+ * unless its value is {@linkplain #set set} by the current browser context
+ * in the interim. This may result in multiple invocations of the
+ * <tt>initialValue</tt> method in the current browser context.
+ *
+ * @throws IllegalStateException if there is no active browser context
+ */
+ public void remove() {
+ BrowserActions.currentBrowserActions().browserLocals.remove(this);
+ }
+
+ /**
+ * Sets the current browser context's copy of this browser-local variable
+ * to the specified value. Most subclasses will have no need to
+ * override this method, relying solely on the {@link #initialValue}
+ * method to set the values of browser-locals.
+ *
+ * @param value the value to be stored in the current browser context's copy of
+ * this browser-local.
+ * @throws IllegalStateException if there is no active browser context
+ */
+ public void set(T value) {
+ BrowserActions.currentBrowserActions().browserLocals.put(this, value);
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/Graphene.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/Graphene.java
index 0c279dc70..3537c50c1 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/Graphene.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/Graphene.java
@@ -26,12 +26,14 @@
import org.jboss.arquillian.graphene.condition.attribute.ElementAttributeConditionFactory;
import org.jboss.arquillian.graphene.condition.element.WebElementConditionFactory;
import org.jboss.arquillian.graphene.condition.locator.ElementLocatorConditionFactory;
-import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.jboss.arquillian.graphene.enricher.PageFragmentEnricher;
+import org.jboss.arquillian.graphene.guard.RequestGuard;
import org.jboss.arquillian.graphene.guard.RequestGuardFactory;
+import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory;
import org.jboss.arquillian.graphene.page.RequestType;
+import org.jboss.arquillian.graphene.page.document.Document;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.jboss.arquillian.graphene.wait.WebDriverWait;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
@@ -120,7 +122,7 @@ public static ElementConditionFactory element(By locator) {
* @return the guarded object
*/
public static <T> T guardHttp(T target) {
- return RequestGuardFactory.guard(target, RequestType.HTTP, true);
+ return getRequestGuardFactoryFor(target).guard(target, RequestType.HTTP, true);
}
/**
@@ -133,7 +135,7 @@ public static <T> T guardHttp(T target) {
* @return the guarded object
*/
public static <T> T guardNoRequest(T target) {
- return RequestGuardFactory.guard(target, RequestType.NONE, true);
+ return getRequestGuardFactoryFor(target).guard(target, RequestType.NONE, true);
}
/**
@@ -149,7 +151,7 @@ public static <T> T guardNoRequest(T target) {
*/
@Deprecated
public static <T> T guardXhr(T target) {
- return RequestGuardFactory.guard(target, RequestType.XHR, true);
+ return guardAjax(target);
}
/**
@@ -162,43 +164,60 @@ public static <T> T guardXhr(T target) {
* @return the guarded object
*/
public static <T> T guardAjax(T target) {
- return RequestGuardFactory.guard(target, RequestType.XHR, true);
+ return getRequestGuardFactoryFor(target).guard(target, RequestType.XHR, true);
}
public static <T> T waitForHttp(T target) {
- return RequestGuardFactory.guard(target, RequestType.HTTP, false);
+ return getRequestGuardFactoryFor(target).guard(target, RequestType.HTTP, false);
}
public static WebDriverWait<Void> waitAjax() {
- return waitAjax(GrapheneContext.getProxy());
+ return waitAjax(context().getWebDriver());
}
public static WebDriverWait<Void> waitAjax(WebDriver driver) {
- return new WebDriverWait<Void>(null, driver, getConfiguration().getWaitAjaxInterval());
+ return new WebDriverWait<Void>(null, driver, ((GrapheneProxyInstance) driver).getContext().getConfiguration().getWaitAjaxInterval());
}
public static WebDriverWait<Void> waitGui() {
- return waitGui(GrapheneContext.getProxy());
+ return waitGui(context().getWebDriver());
}
public static WebDriverWait<Void> waitGui(WebDriver driver) {
- return new WebDriverWait<Void>(null, driver, getConfiguration().getWaitGuiInterval());
+ return new WebDriverWait<Void>(null, driver, ((GrapheneProxyInstance) driver).getContext().getConfiguration().getWaitGuiInterval());
}
public static WebDriverWait<Void> waitModel() {
- return waitModel(GrapheneContext.getProxy());
+ return waitModel(context().getWebDriver());
}
public static WebDriverWait<Void> waitModel(WebDriver driver) {
- return new WebDriverWait<Void>(null, driver, getConfiguration().getWaitModelInterval());
+ return new WebDriverWait<Void>(null, driver, ((GrapheneProxyInstance) driver).getContext().getConfiguration().getWaitModelInterval());
}
public static <T> T createPageFragment(Class<T> clazz, WebElement root) {
return PageFragmentEnricher.createPageFragment(clazz, root);
}
- private static GrapheneConfiguration getConfiguration() {
- return GrapheneConfigurationContext.getProxy();
+ private static RequestGuardFactory getRequestGuardFactoryFor(Object target) {
+ GrapheneContext context;
+ if (GrapheneProxy.isProxyInstance(target)) {
+ context = ((GrapheneProxyInstance) target).getContext();
+ } else {
+ context = context();
+ }
+ return new RequestGuardFactory(
+ JSInterfaceFactory.create(context, RequestGuard.class),
+ JSInterfaceFactory.create(context, Document.class),
+ context);
}
-}
+ private static GrapheneContext context() {
+ GrapheneContext context = GrapheneContext.lastContext();
+ if (context == null) {
+ throw new IllegalStateException("The last used Graphene context is not available.");
+ }
+ return context;
+ }
+
+}
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneContext.java
new file mode 100644
index 000000000..da2787e1f
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneContext.java
@@ -0,0 +1,307 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
+import org.jboss.arquillian.graphene.enricher.SearchContextInterceptor;
+import org.jboss.arquillian.graphene.enricher.StaleElementInterceptor;
+import org.jboss.arquillian.graphene.page.extension.PageExtensionInstallatorProvider;
+import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistry;
+import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistryImpl;
+import org.jboss.arquillian.graphene.page.extension.RemotePageExtensionInstallatorProvider;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyUtil;
+import org.openqa.selenium.JavascriptExecutor;
+import org.openqa.selenium.WebDriver;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+public class GrapheneContext {
+
+ private final GrapheneConfiguration configuration;
+ private final WebDriver webDriver;
+ private final Class<?> qualifier;
+ /**
+ * This field contains a reference to the context associated to the current
+ * active browser actions. {@link LazyContext} instance is placed here.
+ */
+ private static final BrowserLocal<GrapheneContext> CURRENT_CONTEXT = new BrowserLocal<GrapheneContext>();
+ /**
+ * This field contains a map qualifier => real contexts. Real context is
+ * an instance of {@link GrapheneContext} holding current {@link WebDriver},
+ * qualifier and {@link GrapheneConfiguration}. Contexts from this field are
+ * used by lazy contexts.
+ */
+ private static ThreadLocal<Map<Class<?>, GrapheneContext>> ALL_CONTEXTS = new ThreadLocal<Map<Class<?>, GrapheneContext>>() {
+ @Override
+ protected Map<Class<?>, GrapheneContext> initialValue() {
+ return new HashMap<Class<?>, GrapheneContext>();
+ }
+ };
+ /**
+ * This field contains a map qualifier => lazy context. Lazy context uses
+ * {@link #ALL_CONTEXTS} field for its method invocation and is able to create
+ * a proxy for {@link WebDriver}.
+ */
+ private static ThreadLocal<Map<Class<?>, LazyContext>> LAZY_CONTEXTS = new ThreadLocal<Map<Class<?>, LazyContext>>() {
+ @Override
+ protected Map<Class<?>, LazyContext> initialValue() {
+ return new HashMap<Class<?>, LazyContext>();
+ }
+ };
+
+ private GrapheneContext(GrapheneConfiguration configuration, WebDriver webDriver, Class<?> qualifier) {
+ this.configuration = configuration;
+ this.webDriver = webDriver;
+ this.qualifier = qualifier;
+ }
+
+ public BrowserActions getBrowserActions() {
+ return null;
+ }
+
+ public GrapheneConfiguration getConfiguration() {
+ return configuration;
+ }
+
+ public PageExtensionInstallatorProvider getPageExtensionInstallatorProvider() {
+ return null;
+ }
+
+ public PageExtensionRegistry getPageExtensionRegistry() {
+ return null;
+ }
+
+ /**
+ * If the {@link WebDriver} instance is not available yet, the returned
+ * proxy just implements {@link WebDriver} interface. If the {@link WebDriver}
+ * instance is available, its class is used to create a proxy, so the proxy extends it.
+ *
+ * @param interfaces interfaces which should be implemented by the returned {@link WebDriver}
+ * @return proxy for the {@link WebDriver} held in the context
+ */
+ public WebDriver getWebDriver(Class<?>... interfaces) {
+ return webDriver;
+ }
+
+ /**
+ * @return qualifier identifying the context.
+ */
+ public Class<?> getQualifier() {
+ return qualifier;
+ }
+
+ // static methods
+ static GrapheneContext lastContext() {
+ return CURRENT_CONTEXT.getLast();
+ }
+
+ /**
+ * Get context associated to the given qualifier. If the {@link Default}
+ * qualifier is given, the returned context tries to resolves the active context before
+ * each method invocation. If the active context is available, the returned context
+ * behaves like the active one.
+ */
+ public static GrapheneContext getContextFor(Class<?> qualifier) {
+ if (qualifier == null) {
+ throw new IllegalArgumentException("The parameter 'qualifer' is null.");
+ }
+ LazyContext context = (LazyContext) LAZY_CONTEXTS.get().get(qualifier);
+ if (context == null) {
+ try {
+ context = new LazyContext(qualifier, new BrowserActions(qualifier.getName()));
+ context.handler = GrapheneProxyHandler.forFuture(context, context.getFutureTarget());
+ GrapheneProxyInstance proxy = (GrapheneProxyInstance) context.getWebDriver();
+ proxy.registerInterceptor(new SearchContextInterceptor());
+ proxy.registerInterceptor(new StaleElementInterceptor());
+ context.installatorProvider = new RemotePageExtensionInstallatorProvider(context.registry, (JavascriptExecutor) context.getWebDriver(JavascriptExecutor.class));
+ final GrapheneContext finalContext = context;
+ context.getBrowserActions().performAction(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ CURRENT_CONTEXT.set(finalContext);
+ return null;
+ }
+ });
+ LAZY_CONTEXTS.get().put(qualifier, context);
+ } catch (Exception e) {
+ throw new IllegalStateException("Can't create a lazy context for " + qualifier.getName() + " qualifier.", e);
+ }
+ }
+ return context;
+ }
+
+ /**
+ * Creates a new context for the given webdriver, configuration and qualifier.
+ * <strong>When you create the context, you are responsible to invoke {@link #removeContextFor(java.lang.Class) }
+ * after the context is no longer valid.</strong>
+ *
+ * @return created context
+ * @see #getContextFor(java.lang.Class)
+ * @see #removeContextFor(java.lang.Class)
+ */
+ public static GrapheneContext setContextFor(GrapheneConfiguration configuration, WebDriver driver, Class<?> qualifier) {
+ GrapheneContext grapheneContext = new GrapheneContext(configuration, driver, qualifier);
+ ALL_CONTEXTS.get().put(qualifier, grapheneContext);
+ return getContextFor(qualifier);
+ }
+
+ /**
+ * Removes the context associated to the given qualifier.
+ * @param qualifier
+ * @see #setContextFor(org.jboss.arquillian.graphene.configuration.GrapheneConfiguration, org.openqa.selenium.WebDriver, java.lang.Class)
+ */
+ public static void removeContextFor(Class<?> qualifier) {
+ final GrapheneContext context = LAZY_CONTEXTS.get().get(qualifier);
+ if (context != null) {
+ try {
+ ((LazyContext) context).getBrowserActions().performAction(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ CURRENT_CONTEXT.remove();
+ return null;
+ }
+ });
+ } catch (Exception ignored) {
+ }
+ LAZY_CONTEXTS.get().remove(qualifier);
+ }
+ ALL_CONTEXTS.get().remove(qualifier);
+ }
+
+ private static class LazyContext extends GrapheneContext {
+
+ private final Class<?> qualifier;
+ private final PageExtensionRegistry registry;
+ private final BrowserActions browserActions;
+ private PageExtensionInstallatorProvider installatorProvider;
+ private GrapheneProxyHandler handler;
+
+ public LazyContext(Class<?> qualifier, BrowserActions browserActions) {
+ super(null, null, null);
+ this.qualifier = qualifier;
+ this.browserActions = browserActions;
+ this.registry = new PageExtensionRegistryImpl();
+ }
+
+ @Override
+ public BrowserActions getBrowserActions() {
+ LazyContext context = LAZY_CONTEXTS.get().get(getQualifier());
+ if (context == null) {
+ return browserActions;
+ } else {
+ return context.browserActions;
+ }
+ }
+
+ @Override
+ public GrapheneConfiguration getConfiguration() {
+ return getContext(true).getConfiguration();
+ }
+
+ @Override
+ public PageExtensionInstallatorProvider getPageExtensionInstallatorProvider() {
+ LazyContext context = LAZY_CONTEXTS.get().get(getQualifier());
+ if (context == null) {
+ return installatorProvider;
+ } else {
+ return context.installatorProvider;
+ }
+ }
+
+ @Override
+ public PageExtensionRegistry getPageExtensionRegistry() {
+ LazyContext context = LAZY_CONTEXTS.get().get(getQualifier());
+ if (context == null) {
+ return registry;
+ } else {
+ return context.registry;
+ }
+ }
+
+ @Override
+ public Class<?> getQualifier() {
+ if (Default.class.equals(qualifier)) {
+ GrapheneContext context = getContext(false);
+ if (context == null) {
+ return qualifier;
+ } if (context instanceof LazyContext) {
+ return ((LazyContext) context).qualifier;
+ } else {
+ return context.getQualifier();
+ }
+ } else {
+ return qualifier;
+ }
+ }
+
+ @Override
+ public WebDriver getWebDriver(Class<?>... interfaces) {
+ GrapheneContext context = getContext(false);
+ if (context == null) {
+ return GrapheneProxy.getProxyForHandler(handler, WebDriver.class, interfaces);
+ } else if (GrapheneProxyUtil.isProxy(context.getWebDriver())) {
+ Class<?> superclass = context.getWebDriver().getClass().getSuperclass();
+ if (superclass != null && !GrapheneProxyUtil.isProxy(superclass) && WebDriver.class.isAssignableFrom(superclass)) {
+ return GrapheneProxy.getProxyForHandler(handler, context.getWebDriver().getClass().getSuperclass(), interfaces);
+ } else {
+ return GrapheneProxy.getProxyForHandler(handler, WebDriver.class, interfaces);
+ }
+ } else {
+ return GrapheneProxy.getProxyForHandler(handler, context.getWebDriver().getClass(), interfaces);
+ }
+ }
+
+ protected GrapheneContext getContext(boolean exception) {
+ GrapheneContext context = null;
+ if (qualifier.equals(Default.class)) {
+ try {
+ context = CURRENT_CONTEXT.get();
+ } catch (Exception ignored) {
+ }
+ }
+ if (context == null || context.equals(this)) {
+ context = ALL_CONTEXTS.get().get(qualifier);
+ }
+ if (context == null && exception) {
+ throw new IllegalStateException("There is no context available for qualifier " + qualifier.getName() + ". Available contexts are " + ALL_CONTEXTS.get().keySet() + ".");
+ }
+ return context;
+ }
+
+ protected GrapheneProxy.FutureTarget getFutureTarget() {
+ return new GrapheneProxy.FutureTarget() {
+ @Override
+ public Object getTarget() {
+ return getContext(true).getWebDriver();
+ }
+ };
+ }
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneExtension.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneExtension.java
index fb3de9d5c..8d31ffdbc 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneExtension.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/GrapheneExtension.java
@@ -25,15 +25,16 @@
import org.jboss.arquillian.drone.spi.Enhancer;
import org.jboss.arquillian.graphene.configuration.GrapheneConfigurationResourceProvider;
import org.jboss.arquillian.graphene.configuration.GrapheneConfigurator;
+import org.jboss.arquillian.graphene.enricher.GrapheneContextProvider;
import org.jboss.arquillian.graphene.enricher.GrapheneEnricher;
import org.jboss.arquillian.graphene.enricher.JavaScriptEnricher;
import org.jboss.arquillian.graphene.enricher.PageFragmentEnricher;
import org.jboss.arquillian.graphene.enricher.PageObjectEnricher;
import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider;
+import org.jboss.arquillian.graphene.enricher.FieldAccessValidatorEnricher;
import org.jboss.arquillian.graphene.enricher.WebElementEnricher;
import org.jboss.arquillian.graphene.enricher.WebElementWrapperEnricher;
import org.jboss.arquillian.graphene.integration.GrapheneEnhancer;
-import org.jboss.arquillian.graphene.page.extension.GraphenePageExtensionRegistrar;
import org.jboss.arquillian.graphene.spi.enricher.SearchContextTestEnricher;
import org.jboss.arquillian.test.spi.TestEnricher;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
@@ -54,11 +55,11 @@ public void register(ExtensionBuilder builder) {
builder.service(SearchContextTestEnricher.class, PageFragmentEnricher.class);
builder.service(SearchContextTestEnricher.class, PageObjectEnricher.class);
builder.service(SearchContextTestEnricher.class, WebElementWrapperEnricher.class);
+ builder.service(SearchContextTestEnricher.class, FieldAccessValidatorEnricher.class);
/** Javascript enrichment */
- builder.service(TestEnricher.class, JavaScriptEnricher.class);
- /** Page Extensions */
- builder.observer(GraphenePageExtensionRegistrar.class);
+ builder.service(SearchContextTestEnricher.class, JavaScriptEnricher.class);
/* Resource Providers */
+ builder.service(ResourceProvider.class, GrapheneContextProvider.class);
builder.service(ResourceProvider.class, GrapheneConfigurationResourceProvider.class);
SeleniumResourceProvider.registerAllProviders(builder);
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java
index 6795a8ac5..2a60ac8af 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfiguration.java
@@ -44,8 +44,8 @@ public class GrapheneConfiguration implements DroneConfiguration<GrapheneConfigu
private String defaultElementLocatingStrategy = How.ID_OR_NAME.toString().toLowerCase();
- public String getDefaultElementLocatingStrategy() {
- return defaultElementLocatingStrategy;
+ public How getDefaultElementLocatingStrategy() {
+ return How.valueOf(defaultElementLocatingStrategy.toUpperCase());
}
public long getWaitAjaxInterval() {
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfigurator.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfigurator.java
index 0098e776e..7bf2652c8 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfigurator.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/configuration/GrapheneConfigurator.java
@@ -28,10 +28,9 @@
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.drone.api.annotation.Default;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
import org.jboss.arquillian.graphene.spi.configuration.GrapheneConfigured;
import org.jboss.arquillian.graphene.spi.configuration.GrapheneUnconfigured;
-import org.jboss.arquillian.test.spi.annotation.SuiteScoped;
+import org.jboss.arquillian.test.spi.annotation.ClassScoped;
import org.jboss.arquillian.test.spi.event.suite.AfterClass;
import org.jboss.arquillian.test.spi.event.suite.BeforeClass;
@@ -42,7 +41,7 @@
public class GrapheneConfigurator {
@Inject
- @SuiteScoped
+ @ClassScoped
private InstanceProducer<GrapheneConfiguration> configuration;
@Inject
@@ -57,12 +56,10 @@ public void configureGraphene(@Observes(precedence=100) BeforeClass event, Arqui
c.configure(descriptor, Default.class).validate();
this.configuration.set(c);
this.configuredEvent.fire(new GrapheneConfigured());
- GrapheneConfigurationContext.set(c);
}
// configuration has to be dropped after the drone factory destroy the webdriver
public void unconfigureGraphene(@Observes(precedence=-100) AfterClass event) {
- GrapheneConfigurationContext.reset();
unconfiguredEvent.fire(new GrapheneUnconfigured());
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneConfigurationContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneConfigurationContext.java
deleted file mode 100644
index 6102949e5..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneConfigurationContext.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, 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.arquillian.graphene.context;
-
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
-import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget;
-
-/**
- * <p>
- * Class for keeping thread local context of {@link GrapheneConfiguration}.
- * </p>
- *
- * <p>
- * Provides {@link #getProxy()} method for accessing that context in model of your tests.
- * </p>
- *
- * <p>
- * Proxy specifically handles the situations when no context is set - in this situation, runtime exception with
- * NullPointerException cause is thrown.
- * </p>
- *
- * @author <a href="mailto:[email protected]">Jan Papousek</a>
- */
-public class GrapheneConfigurationContext {
-
- private static final ThreadLocal<GrapheneConfiguration> REFERENCE = new ThreadLocal<GrapheneConfiguration>();
-
- /**
- * Returns the context of configuration for current thread
- *
- * @return the context of configuration for current thread
- * @throws NullPointerException when context is null
- */
- static GrapheneConfiguration get() {
- GrapheneConfiguration configuration = REFERENCE.get();
- if (configuration == null) {
- throw new NullPointerException("configuration is null - it needs to be setup before starting to use it");
- }
- return configuration;
- }
-
- /**
- * Returns the instance of proxy to thread local context of configuration
- *
- * @return the instance of proxy to thread local context of configuration
- */
- public static GrapheneConfiguration getProxy() {
- return GrapheneProxy.getProxyForFutureTarget(TARGET, GrapheneConfiguration.class);
- }
-
- /**
- * Returns true if the context is initialized
- *
- * @return true if the context is initialized
- */
- public static boolean isInitialized() {
- return REFERENCE.get() != null;
- }
-
- /**
- * Resets the WebDriver context for current thread
- */
- public static void reset() {
- REFERENCE.set(null);
- }
-
- /**
- * Sets the configuration context for current thread
- *
- * @param configuration the configuration instance
- * @throws IllegalArgumentException when provided configuration instance is null
- */
- public static void set(GrapheneConfiguration configuration) {
- if (configuration == null) {
- throw new IllegalArgumentException("configuration instance can't be null");
- }
- if (GrapheneProxy.isProxyInstance(configuration)) {
- throw new IllegalArgumentException("instance of the proxy can't be set to the configuration");
- }
- REFERENCE.set(configuration);
- }
-
- private static FutureTarget TARGET = new FutureTarget() {
- @Override
- public Object getTarget() {
- return get();
- }
- };
-
-}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneContext.java
deleted file mode 100644
index a57654a77..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GrapheneContext.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/**
- * 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.arquillian.graphene.context;
-
-import org.jboss.arquillian.graphene.enricher.SearchContextInterceptor;
-import org.jboss.arquillian.graphene.enricher.StaleElementInterceptor;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxyUtil;
-import org.openqa.selenium.HasInputDevices;
-import org.openqa.selenium.JavascriptExecutor;
-import org.openqa.selenium.WebDriver;
-
-/**
- * <p>
- * Class for keeping thread local context of {@link WebDriver}.
- * </p>
- *
- * <p>
- * Provides {@link #getProxy()} method for accessing that context in model of your tests.
- * </p>
- *
- * <p>
- * Proxy specifically handles the situations when no context is set - in this situation, runtime exception with
- * NullPointerException cause is thrown.
- * </p>
- *
- * @author Lukas Fryc
- */
-public final class GrapheneContext {
-
- /**
- * The thread local context of WebDriver
- */
- private static final ThreadLocal<WebDriver> REFERENCE = new ThreadLocal<WebDriver>();
-
- /**
- * The thread local context of {@link GrapheneProxyHandler}
- */
- private static final ThreadLocal<GrapheneProxyHandler> HANDLER = new ThreadLocal<GrapheneProxyHandler>() {
- protected GrapheneProxyHandler initialValue() {
- return GrapheneProxyHandler.forFuture(TARGET);
- };
- };
-
- private GrapheneContext() {
- }
-
- private static FutureTarget TARGET = new FutureTarget() {
- public Object getTarget() {
- return get();
- }
- };
-
- /**
- * Sets the WebDriver context for current thread
- *
- * @param driver the WebDriver instance
- * @throws IllegalArgumentException when provided WebDriver instance is null
- */
- public static void set(WebDriver driver) {
- if (driver == null) {
- throw new IllegalArgumentException("context instance can't be null");
- }
- if (GrapheneProxy.isProxyInstance(driver)) {
- throw new IllegalArgumentException("instance of the proxy can't be set to the context");
- }
-
- REFERENCE.set(driver);
- }
-
- /**
- * Resets the WebDriver context for current thread
- */
- public static void reset() {
- REFERENCE.set(null);
- HANDLER.get().resetInterceptors();
- }
-
- /**
- * Returns the context of WebDriver for current thread
- *
- * @return the context of WebDriver for current thread
- * @throws NullPointerException when context is null
- */
- static WebDriver get() {
- WebDriver driver = REFERENCE.get();
- if (driver == null) {
- throw new NullPointerException("context is null - it needs to be setup before starting to use it");
- }
- return driver;
- }
-
- /**
- * Returns true if the context is initialized
- *
- * @return true if the context is initialized
- */
- public static boolean isInitialized() {
- return REFERENCE.get() != null;
- }
-
- /**
- * Returns the instance of proxy to thread local context of WebDriver
- *
- * @return the instance of proxy to thread local context of WebDriver
- */
- public static WebDriver getProxy() {
- WebDriver webdriver = GrapheneProxy.getProxyForHandler(HANDLER.get(), null, WebDriver.class, JavascriptExecutor.class, HasInputDevices.class);
- GrapheneProxyInstance proxy = (GrapheneProxyInstance) webdriver;
- proxy.registerInterceptor(new SearchContextInterceptor());
- proxy.registerInterceptor(new StaleElementInterceptor());
- return webdriver;
- }
-
- /**
- * Returns the proxy for current thread local context of WebDriver which implements all interfaces as the current instance
- * in the context.
- *
- * @return the instance of proxy to thread local context of WebDriver
- */
- public static WebDriver getAugmentedProxy() {
- WebDriver currentDriver = REFERENCE.get();
- Class<?>[] interfaces = GrapheneProxyUtil.getInterfaces(currentDriver.getClass());
- WebDriver augmentedProxy = GrapheneContext.getProxyForInterfaces(interfaces);
- return augmentedProxy;
- }
-
- /**
- * Returns the instance of proxy to thread local context of WebDriver, the proxy handles the same interfaces which
- * implements provided class.
- *
- * @return the instance of proxy to thread local context of WebDriver
- */
- public static <T extends WebDriver> T getProxyForDriver(Class<T> webDriverImplClass, Class<?>... additionalInterfaces) {
- T webdriver = GrapheneProxy.<T>getProxyForHandler(HANDLER.get(), webDriverImplClass, additionalInterfaces);
- GrapheneProxyInstance proxy = (GrapheneProxyInstance) webdriver;
- proxy.registerInterceptor(new SearchContextInterceptor());
- proxy.registerInterceptor(new StaleElementInterceptor());
- return webdriver;
- }
-
- /**
- * Returns the instance of proxy to thread local context of WebDriver, the proxy handles all the interfaces provided as
- * parameter.
- *
- * @return the instance of proxy to thread local context of WebDriver
- */
-
- public static <T> T getProxyForInterfaces(Class<?>... interfaces) {
- Class<?>[] interfacesIncludingWebdriver = GrapheneProxyUtil.concatClasses(interfaces, WebDriver.class);
- T webdriver = GrapheneProxy.<T>getProxyForHandler(HANDLER.get(), null, interfacesIncludingWebdriver);
- GrapheneProxyInstance proxy = (GrapheneProxyInstance) webdriver;
- proxy.registerInterceptor(new SearchContextInterceptor());
- proxy.registerInterceptor(new StaleElementInterceptor());
- return webdriver;
- }
-
- /**
- * Returns true when the current context is the instance of provided class.
- *
- * @param clazz the class used to check current context
- * @return true when the current context is the instance of provided class; false otherwise.
- */
- public static boolean holdsInstanceOf(Class<?> clazz) {
- return clazz.isAssignableFrom(get().getClass());
- }
-}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GraphenePageExtensionsContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GraphenePageExtensionsContext.java
deleted file mode 100644
index e92abebdb..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/context/GraphenePageExtensionsContext.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, 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.arquillian.graphene.context;
-
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget;
-import org.jboss.arquillian.graphene.page.extension.PageExtensionInstallatorProvider;
-import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistry;
-
-/**
- * @author <a href="mailto:[email protected]">Jan Papousek</a>
- */
-public class GraphenePageExtensionsContext {
-
- private static final ThreadLocal<PageExtensionRegistry> REGISTRY_REFERENCE = new ThreadLocal<PageExtensionRegistry>();
- private static final ThreadLocal<PageExtensionInstallatorProvider> INSTALLATOR_PROVIDER_REFERENCE = new ThreadLocal<PageExtensionInstallatorProvider>();
-
- public static PageExtensionRegistry getRegistryProxy() {
- return GrapheneProxy.getProxyForFutureTarget(REGISTRY_TARGET, PageExtensionRegistry.class);
- }
-
- public static PageExtensionInstallatorProvider getInstallatorProviderProxy() {
- return GrapheneProxy.getProxyForFutureTarget(INSTALLATOR_PROVIDER_TARGET, PageExtensionInstallatorProvider.class);
- }
-
- /**
- * Returns true if the context is initialized
- *
- * @return true if the context is initialized
- */
- public static boolean isInitialized() {
- return REGISTRY_REFERENCE.get() != null && INSTALLATOR_PROVIDER_REFERENCE != null;
- }
-
- /**
- * Resets the WebDriver context for current thread
- */
- public static void reset() {
- REGISTRY_REFERENCE.set(null);
- INSTALLATOR_PROVIDER_REFERENCE.set(null);
- }
-
-
- public static void setInstallatorProvider(PageExtensionInstallatorProvider installatorProvider) {
- if (installatorProvider == null) {
- throw new IllegalArgumentException("context instance can't be null");
- }
- if (GrapheneProxy.isProxyInstance(installatorProvider)) {
- throw new IllegalArgumentException("instance of the proxy can't be set to the context");
- }
- INSTALLATOR_PROVIDER_REFERENCE.set(installatorProvider);
- }
-
- public static void setRegistry(PageExtensionRegistry registry) {
- if (registry == null) {
- throw new IllegalArgumentException("context instance can't be null");
- }
- if (GrapheneProxy.isProxyInstance(registry)) {
- throw new IllegalArgumentException("instance of the proxy can't be set to the context");
- }
- REGISTRY_REFERENCE.set(registry);
- }
-
- static PageExtensionInstallatorProvider getInstallatorProvider() {
- PageExtensionInstallatorProvider installatorProvider = INSTALLATOR_PROVIDER_REFERENCE.get();
- if (installatorProvider == null) {
- throw new NullPointerException("context is null - it needs to be setup before starting to use it");
- }
- return installatorProvider;
- }
-
- static PageExtensionRegistry getRegistry() {
- PageExtensionRegistry registry = REGISTRY_REFERENCE.get();
- if (registry == null) {
- throw new NullPointerException("context is null - it needs to be setup before starting to use it");
- }
- return registry;
- }
-
- private static FutureTarget INSTALLATOR_PROVIDER_TARGET = new FutureTarget() {
- @Override
- public Object getTarget() {
- return getInstallatorProvider();
- }
- };
-
- private static FutureTarget REGISTRY_TARGET = new FutureTarget() {
- @Override
- public Object getTarget() {
- return getRegistry();
- }
- };
-
-}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/AbstractSearchContextEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/AbstractSearchContextEnricher.java
index 720d3695d..5157e2fd3 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/AbstractSearchContextEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/AbstractSearchContextEnricher.java
@@ -1,23 +1,24 @@
/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, Red Hat, Inc. and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
+ * JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc. and
+ * individual contributors by the
*
- * 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.
+ * @authors tag. See the copyright.txt in the distribution for a full listing of
+ * individual contributors.
*
- * 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.
+ * 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.
*
- * 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.
+ * 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.arquillian.graphene.enricher;
@@ -28,13 +29,12 @@
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
-import java.util.Arrays;
-
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.spi.ServiceLoader;
import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException;
import org.jboss.arquillian.graphene.spi.enricher.SearchContextTestEnricher;
+import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.arquillian.test.spi.TestEnricher;
import org.openqa.selenium.SearchContext;
@@ -50,18 +50,18 @@ public abstract class AbstractSearchContextEnricher implements SearchContextTest
* Constant containing new line separator dependent on the environment.
*/
protected static final String NEW_LINE = System.getProperty("line.separator");
-
@Inject
private static Instance<ServiceLoader> serviceLoader;
/**
- * Performs further enrichment on the given instance with the given search context. That means all instances
- * {@link TestEnricher} and {@link SearchContextTestEnricher} are invoked.
+ * Performs further enrichment on the given instance with the given search
+ * context. That means all instances {@link TestEnricher} and
+ * {@link SearchContextTestEnricher} are invoked.
*
* @param searchContext
* @param target
*/
- protected static final void enrichRecursively(SearchContext searchContext, Object target) {
+ protected static void enrichRecursively(SearchContext searchContext, Object target) {
for (TestEnricher enricher : serviceLoader.get().all(TestEnricher.class)) {
if (!enricher.getClass().equals(GrapheneEnricher.class)) {
enricher.enrich(target);
@@ -73,9 +73,10 @@ protected static final void enrichRecursively(SearchContext searchContext, Objec
}
/**
- * It loads a real type of a field defined by parametric type. It searches in declaring class and super class. E. g. if a
- * field is declared as 'A fieldName', It tries to find type parameter called 'A' in super class declaration and its
- * evaluation in the class declaring the given field.
+ * It loads a real type of a field defined by parametric type. It searches
+ * in declaring class and super class. E. g. if a field is declared as 'A
+ * fieldName', It tries to find type parameter called 'A' in super class
+ * declaration and its evaluation in the class declaring the given field.
*
* @param field
* @param testCase
@@ -91,7 +92,7 @@ protected final Class<?> getActualType(Field field, Object testCase) {
// the type parameter has the same index as the actual type
String fieldParameterTypeName = field.getGenericType().toString();
- int index = Arrays.asList(superClassTypeParameters).indexOf(fieldParameterTypeName);
+ int index;
for (index = 0; index < superClassTypeParameters.length; index++) {
String superClassTypeParameterName = superClassTypeParameters[index].getName();
if (fieldParameterTypeName.equals(superClassTypeParameterName)) {
@@ -103,7 +104,8 @@ protected final Class<?> getActualType(Field field, Object testCase) {
}
/**
- * It loads the concrete type of list items. E.g. for List<String>, String is returned.
+ * It loads the concrete type of list items. E.g. for List<String>, String
+ * is returned.
*
* @param listField
* @return
@@ -124,8 +126,8 @@ protected final Class<?> getListType(Field listField) throws ClassNotFoundExcept
* @throws SecurityException
* @throws NoSuchMethodException
*/
- protected static final <T> T instantiate(Class<T> clazz, Object... args) throws NoSuchMethodException, SecurityException, InstantiationException,
- IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ protected static <T> T instantiate(Class<T> clazz, Object... args) throws NoSuchMethodException, SecurityException, InstantiationException,
+ IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> outerClass = clazz.getDeclaringClass();
// load constructor and rea; arguments
@@ -135,7 +137,7 @@ protected static final <T> T instantiate(Class<T> clazz, Object... args) throws
if (outerClass == null || Modifier.isStatic(clazz.getModifiers())) {
argTypes = new Class<?>[args.length];
realArgs = args;
- for (int i=0; i<args.length; i++) {
+ for (int i = 0; i < args.length; i++) {
argTypes[i] = args[i].getClass();
}
} else {
@@ -143,9 +145,9 @@ protected static final <T> T instantiate(Class<T> clazz, Object... args) throws
realArgs = new Object[args.length + 1];
argTypes[0] = outerClass;
realArgs[0] = instantiate(outerClass);
- for (int i=0; i<args.length; i++) {
- argTypes[i+1] = args[i].getClass();
- realArgs[i+1] = args[i];
+ for (int i = 0; i < args.length; i++) {
+ argTypes[i + 1] = args[i].getClass();
+ realArgs[i + 1] = args[i];
}
}
Constructor<T> construtor;
@@ -162,7 +164,7 @@ protected static final <T> T instantiate(Class<T> clazz, Object... args) throws
return construtor.newInstance(realArgs);
}
- protected static final void setValue(Field field, Object target, Object value) {
+ protected static void setValue(Field field, Object target, Object value) {
boolean accessible = field.isAccessible();
if (!accessible) {
@@ -172,7 +174,7 @@ protected static final void setValue(Field field, Object target, Object value) {
field.set(target, value);
} catch (Exception ex) {
throw new GrapheneTestEnricherException("During enriching of " + NEW_LINE + target.getClass() + NEW_LINE
- + " the field " + NEW_LINE + field + " was not able to be set! Check the cause!", ex);
+ + " the field " + NEW_LINE + field + " was not able to be set! Check the cause!", ex);
}
if (!accessible) {
field.setAccessible(false);
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java
new file mode 100644
index 000000000..772b3c35a
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java
@@ -0,0 +1,61 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.enricher;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.List;
+import java.util.logging.Logger;
+import org.jboss.arquillian.graphene.spi.enricher.SearchContextTestEnricher;
+import org.openqa.selenium.SearchContext;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+public class FieldAccessValidatorEnricher implements SearchContextTestEnricher {
+
+ private static final Logger LOGGER = Logger.getLogger(FieldAccessValidatorEnricher.class.getName());
+
+ @Override
+ public void enrich(SearchContext searchContext, Object target) {
+ List<Field> fields = ReflectionHelper.getFields(target.getClass());
+ for (Field field : fields) {
+ checkFieldValidity(searchContext, target, field);
+ }
+
+ }
+
+ protected void checkFieldValidity(final SearchContext searchContext, final Object target, final Field field) {
+ if (!Modifier.isStatic(field.getModifiers()) || !Modifier.isFinal(field.getModifiers())) {
+ // public field
+ if (searchContext != null && field.isAccessible() || Modifier.isPublic(field.getModifiers())) {
+ final String message = "Public field '" + field.getName() + "' found in " + target.getClass().getName() + ". Direct access to fields outside of the declaring class is not allowed.";
+ LOGGER.warning(message);
+ }
+ // package friendly field
+ if (searchContext != null && !field.getName().startsWith("this$") && !Modifier.isPrivate(field.getModifiers()) && !Modifier.isProtected(field.getModifiers())) {
+ final String message = "Package-friendly field '" + field.getName() + "' found in " + target.getClass().getName() + ". Direct access to fields outside of the declaring class is not allowed.";
+ LOGGER.warning(message);
+ }
+ }
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneContextProvider.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneContextProvider.java
new file mode 100644
index 000000000..5964c6939
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneContextProvider.java
@@ -0,0 +1,44 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.enricher;
+
+import java.lang.annotation.Annotation;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.test.api.ArquillianResource;
+import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
+
+/**
+ * @author <a href="mailto:[email protected]">Jan Papousek</a>
+ */
+public class GrapheneContextProvider implements ResourceProvider {
+
+ @Override
+ public boolean canProvide(Class<?> type) {
+ return type.equals(GrapheneContext.class);
+ }
+
+ @Override
+ public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
+ return GrapheneContext.getContextFor(ReflectionHelper.getQualifier(qualifiers));
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java
index d50293d28..80b0506ae 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java
@@ -26,9 +26,7 @@
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.spi.ServiceLoader;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.jboss.arquillian.test.spi.TestEnricher;
-import org.openqa.selenium.WebDriver;
/**
* Graphene enricher calls all {@link SearchContextTestEnricher} instances to start
@@ -44,9 +42,8 @@ public class GrapheneEnricher implements TestEnricher {
@Override
public void enrich(Object o) {
- final WebDriver driver = GrapheneContext.getProxy();
for (SearchContextTestEnricher enricher: serviceLoader.get().all(SearchContextTestEnricher.class)) {
- enricher.enrich(driver, o);
+ enricher.enrich(null, o);
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java
index e27c195ea..7585486c2 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java
@@ -1,61 +1,56 @@
/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, Red Hat, Inc. and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
+ * JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc. and
+ * individual contributors by the
*
- * 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.
+ * @authors tag. See the copyright.txt in the distribution for a full listing of
+ * individual contributors.
*
- * 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.
+ * 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.
*
- * 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.
+ * 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.arquillian.graphene.enricher;
import java.lang.reflect.Field;
-import java.lang.reflect.Method;
import java.util.Collection;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory;
import org.jboss.arquillian.graphene.javascript.JavaScript;
-import org.jboss.arquillian.test.spi.TestEnricher;
-import org.openqa.selenium.JavascriptExecutor;
-import org.openqa.selenium.WebDriver;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
+import org.openqa.selenium.SearchContext;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
*/
-public class JavaScriptEnricher implements TestEnricher {
+public class JavaScriptEnricher extends AbstractSearchContextEnricher {
@Override
- public void enrich(Object o) {
- Collection<Field> fields = ReflectionHelper.getFieldsWithAnnotation(o.getClass(), JavaScript.class);
- for (Field field: fields) {
+ public void enrich(final SearchContext searchContext, Object target) {
+ Collection<Field> fields = ReflectionHelper.getFieldsWithAnnotation(target.getClass(), JavaScript.class);
+ for (Field field : fields) {
+ GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext();
+ if (grapheneContext == null) {
+ grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations()));
+ }
if (!field.isAccessible()) {
field.setAccessible(true);
}
try {
- field.set(o, JSInterfaceFactory.create(
- (WebDriver) GrapheneContext.getProxyForInterfaces(JavascriptExecutor.class),
- field.getType()));
+ field.set(target, JSInterfaceFactory.create(grapheneContext, field.getType()));
} catch (Exception e) {
- throw new IllegalStateException("Can't inject value to the field '" + field.getName() + "' declared in class '" + field.getDeclaringClass().getName() +"'");
+ throw new IllegalStateException("Can't inject value to the field '" + field.getName() + "' declared in class '" + field.getDeclaringClass().getName() + "'");
}
}
}
-
- @Override
- public Object[] resolve(Method method) {
- return new Object[method.getParameterTypes().length];
- }
-
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
index b2bd344bf..778f78af9 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
@@ -1,23 +1,24 @@
/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, Red Hat, Inc. and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
+ * JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc. and
+ * individual contributors by the
*
- * 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.
+ * @authors tag. See the copyright.txt in the distribution for a full listing of
+ * individual contributors.
*
- * 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.
+ * 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.
*
- * 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.
+ * 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.arquillian.graphene.enricher;
@@ -25,14 +26,17 @@
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
-
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
-import org.jboss.arquillian.core.spi.ServiceLoader;
+
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import org.jboss.arquillian.graphene.enricher.exception.PageFragmentInitializationException;
import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities;
import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.jboss.arquillian.graphene.spi.annotations.Root;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
@@ -40,29 +44,45 @@
import org.openqa.selenium.support.FindBy;
/**
- * Enricher injecting page fragments ({@link FindBy} annotation is used) to the fields of the given object.
+ * Enricher injecting page fragments ({@link FindBy} annotation is used) to the
+ * fields of the given object.
*
* @author <a href="mailto:[email protected]">Juraj Huska</a>
* @author <a href="mailto:[email protected]">Jan Papousek</a>
*/
public class PageFragmentEnricher extends AbstractSearchContextEnricher {
- @SuppressWarnings("unused")
@Inject
- private Instance<ServiceLoader> serviceLoader;
+ private Instance<GrapheneConfiguration> configuration;
+
+ public PageFragmentEnricher() {
+ }
+
+ // because of testing
+ public PageFragmentEnricher(Instance<GrapheneConfiguration> configuration) {
+ this.configuration = configuration;
+ }
@Override
- public void enrich(SearchContext searchContext, Object target) {
+ public void enrich(final SearchContext searchContext, Object target) {
List<Field> fields = FindByUtilities.getListOfFieldsAnnotatedWithFindBys(target);
for (Field field : fields) {
+ GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext();
+ final SearchContext localSearchContext;
+ if (grapheneContext == null) {
+ grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations()));
+ localSearchContext = grapheneContext.getWebDriver(SearchContext.class);
+ } else {
+ localSearchContext = searchContext;
+ }
// Page fragment
if (isPageFragmentClass(field.getType())) {
- setupPageFragment(searchContext, target, field);
+ setupPageFragment(localSearchContext, target, field);
// List<Page fragment>
} else {
try {
if (field.getType().isAssignableFrom(List.class) && isPageFragmentClass(getListType(field))) {
- setupPageFragmentList(searchContext, target, field);
+ setupPageFragmentList(localSearchContext, target, field);
}
} catch (ClassNotFoundException e) {
throw new PageFragmentInitializationException(e.getMessage(), e);
@@ -90,7 +110,8 @@ protected final boolean isPageFragmentClass(Class<?> clazz) {
}
protected final <T> List<T> createPageFragmentList(final Class<T> clazz, final SearchContext searchContext, final By rootBy) {
- List<T> result = GrapheneProxy.getProxyForFutureTarget(new FutureTarget() {
+ GrapheneContext grapheneContext = ((GrapheneProxyInstance) searchContext).getContext();
+ List<T> result = GrapheneProxy.getProxyForFutureTarget(grapheneContext, new FutureTarget() {
@Override
public Object getTarget() {
List<WebElement> elements = searchContext.findElements(rootBy);
@@ -100,13 +121,13 @@ public Object getTarget() {
}
return fragments;
}
-
}, List.class);
return result;
}
- public static final <T> T createPageFragment(Class<T> clazz, WebElement root) {
+ public static <T> T createPageFragment(Class<T> clazz, WebElement root) {
try {
+ GrapheneContext grapheneContext = ((GrapheneProxyInstance) root).getContext();
T pageFragment = instantiate(clazz);
List<Field> roots = ReflectionHelper.getFieldsWithAnnotation(clazz, Root.class);
if (roots.size() > 1) {
@@ -118,7 +139,9 @@ public static final <T> T createPageFragment(Class<T> clazz, WebElement root) {
setValue(roots.get(0), pageFragment, root);
}
enrichRecursively(root, pageFragment);
- return pageFragment;
+ T proxy = GrapheneProxy.getProxyForHandler(GrapheneProxyHandler.forTarget(grapheneContext, pageFragment), clazz);
+ enrichRecursively(root, proxy); // because of possibility of direct access to attributes from test class
+ return proxy;
} catch (NoSuchMethodException ex) {
throw new PageFragmentInitializationException(" Check whether declared Page Fragment has no argument constructor!",
ex);
@@ -135,15 +158,17 @@ public static final <T> T createPageFragment(Class<T> clazz, WebElement root) {
protected final void setupPageFragmentList(SearchContext searchContext, Object target, Field field)
throws ClassNotFoundException {
+ GrapheneContext grapheneContext = ((GrapheneProxyInstance) searchContext).getContext();
//the by retrieved in this way is never null, by default it is ByIdOrName using field name
- By rootBy = FindByUtilities.getCorrectBy(field);
+ By rootBy = FindByUtilities.getCorrectBy(field, configuration.get().getDefaultElementLocatingStrategy());
List<?> pageFragments = createPageFragmentList(getListType(field), searchContext, rootBy);
setValue(field, target, pageFragments);
}
protected final void setupPageFragment(SearchContext searchContext, Object target, Field field) {
+ GrapheneContext grapheneContext = ((GrapheneProxyInstance) searchContext).getContext();
//the by retrieved in this way is never null, by default it is ByIdOrName using field name
- By rootBy = FindByUtilities.getCorrectBy(field);
+ By rootBy = FindByUtilities.getCorrectBy(field, configuration.get().getDefaultElementLocatingStrategy());
WebElement root = WebElementUtils.findElementLazily(rootBy, searchContext);
Object pageFragment = createPageFragment(field.getType(), root);
setValue(field, target, pageFragment);
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java
index a22cb3104..dc79b2048 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java
@@ -1,23 +1,24 @@
/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, Red Hat, Inc. and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
+ * JBoss, Home of Professional Open Source Copyright 2012, Red Hat, Inc. and
+ * individual contributors by the
*
- * 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.
+ * @authors tag. See the copyright.txt in the distribution for a full listing of
+ * individual contributors.
*
- * 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.
+ * 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.
*
- * 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.
+ * 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.arquillian.graphene.enricher;
@@ -25,10 +26,11 @@
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
-import org.jboss.arquillian.core.api.Instance;
-import org.jboss.arquillian.core.api.annotation.Inject;
-import org.jboss.arquillian.core.spi.ServiceLoader;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.enricher.exception.PageObjectInitializationException;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.jboss.arquillian.graphene.spi.annotations.Page;
import org.openqa.selenium.SearchContext;
@@ -40,15 +42,19 @@
*/
public class PageObjectEnricher extends AbstractSearchContextEnricher {
- @SuppressWarnings("unused")
- @Inject
- private Instance<ServiceLoader> serviceLoader;
-
@Override
- public void enrich(SearchContext searchContext, Object target) {
+ public void enrich(final SearchContext searchContext, Object target) {
String errorMsgBegin = "";
List<Field> fields = ReflectionHelper.getFieldsWithAnnotation(target.getClass(), Page.class);
for (Field field : fields) {
+ GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext();
+ final SearchContext localSearchContext;
+ if (grapheneContext == null) {
+ grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations()));
+ localSearchContext = grapheneContext.getWebDriver(SearchContext.class);
+ } else {
+ localSearchContext = searchContext;
+ }
try {
Type type = field.getGenericType();
Class<?> declaredClass;
@@ -62,11 +68,9 @@ public void enrich(SearchContext searchContext, Object target) {
}
errorMsgBegin = "Can not instantiate Page Object " + NEW_LINE + declaredClass + NEW_LINE
- + " declared in: " + NEW_LINE + target.getClass().getName() + NEW_LINE;
+ + " declared in: " + NEW_LINE + target.getClass().getName() + NEW_LINE;
- Object page = instantiate(declaredClass);
-
- enrichRecursively(searchContext, page);
+ Object page = setupPage(grapheneContext, localSearchContext, declaredClass);
setValue(field, target, page);
} catch (NoSuchMethodException ex) {
@@ -84,4 +88,12 @@ public void enrich(SearchContext searchContext, Object target) {
}
}
+
+ protected <P> P setupPage(GrapheneContext context, SearchContext searchContext, Class<?> pageClass) throws Exception{
+ P page = (P) instantiate(pageClass);
+ P proxy = GrapheneProxy.getProxyForHandler(GrapheneProxyHandler.forTarget(context, page), pageClass);
+ enrichRecursively(searchContext, page);
+ enrichRecursively(searchContext, proxy); // because of possibility of direct access to attributes from test class
+ return proxy;
+ }
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java
index 3e9e71565..60d3c3dcf 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java
@@ -27,6 +27,8 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.drone.api.annotation.Qualifier;
/**
* SecurityActions
@@ -179,6 +181,23 @@ public static boolean isClassPresent(String name) {
}
}
+ public static List<Field> getFields(final Class<?> source) {
+ return AccessController.doPrivileged(new PrivilegedAction<List<Field>>() {
+ @Override
+ public List<Field> run() {
+ List<Field> foundFields = new ArrayList<Field>();
+ Class<?> nextSource = source;
+ while (nextSource != Object.class) {
+ for (Field field : nextSource.getDeclaredFields()) {
+ foundFields.add(field);
+ }
+ nextSource = nextSource.getSuperclass();
+ }
+ return foundFields;
+ }
+ });
+ }
+
public static List<Field> getFieldsWithAnnotation(final Class<?> source, final Class<? extends Annotation> annotationClass) {
List<Field> declaredAccessableFields = AccessController.doPrivileged(new PrivilegedAction<List<Field>>() {
@Override
@@ -221,6 +240,31 @@ public List<Method> run() {
return declaredAccessableMethods;
}
+ // method from Drone, SecurityActions
+ public static Class<?> getQualifier(Annotation[] annotations) {
+
+ if (annotations == null) {
+ return Default.class;
+ }
+
+ List<Class<? extends Annotation>> candidates = new ArrayList<Class<? extends Annotation>>();
+
+ for (Annotation a : annotations) {
+ if (a.annotationType().isAnnotationPresent(Qualifier.class)) {
+ candidates.add(a.annotationType());
+ }
+ }
+
+ if (candidates.isEmpty()) {
+ return Default.class;
+ } else if (candidates.size() == 1) {
+ return candidates.get(0);
+ }
+
+ throw new IllegalStateException("Unable to determine Qualifier, multiple (" + candidates.size()
+ + ") Qualifier annotations were present");
+ }
+
// -------------------------------------------------------------------------------||
// Inner Classes ----------------------------------------------------------------||
// -------------------------------------------------------------------------------||
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SearchContextInterceptor.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SearchContextInterceptor.java
index 2ca80f1e4..e63a2c28d 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SearchContextInterceptor.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SearchContextInterceptor.java
@@ -22,10 +22,12 @@
package org.jboss.arquillian.graphene.enricher;
import java.lang.reflect.Method;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
import org.jboss.arquillian.graphene.proxy.Interceptor;
import org.jboss.arquillian.graphene.proxy.InvocationContext;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
+import org.openqa.selenium.WebDriver;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
@@ -33,11 +35,17 @@
public class SearchContextInterceptor implements Interceptor {
@Override
- public Object intercept(InvocationContext context) throws Throwable {
+ public Object intercept(final InvocationContext context) throws Throwable {
+ GrapheneProxy.FutureTarget future = new GrapheneProxy.FutureTarget() {
+ @Override
+ public Object getTarget() {
+ return context.getProxy();
+ }
+ };
if (methodsEqual(context.getMethod(), SearchContext.class.getDeclaredMethod("findElement", By.class))) {
- return WebElementUtils.findElement((By) context.getArguments()[0], context);
+ return WebElementUtils.findElement(context.getGrapheneContext(), (By) context.getArguments()[0], future);
} else if (methodsEqual(context.getMethod(), SearchContext.class.getDeclaredMethod("findElements", By.class))) {
- return WebElementUtils.findElementsLazily((By) context.getArguments()[0], context);
+ return WebElementUtils.findElementsLazily(context.getGrapheneContext(), (By) context.getArguments()[0], future);
} else {
return context.invoke();
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SeleniumResourceProvider.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SeleniumResourceProvider.java
index 3239802f5..a5587b2d4 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SeleniumResourceProvider.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/SeleniumResourceProvider.java
@@ -1,17 +1,12 @@
package org.jboss.arquillian.graphene.enricher;
import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.jboss.arquillian.core.spi.LoadableExtension.ExtensionBuilder;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
-import org.jboss.arquillian.graphene.proxy.Interceptor;
-import org.jboss.arquillian.graphene.proxy.InvocationContext;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
import org.openqa.selenium.Capabilities;
@@ -133,11 +128,12 @@ public boolean canProvide(Class<?> type) {
return type == this.returnType;
}
- protected <BASE> BASE base() {
- return GrapheneContext.getProxyForInterfaces(mediatorType);
+ protected <BASE> BASE base(Annotation[] annotations) {
+ WebDriver webdriver = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(annotations)).getWebDriver(mediatorType);
+ return (BASE) webdriver;
}
- protected Class<?> getTypeArgument(int i) {
+ protected final Class<?> getTypeArgument(int i) {
ParameterizedType superType = (ParameterizedType) getClass().getGenericSuperclass();
Type[] typeArguments = superType.getActualTypeArguments();
return (Class<?>) typeArguments[i];
@@ -152,7 +148,7 @@ private static class DirectProvider<T> extends SeleniumResourceProvider<T> {
@Override
public T lookup(ArquillianResource resource, Annotation... qualifiers) {
- return base();
+ return base(qualifiers);
}
}
@@ -170,38 +166,8 @@ public IndirectProvider() {
@Override
public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
- final M base = base();
-
- // this interceptor is created just to create future target of invocation
- Interceptor interceptor = new Interceptor() {
-
- @Override
- public Object intercept(final InvocationContext context) throws Throwable {
- final Method method = context.getMethod();
- if (method.getDeclaringClass() == mediatorType) {
- return GrapheneProxy.getProxyForFutureTarget(new FutureTarget() {
- public Object getTarget() {
- try {
- M unwrappedBase = ((GrapheneProxyInstance) base).unwrap();
- return method.invoke(unwrappedBase, context.getArguments());
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- }
- }, method.getReturnType());
- } else {
- throw new IllegalStateException("You cannot invoke method " + method + " on the " + mediatorType);
- }
- }
- };
-
- ((GrapheneProxyInstance) base).registerInterceptor(interceptor);
-
- Object futureTargetProxy = invoke(base);
-
- ((GrapheneProxyInstance) base).unregisterInterceptor(interceptor);
-
- return futureTargetProxy;
+ final M base = base(qualifiers);
+ return invoke(base);
}
public abstract T invoke(M mediator);
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/StaleElementInterceptor.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/StaleElementInterceptor.java
index 13b608f2e..61910f0cc 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/StaleElementInterceptor.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/StaleElementInterceptor.java
@@ -10,7 +10,6 @@
import org.openqa.selenium.WebDriver;
import com.google.common.base.Predicate;
-import java.util.concurrent.TimeUnit;
import org.openqa.selenium.TimeoutException;
public class StaleElementInterceptor implements Interceptor {
@@ -21,7 +20,7 @@ public Object intercept(final InvocationContext context) throws Throwable {
final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
final AtomicReference<Throwable> staleness = new AtomicReference<Throwable>();
try {
- waitGui().until(new Predicate<WebDriver>() {
+ waitGui(context.getGrapheneContext().getWebDriver()).until(new Predicate<WebDriver>() {
@Override
public boolean apply(WebDriver driver) {
try {
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
index 2413b4173..2e57ce5bb 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
@@ -23,8 +23,13 @@
import java.lang.reflect.Field;
import java.util.List;
+import org.jboss.arquillian.core.api.Instance;
+import org.jboss.arquillian.core.api.annotation.Inject;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
@@ -35,21 +40,40 @@
*/
public class WebElementEnricher extends AbstractSearchContextEnricher {
+ @Inject
+ private Instance<GrapheneConfiguration> configuration;
+
+ public WebElementEnricher() {
+ }
+
+ // because of testing
+ public WebElementEnricher(Instance<GrapheneConfiguration> configuration) {
+ this.configuration = configuration;
+ }
+
@Override
- public void enrich(SearchContext searchContext, Object target) {
+ public void enrich(final SearchContext searchContext, Object target) {
try {
List<Field> fields = FindByUtilities.getListOfFieldsAnnotatedWithFindBys(target);
for (Field field : fields) {
+ GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext();
+ final SearchContext localSearchContext;
+ if (grapheneContext == null) {
+ grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations()));
+ localSearchContext = grapheneContext.getWebDriver(SearchContext.class);
+ } else {
+ localSearchContext = searchContext;
+ }
//by should never by null, by default it is ByIdOrName using field name
- By by = FindByUtilities.getCorrectBy(field);
+ By by = FindByUtilities.getCorrectBy(field, configuration.get().getDefaultElementLocatingStrategy());
// WebElement
if (field.getType().isAssignableFrom(WebElement.class)) {
- WebElement element = WebElementUtils.findElementLazily(by, searchContext);
+ WebElement element = WebElementUtils.findElementLazily(by, localSearchContext);
setValue(field, target, element);
// List<WebElement>
} else if (field.getType().isAssignableFrom(List.class)
&& getListType(field).isAssignableFrom(WebElement.class)) {
- List<WebElement> elements = WebElementUtils.findElementsLazily(by, searchContext);
+ List<WebElement> elements = WebElementUtils.findElementsLazily(by, localSearchContext);
setValue(field, target, elements);
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java
index e84410296..5a0c71c87 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementUtils.java
@@ -25,6 +25,8 @@
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.enricher.findby.ByJQuery;
import org.jboss.arquillian.graphene.intercept.InterceptorBuilder;
import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
@@ -49,11 +51,11 @@ public final class WebElementUtils {
private WebElementUtils() {
}
- public static WebElement findElement(final By by, final GrapheneProxy.FutureTarget searchContextFuture) {
+ public static WebElement findElement(GrapheneContext context, final By by, final GrapheneProxy.FutureTarget searchContextFuture) {
// Here the web element has to be found to ensure that SearchContext throws
// NoSuchElementException if there is no element with the given By locator.
dropProxyAndFindElement(by, (SearchContext) searchContextFuture.getTarget());
- return findElement(new GrapheneProxy.FutureTarget() {
+ return findElement(context, new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
return dropProxyAndFindElement(by, (SearchContext) searchContextFuture.getTarget());
@@ -61,8 +63,8 @@ public Object getTarget() {
});
}
- public static List<WebElement> findElementsLazily(final By by, final GrapheneProxy.FutureTarget searchContextFuture) {
- return GrapheneProxy.getProxyForFutureTarget(new GrapheneProxy.FutureTarget() {
+ public static List<WebElement> findElementsLazily(final GrapheneContext context, final By by, final GrapheneProxy.FutureTarget searchContextFuture) {
+ return GrapheneProxy.getProxyForFutureTarget(context, new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
List<WebElement> result = new ArrayList<WebElement>();
@@ -71,15 +73,15 @@ public Object getTarget() {
LOGGER.log(Level.WARNING, EMPTY_FIND_BY_WARNING);
}
for (int i = 0; i < elements.size(); i++) {
- result.add(findElementLazily(by, searchContextFuture, i));
+ result.add(findElementLazily(context, by, searchContextFuture, i));
}
return result;
}
}, List.class);
}
- public static WebElement findElementLazily(final By by, final GrapheneProxy.FutureTarget searchContextFuture, final int indexInList) {
- return findElement(new GrapheneProxy.FutureTarget() {
+ public static WebElement findElementLazily(GrapheneContext context, final By by, final GrapheneProxy.FutureTarget searchContextFuture, final int indexInList) {
+ return findElement(context, new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
return dropProxyAndFindElements(by, (SearchContext) searchContextFuture.getTarget()).get(indexInList);
@@ -88,7 +90,7 @@ public Object getTarget() {
}
public static WebElement findElementLazily(final By by, final SearchContext searchContext, final int indexInList) {
- return findElement(new GrapheneProxy.FutureTarget() {
+ return findElement(getContext(searchContext), new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
return dropProxyAndFindElements(by, searchContext).get(indexInList);
@@ -97,7 +99,7 @@ public Object getTarget() {
}
public static WebElement findElementLazily(final By by, final SearchContext searchContext) {
- return findElement(new GrapheneProxy.FutureTarget() {
+ return findElement(getContext(searchContext), new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
try {
@@ -111,7 +113,7 @@ public Object getTarget() {
}
public static List<WebElement> findElementsLazily(final By by, final SearchContext searchContext) {
- return findElementsLazily(by, new GrapheneProxy.FutureTarget() {
+ return findElementsLazily(getContext(searchContext), by, new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
return searchContext;
@@ -119,8 +121,8 @@ public Object getTarget() {
});
}
- protected static WebElement findElement(final GrapheneProxy.FutureTarget target) {
- final WebElement element = GrapheneProxy.getProxyForFutureTarget(target, WebElement.class, Locatable.class,
+ protected static WebElement findElement(GrapheneContext context, final GrapheneProxy.FutureTarget target) {
+ final WebElement element = GrapheneProxy.getProxyForFutureTarget(context, target, WebElement.class, Locatable.class,
WrapsElement.class);
final GrapheneProxyInstance elementProxy = (GrapheneProxyInstance) element;
@@ -135,7 +137,12 @@ protected static WebElement findElement(final GrapheneProxy.FutureTarget target)
protected static WebElement dropProxyAndFindElement(By by, SearchContext searchContext) {
if (searchContext instanceof GrapheneProxyInstance) {
- return ((SearchContext) ((GrapheneProxyInstance) searchContext).unwrap()).findElement(by);
+ if (by instanceof ByJQuery) {
+ return by.findElement(searchContext);
+ } else {
+ SearchContext unwrapped = (SearchContext) ((GrapheneProxyInstance) searchContext).unwrap();
+ return unwrapped.findElement(by);
+ }
} else {
return searchContext.findElement(by);
}
@@ -143,10 +150,21 @@ protected static WebElement dropProxyAndFindElement(By by, SearchContext searchC
protected static List<WebElement> dropProxyAndFindElements(By by, SearchContext searchContext) {
if (searchContext instanceof GrapheneProxyInstance) {
- return ((SearchContext) ((GrapheneProxyInstance) searchContext).unwrap()).findElements(by);
+ if (by instanceof ByJQuery) {
+ return by.findElements(searchContext);
+ } else {
+ return ((SearchContext) ((GrapheneProxyInstance) searchContext).unwrap()).findElements(by);
+ }
} else {
return searchContext.findElements(by);
}
}
+ protected static GrapheneContext getContext(Object object) {
+ if (!GrapheneProxy.isProxyInstance(object)) {
+ throw new IllegalArgumentException("The parameter [object] has to be instance of " + GrapheneProxyInstance.class.getName() + ", but it is not. The given object is " + object + ".");
+ }
+ return ((GrapheneProxyInstance) object).getContext();
+ }
+
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java
index a5b81a982..490ab10b4 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java
@@ -7,9 +7,14 @@
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
+import org.jboss.arquillian.core.api.Instance;
+import org.jboss.arquillian.core.api.annotation.Inject;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException;
import org.jboss.arquillian.graphene.enricher.findby.FindByUtilities;
import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
@@ -19,21 +24,40 @@
*/
public class WebElementWrapperEnricher extends AbstractSearchContextEnricher {
+ @Inject
+ private Instance<GrapheneConfiguration> configuration;
+
+ public WebElementWrapperEnricher() {
+ }
+
+ // because of testing
+ public WebElementWrapperEnricher(Instance<GrapheneConfiguration> configuration) {
+ this.configuration = configuration;
+ }
+
@Override
public void enrich(final SearchContext searchContext, Object target) {
List<Field> fields = FindByUtilities.getListOfFieldsAnnotatedWithFindBys(target);
for (Field field: fields) {
final Field finalField = field;
if (isValidClass(field.getType())) {
- final By rootBy = FindByUtilities.getCorrectBy(field);
+ final SearchContext localSearchContext;
+ GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getContext();
+ if (grapheneContext == null) {
+ grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations()));
+ localSearchContext = grapheneContext.getWebDriver(SearchContext.class);
+ } else {
+ localSearchContext = searchContext;
+ }
+ final By rootBy = FindByUtilities.getCorrectBy(field, configuration.get().getDefaultElementLocatingStrategy());
try {
- Object component = GrapheneProxy.getProxyForFutureTarget(new GrapheneProxy.FutureTarget() {
+ Object component = GrapheneProxy.getProxyForFutureTarget(grapheneContext, new GrapheneProxy.FutureTarget() {
@Override
public Object getTarget() {
try {
- return instantiate(finalField.getType(), WebElementUtils.findElementLazily(rootBy, searchContext));
+ return instantiate(finalField.getType(), WebElementUtils.findElementLazily(rootBy, localSearchContext));
} catch (Exception e) {
- throw new IllegalStateException("Can't instantiate the " + finalField.getType());
+ throw new IllegalStateException("Can't instantiate the " + finalField.getType(), e);
}
}
}, field.getType());
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java
index 7d1daa217..36dd74999 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/Annotations.java
@@ -15,16 +15,16 @@
*/
/**
* <p>
- * Utility class originally copied from WebDriver. It main purpose is to retrieve correct
- * <code>By</code> instance according to the field on which <code>@FindBy</code> or <code>@FinfBys</code> annotation is.</p>
- *
+ * Utility class originally copied from WebDriver. It main purpose is to retrieve correct
+ * <code>By</code> instance according to the field on which <code>@FindBy</code> or <code>@FinfBys</code> annotation is.</p>
+ *
* <p>The differences are:
* <ul>
* <li>this class supports also Graphene <code>@FindBy</code> with JQuery locators support</li>
* <li>it is able to return default locating strategy according to the <code>GrapheneConfiguration</code></li>
* </ul>
* </p>
- *
+ *
* <p>Altered by <a href="mailto:[email protected]">Juraj Huska</a></p>.
*/
package org.jboss.arquillian.graphene.enricher.findby;
@@ -32,8 +32,6 @@
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
-
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ByIdOrName;
import org.openqa.selenium.support.CacheLookup;
@@ -43,10 +41,12 @@
public class Annotations {
- private Field field;
+ private final Field field;
+ private final org.jboss.arquillian.graphene.enricher.findby.How defaultElementLocatingStrategy;
- public Annotations(Field field) {
+ public Annotations(Field field, org.jboss.arquillian.graphene.enricher.findby.How defaultElementLocatingStrategy) {
this.field = field;
+ this.defaultElementLocatingStrategy = defaultElementLocatingStrategy;
}
public boolean isLookupCached() {
@@ -65,7 +65,7 @@ public By buildBy() {
ans = buildByFromGrapheneFindBys(grapheneFindBys);
}
- org.openqa.selenium.support.FindBys webDriverFindBys =
+ org.openqa.selenium.support.FindBys webDriverFindBys =
field.getAnnotation(org.openqa.selenium.support.FindBys.class);
if (ans == null && webDriverFindBys != null) {
ans = buildByFromWebDriverFindBys(webDriverFindBys);
@@ -117,11 +117,8 @@ private By checkAndProcessEmptyFindBy() {
}
protected By buildByFromDefault() {
- org.jboss.arquillian.graphene.enricher.findby.How how = org.jboss.arquillian.graphene.enricher.findby.How
- .valueOf(GrapheneConfigurationContext.getProxy().getDefaultElementLocatingStrategy().toUpperCase());
-
String using = field.getName();
- return getByFromGrapheneHow(how, using);
+ return getByFromGrapheneHow(defaultElementLocatingStrategy, using);
}
protected By buildByFromGrapheneFindBys(FindBys grapheneFindBys) {
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
index 621f4a0c6..4c7c9052d 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/ByJQuery.java
@@ -23,7 +23,9 @@
import java.util.List;
import org.jboss.arquillian.core.spi.Validate;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.SearchContext;
@@ -37,7 +39,6 @@
public class ByJQuery extends By {
private final String jquerySelector;
- private final JQuerySearchContext jQuerySearchContext = JSInterfaceFactory.create(JQuerySearchContext.class);
public ByJQuery(String jquerySelector) {
Validate.notNull(jquerySelector, "Cannot find elements when jquerySelector is null!");
@@ -55,6 +56,8 @@ public String toString() {
@Override
public List<WebElement> findElements(SearchContext context) {
+ GrapheneContext grapheneContext = ((GrapheneProxyInstance) context).getContext();
+ JQuerySearchContext jQuerySearchContext = JSInterfaceFactory.create(grapheneContext, JQuerySearchContext.class);
List<WebElement> elements;
try {
// the element is referenced from parent web element
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
index 96d3ab29c..0987610f3 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/enricher/findby/FindByUtilities.java
@@ -34,13 +34,13 @@
*/
public class FindByUtilities {
- public static By getCorrectBy(Field field) {
- Annotations annotations = new Annotations(field);
+ public static By getCorrectBy(Field field, How defaultElementLocatingStrategy) {
+ Annotations annotations = new Annotations(field, defaultElementLocatingStrategy);
By by = annotations.buildBy();
-
+
return by;
}
-
+
public static List<Field> getListOfFieldsAnnotatedWithFindBys(Object target) {
List<Field> fields = ReflectionHelper.getFieldsWithAnnotation(target.getClass(), FindBy.class);
fields.addAll(ReflectionHelper.getFieldsWithAnnotation(target.getClass(), org.jboss.arquillian.graphene.enricher.findby.FindBy.class));
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/guard/RequestGuardFactory.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/guard/RequestGuardFactory.java
index cb9b43866..34359a1fd 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/guard/RequestGuardFactory.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/guard/RequestGuardFactory.java
@@ -25,8 +25,6 @@
import java.util.concurrent.TimeUnit;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
-import org.jboss.arquillian.graphene.javascript.JSInterfaceFactory;
import org.jboss.arquillian.graphene.page.RequestState;
import org.jboss.arquillian.graphene.page.RequestType;
import org.jboss.arquillian.graphene.page.document.Document;
@@ -40,22 +38,30 @@
import com.google.common.base.Function;
import com.google.common.base.Predicate;
+import org.jboss.arquillian.graphene.GrapheneContext;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
*/
public class RequestGuardFactory {
- private static RequestGuard guard = JSInterfaceFactory.create(RequestGuard.class);
- private static Document document = JSInterfaceFactory.create(Document.class);
-
- private static DocumentReady documentReady = new DocumentReady();
- private static RequestIsDone requestIsDone = new RequestIsDone();
- private static RequestChange requestChange = new RequestChange();
-
- private static FluentWait<WebDriver, Void> waitGuard = waitAjax()
- .withTimeout(GrapheneConfigurationContext.getProxy().getWaitGuardInterval(), TimeUnit.SECONDS)
- .pollingEvery(Math.min(GrapheneConfigurationContext.getProxy().getWaitGuardInterval() * 100, 200), TimeUnit.MILLISECONDS);
+ private final RequestGuard guard;
+ private final Document document;
+ private final FluentWait<WebDriver, Void> waitGuard;
+ private final GrapheneContext context;
+ private final DocumentReady documentReady = new DocumentReady();
+ private final RequestIsDone requestIsDone = new RequestIsDone();
+ private final RequestChange requestChange = new RequestChange();
+
+
+ public RequestGuardFactory(RequestGuard guard, Document document, GrapheneContext context) {
+ this.guard = guard;
+ this.document = document;
+ this.context = context;
+ this.waitGuard = waitAjax()
+ .withTimeout(context.getConfiguration().getWaitGuardInterval(), TimeUnit.SECONDS)
+ .pollingEvery(Math.min(context.getConfiguration().getWaitGuardInterval() * 100, 200), TimeUnit.MILLISECONDS);
+ }
/**
* Returns the guarded object checking whether the request of the given type is done during each method invocation. If the
@@ -67,7 +73,7 @@ public class RequestGuardFactory {
* @param strict indicates that the expected request type can be interleaved by another type
* @return the guarded object
*/
- public static <T> T guard(T target, final RequestType requestExpected, final boolean strict) {
+ public <T> T guard(T target, final RequestType requestExpected, final boolean strict) {
if (requestExpected == null) {
throw new IllegalArgumentException("The paremeter [requestExpected] is null.");
}
@@ -78,7 +84,7 @@ public static <T> T guard(T target, final RequestType requestExpected, final boo
if (GrapheneProxy.isProxyInstance(target)) {
proxy = (GrapheneProxyInstance) ((GrapheneProxyInstance) target).copy();
} else {
- proxy = (GrapheneProxyInstance) GrapheneProxy.getProxyForTarget(target);
+ proxy = (GrapheneProxyInstance) GrapheneProxy.getProxyForTarget(context, target);
}
proxy.registerInterceptor(new Interceptor() {
@Override
@@ -140,27 +146,30 @@ private void waitForRequestFinished() {
return (T) proxy;
}
- private static class DocumentReady implements Predicate<WebDriver> {
+ private class DocumentReady implements Predicate<WebDriver> {
+ @Override
public boolean apply(WebDriver driver) {
return "complete".equals(document.getReadyState());
}
}
- private static class RequestIsDone implements Predicate<WebDriver> {
+ private class RequestIsDone implements Predicate<WebDriver> {
+ @Override
public boolean apply(WebDriver driver) {
RequestState state = guard.getRequestState();
return RequestState.DONE.equals(state);
}
}
- private static class RequestChange implements Function<WebDriver, RequestType> {
+ private class RequestChange implements Function<WebDriver, RequestType> {
+ @Override
public RequestType apply(WebDriver driver) {
RequestType type = guard.getRequestType();
return (RequestType.NONE.equals(type)) ? null : type;
}
}
- private static class RequestTypeDone implements Function<WebDriver, RequestType> {
+ private class RequestTypeDone implements Function<WebDriver, RequestType> {
private RequestType requestExpected;
@@ -168,6 +177,7 @@ public RequestTypeDone(RequestType requestExpected) {
this.requestExpected = requestExpected;
}
+ @Override
public RequestType apply(WebDriver driver) {
RequestType type = guard.getRequestType();
if (!requestExpected.equals(type)) {
@@ -176,4 +186,4 @@ public RequestType apply(WebDriver driver) {
return type;
}
}
-}
+}
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/GrapheneEnhancer.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/GrapheneEnhancer.java
index 9d24a0649..523c12bfc 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/GrapheneEnhancer.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/GrapheneEnhancer.java
@@ -1,11 +1,33 @@
+/**
+ * JBoss, Home of Professional Open Source
+ * Copyright 2012, 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.arquillian.graphene.integration;
import java.lang.annotation.Annotation;
-
+import org.jboss.arquillian.core.api.Instance;
+import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.drone.spi.Enhancer;
-import org.jboss.arquillian.drone.webdriver.spi.DroneAugmented;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.jboss.arquillian.graphene.proxy.GrapheneProxyUtil;
import org.openqa.selenium.WebDriver;
@@ -17,6 +39,9 @@
*/
public class GrapheneEnhancer implements Enhancer<WebDriver> {
+ @Inject
+ private Instance<GrapheneConfiguration> configuration;
+
@Override
public int getPrecedence() {
return -100;
@@ -31,34 +56,23 @@ public boolean canEnhance(Class<?> type, Class<? extends Annotation> qualifier)
* Wraps the {@link WebDriver} instance provided by {@link Drone} in a proxy and sets the driver into context
*/
@Override
- @SuppressWarnings("unchecked")
public WebDriver enhance(WebDriver driver, Class<? extends Annotation> qualifier) {
- GrapheneContext.set(driver);
-
- Class<? extends WebDriver> baseDriverClass = driver.getClass();
- if (driver instanceof DroneAugmented) {
- baseDriverClass = (Class<? extends WebDriver>)((DroneAugmented) driver).getWrapped().getClass();
- }
-
+ GrapheneContext grapheneContext = GrapheneContext.setContextFor(configuration.get(), driver, qualifier);
Class<?>[] interfaces = GrapheneProxyUtil.getInterfaces(driver.getClass());
-
- WebDriver proxy = GrapheneContext.getProxyForDriver(baseDriverClass, interfaces);
-
- return proxy;
+ return grapheneContext.getWebDriver(interfaces);
}
/**
* Unwraps the proxy
*/
@Override
- public WebDriver deenhance(WebDriver instance, Class<? extends Annotation> qualifier) {
- if (instance instanceof GrapheneProxyInstance) {
- instance = ((GrapheneProxyInstance) instance).unwrap();
+ public WebDriver deenhance(WebDriver enhancedDriver, Class<? extends Annotation> qualifier) {
+ if (enhancedDriver instanceof GrapheneProxyInstance) {
+ WebDriver driver = ((GrapheneProxyInstance) enhancedDriver).unwrap();
+ GrapheneContext.removeContextFor(qualifier);
+ return driver;
}
-
- GrapheneContext.reset();
-
- return instance;
+ return enhancedDriver;
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/intercept/InterceptorBuilder.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/intercept/InterceptorBuilder.java
index 9ca8ecfef..cc1799c9d 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/intercept/InterceptorBuilder.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/intercept/InterceptorBuilder.java
@@ -10,6 +10,7 @@
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.proxy.Interceptor;
import org.jboss.arquillian.graphene.proxy.InvocationContext;
@@ -91,6 +92,11 @@ public Object getTarget() {
return originalContext.getTarget();
}
+ @Override
+ public Object getProxy() {
+ return originalContext.getProxy();
+ }
+
@Override
public Method getMethod() {
return originalContext.getMethod();
@@ -100,6 +106,11 @@ public Method getMethod() {
public Object[] getArguments() {
return originalContext.getArguments();
}
+
+ @Override
+ public GrapheneContext getGrapheneContext() {
+ return originalContext.getGrapheneContext();
+ }
});
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/DefaultExecutionResolver.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/DefaultExecutionResolver.java
index a06505571..bdfbda10d 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/DefaultExecutionResolver.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/DefaultExecutionResolver.java
@@ -21,22 +21,19 @@
*/
package org.jboss.arquillian.graphene.javascript;
+import com.google.common.io.Resources;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Arrays;
+import java.util.logging.Level;
import java.util.logging.Logger;
-
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext;
+import org.jboss.arquillian.drone.api.annotation.Default;
import org.jboss.arquillian.graphene.page.extension.JavaScriptPageExtension;
+import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistry;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.openqa.selenium.JavascriptExecutor;
-import org.openqa.selenium.WebDriver;
-
-import com.google.common.io.Resources;
-import java.util.logging.Level;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
/**
* This resolver uses page extension mechanism to install needed JavaScript
@@ -61,29 +58,21 @@ public class DefaultExecutionResolver implements ExecutionResolver {
}
}
- private JavascriptExecutor browser = GrapheneContext.getProxyForInterfaces(JavascriptExecutor.class);
-
@Override
- public Object execute(WebDriver driver, JSCall call) {
- if (driver == null) {
- throw new IllegalArgumentException("Driver can't be null.");
- }
- if (!(driver instanceof JavascriptExecutor)) {
- throw new IllegalArgumentException("The executor can be used only for drivers implementing " + JavascriptExecutor.class.getName());
- }
+ public Object execute(GrapheneContext context, JSCall call) {
// check name
JSTarget target = call.getTarget();
if (target.getName() == null) {
throw new IllegalStateException("Can't use " + this.getClass() + " for " + target.getInterface() + ", because the @JavaScript annotation doesn't define non empty value()");
}
// register page extension
- registerExtension(target);
+ registerExtension(context.getPageExtensionRegistry(), target);
// try to execute javascript, if fails install the extension
- final long LIMIT = GrapheneConfigurationContext.getProxy().getJavascriptInstallationLimit();
+ final long LIMIT = context.getConfiguration().getJavascriptInstallationLimit();
for (long i=1; i<=5; i++) {
try {
// execute javascript
- Object returnValue = executeScriptForCall(call);
+ Object returnValue = executeScriptForCall((JavascriptExecutor) context.getWebDriver(JavascriptExecutor.class), call);
Object castedResult = castResult(call, returnValue);
return castedResult;
} catch (RuntimeException e) {
@@ -93,9 +82,8 @@ public Object execute(WebDriver driver, JSCall call) {
// try to install the extension
} else {
try {
- GraphenePageExtensionsContext.getInstallatorProviderProxy().installator(target.getName()).install();
- } catch (RuntimeException ex) {
- LOGGER.log(Level.WARNING, "Installation of page extension for " + call.getTarget().getInterface().getName() + " javascript interface failed.", ex);
+ context.getPageExtensionInstallatorProvider().installator(target.getName()).install();
+ } catch (RuntimeException ignored) {
}
}
}
@@ -140,10 +128,10 @@ protected Object castStringToEnum(Class<?> returnType, Object returnValue) {
}
}
- protected Object executeScriptForCall(JSCall call) {
+ protected Object executeScriptForCall(JavascriptExecutor executor, JSCall call) {
String script = resolveScriptToExecute(call);
Object[] arguments = castArguments(call.getArguments());
- Object returnValue = JavaScriptUtils.execute(browser, script, arguments);
+ Object returnValue = JavaScriptUtils.execute(executor, script, arguments);
if (returnValue instanceof String && ((String) returnValue).startsWith("GRAPHENE ERROR: ")) {
throw new IllegalStateException("exception thrown when executing method '" + call.getMethod().getName() + "': " + ((String) returnValue).substring(16));
}
@@ -156,17 +144,17 @@ protected String resolveScriptToExecute(JSCall call) {
return functionDefinitionWithCall;
}
- protected <T> void registerExtension(JSTarget target) {
+ protected <T> void registerExtension(PageExtensionRegistry registry, JSTarget target) {
if (target.getName() == null || target.getName().isEmpty()) {
throw new IllegalArgumentException("The extension " + target.getInterface() + "has no mapping.");
}
- if (GraphenePageExtensionsContext.getRegistryProxy().getExtension(target.getName()) != null) {
+ if (registry.getExtension(target.getName()) != null) {
return;
}
JavaScriptPageExtension extension = new JavaScriptPageExtension(target.getInterface());
- GraphenePageExtensionsContext.getRegistryProxy().register(extension);
+ registry.register(extension);
for (JSTarget dependency: target.getJSInterfaceDependencies()) {
- registerExtension(dependency);
+ registerExtension(registry, dependency);
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/ExecutionResolver.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/ExecutionResolver.java
index dddd0ed95..4f1aeb5de 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/ExecutionResolver.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/ExecutionResolver.java
@@ -1,9 +1,9 @@
package org.jboss.arquillian.graphene.javascript;
-import org.openqa.selenium.WebDriver;
+import org.jboss.arquillian.graphene.GrapheneContext;
public interface ExecutionResolver {
- Object execute(WebDriver driver, JSCall call);
+ Object execute(GrapheneContext context, JSCall call);
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceFactory.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceFactory.java
index 1e7906aea..c8369cd49 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceFactory.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceFactory.java
@@ -1,31 +1,21 @@
package org.jboss.arquillian.graphene.javascript;
import java.lang.reflect.Modifier;
-
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.openqa.selenium.JavascriptExecutor;
-import org.openqa.selenium.WebDriver;
+import org.jboss.arquillian.graphene.GrapheneContext;
public class JSInterfaceFactory<T> {
- private JSInterfaceHandler handler;
-
- private JSInterfaceFactory(WebDriver driver, Class<T> jsInterface) {
+ private final JSInterfaceHandler handler;
+ public JSInterfaceFactory(GrapheneContext context, Class<T> jsInterface) {
if (!jsInterface.isInterface() && !Modifier.isAbstract(jsInterface.getModifiers())) {
throw new IllegalArgumentException("interface or abstract class must be provided :" + jsInterface);
}
-
- this.handler = new JSInterfaceHandler(driver, new JSTarget(jsInterface));
-
- }
-
- public static <T> T create(Class<T> jsInterface) {
- return create((WebDriver) GrapheneContext.getProxyForInterfaces(JavascriptExecutor.class), jsInterface);
+ this.handler = new JSInterfaceHandler(new JSTarget(jsInterface), context);
}
- public static <T> T create(WebDriver driver, Class<T> jsInterface) {
- return new JSInterfaceFactory<T>(driver, jsInterface).instantiate();
+ public static <T> T create(GrapheneContext context, Class<T> jsInterface) {
+ return new JSInterfaceFactory<T>(context, jsInterface).instantiate();
}
@SuppressWarnings("unchecked")
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceHandler.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceHandler.java
index ecec25efd..f8a2bea4e 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceHandler.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/javascript/JSInterfaceHandler.java
@@ -2,19 +2,18 @@
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
-import org.openqa.selenium.WebDriver;
-
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
+import org.jboss.arquillian.graphene.GrapheneContext;
public class JSInterfaceHandler implements MethodInterceptor {
private final JSTarget target;
- private final WebDriver driver;
+ private final GrapheneContext context;
- public JSInterfaceHandler(WebDriver driver, JSTarget jsTarget) {
- this.target = jsTarget;
- this.driver = driver;
+ public JSInterfaceHandler(JSTarget target, GrapheneContext context) {
+ this.target = target;
+ this.context = context;
}
public JSTarget getTarget() {
@@ -28,8 +27,11 @@ public Object intercept(Object obj, Method method, Object[] args, MethodProxy me
return methodProxy.invokeSuper(obj, args);
}
}
+ if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) {
+ return null;
+ }
args = (args != null) ? args : new Object[]{};
JSCall call = new JSCall(new JSMethod(target, method), args);
- return target.getResolver().execute(driver, call);
+ return target.getResolver().execute(context, call);
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/GraphenePageExtensionRegistrar.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/GraphenePageExtensionRegistrar.java
deleted file mode 100644
index 79dd3d7db..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/GraphenePageExtensionRegistrar.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, 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.arquillian.graphene.page.extension;
-
-import java.util.Collection;
-
-import org.jboss.arquillian.core.api.Event;
-import org.jboss.arquillian.core.api.Instance;
-import org.jboss.arquillian.core.api.InstanceProducer;
-import org.jboss.arquillian.core.api.annotation.Inject;
-import org.jboss.arquillian.core.api.annotation.Observes;
-import org.jboss.arquillian.core.spi.ServiceLoader;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext;
-import org.jboss.arquillian.graphene.spi.page.PageExtensionProvider;
-import org.jboss.arquillian.graphene.spi.page.PageExtensionsCleaned;
-import org.jboss.arquillian.graphene.spi.page.PageExtensionsReady;
-import org.jboss.arquillian.test.spi.TestClass;
-import org.jboss.arquillian.test.spi.annotation.ClassScoped;
-import org.jboss.arquillian.test.spi.event.suite.AfterClass;
-import org.jboss.arquillian.test.spi.event.suite.BeforeClass;
-import org.openqa.selenium.JavascriptExecutor;
-
-/**
- * @author <a href="mailto:[email protected]">Jan Papousek</a>
- */
-public class GraphenePageExtensionRegistrar {
-
- @Inject
- @ClassScoped
- private InstanceProducer<PageExtensionRegistry> pageExtensionRegistry;
- @Inject
- @ClassScoped
- private InstanceProducer<PageExtensionInstallatorProvider> pageExtensionInstallatorProvider;
- @Inject
- private Instance<ServiceLoader> serviceLoader;
- @Inject
- private Event<PageExtensionsReady> pageExtensionsReady;
- @Inject
- private Event<PageExtensionsCleaned> pageExtensionsCleaned;
-
- public void registerPageExtensionRegistry(@Observes BeforeClass event, TestClass testClass) {
- pageExtensionRegistry.set(new PageExtensionRegistryImpl());
- loadPageExtensions(testClass);
- GraphenePageExtensionsContext.setRegistry(pageExtensionRegistry.get());
- pageExtensionInstallatorProvider.set(new RemotePageExtensionInstallatorProvider(pageExtensionRegistry.get(), GrapheneContext.<JavascriptExecutor>getProxyForInterfaces(JavascriptExecutor.class)));
- GraphenePageExtensionsContext.setInstallatorProvider(pageExtensionInstallatorProvider.get());
- pageExtensionsReady.fire(new PageExtensionsReady());
- }
-
- public void unregisterPageExtensionRegistry(@Observes AfterClass event) {
- pageExtensionRegistry.get().flush();
- GraphenePageExtensionsContext.reset();
- pageExtensionsCleaned.fire(new PageExtensionsCleaned());
- }
-
- protected void loadPageExtensions(TestClass testClass) {
- Collection<PageExtensionProvider> providers = serviceLoader.get().all(PageExtensionProvider.class);
- for (PageExtensionProvider provider: providers) {
- pageExtensionRegistry.get().register(provider.getPageExtensions(testClass));
- }
- }
-
-}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxy.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxy.java
index 728dd4f76..a98fa6710 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxy.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxy.java
@@ -24,6 +24,7 @@
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
+import org.jboss.arquillian.graphene.GrapheneContext;
import net.sf.cglib.proxy.Enhancer;
@@ -58,16 +59,16 @@ public static boolean isProxyInstance(Object target) {
* @return the proxy wrapping the target
*/
@SuppressWarnings("unchecked")
- public static <T> T getProxyForTarget(T target) {
+ public static <T> T getProxyForTarget(GrapheneContext context, T target) {
if (Modifier.isFinal(target.getClass().getModifiers())) {
if (target.getClass().getInterfaces().length > 0) {
- return GrapheneProxy.getProxyForTargetWithInterfaces(target, target.getClass().getInterfaces());
+ return GrapheneProxy.getProxyForTargetWithInterfaces(context, target, target.getClass().getInterfaces());
} else {
throw new IllegalStateException("Can't create a proxy for " + target.getClass()
+ ", it's final and id doesn't implement any interface.");
}
}
- GrapheneProxyHandler handler = GrapheneProxyHandler.forTarget(target);
+ GrapheneProxyHandler handler = GrapheneProxyHandler.forTarget(context, target);
return (T) createProxy(handler, target.getClass());
}
@@ -86,8 +87,8 @@ public static <T> T getProxyForTarget(T target) {
* @return the proxy wrapping the target
*/
@SuppressWarnings("unchecked")
- public static <T> T getProxyForTargetWithInterfaces(T target, Class<?>... interfaces) {
- GrapheneProxyHandler handler = GrapheneProxyHandler.forTarget(target);
+ public static <T> T getProxyForTargetWithInterfaces(GrapheneContext context, T target, Class<?>... interfaces) {
+ GrapheneProxyHandler handler = GrapheneProxyHandler.forTarget(context, target);
return (T) createProxy(handler, null, interfaces);
}
@@ -114,18 +115,16 @@ public static <T> T getProxyForTargetWithInterfaces(T target, Class<?>... interf
* @return the proxy wrapping the future target
*/
@Deprecated
- public static <T> T getProxyForFutureTarget(FutureTarget futureTarget, Class<?> baseType, Class<?>... additionalInterfaces) {
+ public static <T> T getProxyForFutureTarget(GrapheneContext context, FutureTarget futureTarget, Class<?> baseType, Class<?>... additionalInterfaces) {
if (baseType != null && !baseType.isInterface() && Modifier.isFinal(baseType.getModifiers())) {
if (additionalInterfaces.length > 0) {
- return GrapheneProxy.getProxyForFutureTarget(futureTarget, additionalInterfaces[0], additionalInterfaces);
+ return GrapheneProxy.getProxyForFutureTarget(context, futureTarget, additionalInterfaces[0], additionalInterfaces);
} else {
throw new IllegalStateException("Can't create a proxy for " + baseType
+ ", it's final and no additional interface has been given.");
}
}
-
- GrapheneProxyHandler handler = GrapheneProxyHandler.forFuture(futureTarget);
-
+ GrapheneProxyHandler handler = GrapheneProxyHandler.forFuture(context, futureTarget);
return getProxyForHandler(handler, baseType, additionalInterfaces);
}
@@ -176,4 +175,19 @@ public interface FutureTarget {
Object getTarget();
}
+
+ public static class ConstantFutureTarget implements FutureTarget {
+
+ private final Object target;
+
+ public ConstantFutureTarget(Object target) {
+ this.target = target;
+ }
+
+ @Override
+ public Object getTarget() {
+ return target;
+ }
+
+ }
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyHandler.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyHandler.java
index be0a2250a..3bdd4a959 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyHandler.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyHandler.java
@@ -26,9 +26,14 @@
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
+import org.jboss.arquillian.graphene.BrowserActions;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.jboss.arquillian.graphene.proxy.GrapheneProxy.FutureTarget;
@@ -48,9 +53,11 @@ public class GrapheneProxyHandler implements MethodInterceptor, InvocationHandle
private Object target;
private FutureTarget future;
+ private final GrapheneContext context;
private Map<Class<?>, Interceptor> interceptors = new HashMap<Class<?>, Interceptor>();
- private GrapheneProxyHandler() {
+ private GrapheneProxyHandler(GrapheneContext context) {
+ this.context = context;
}
/**
@@ -59,8 +66,8 @@ private GrapheneProxyHandler() {
* @param target the target of invocation
* @return invocation handler which wraps the given target instance
*/
- public static GrapheneProxyHandler forTarget(Object target) {
- GrapheneProxyHandler handler = new GrapheneProxyHandler();
+ public static GrapheneProxyHandler forTarget(GrapheneContext context, Object target) {
+ GrapheneProxyHandler handler = new GrapheneProxyHandler(context);
handler.target = target;
return handler;
}
@@ -71,8 +78,8 @@ public static GrapheneProxyHandler forTarget(Object target) {
* @param future the future target
* @return invocation handler which wraps the target for future computation
*/
- public static GrapheneProxyHandler forFuture(FutureTarget future) {
- GrapheneProxyHandler handler = new GrapheneProxyHandler();
+ public static GrapheneProxyHandler forFuture(GrapheneContext context, FutureTarget future) {
+ GrapheneProxyHandler handler = new GrapheneProxyHandler(context);
handler.future = future;
return handler;
}
@@ -93,6 +100,17 @@ public static GrapheneProxyHandler forFuture(FutureTarget future) {
*/
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
+ // handle finalizer
+ if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) {
+ if (!method.isAccessible()) {
+ method.setAccessible(true);
+ }
+ Object target = getTarget();
+ if (target instanceof GrapheneProxyInstance) {
+ return ((GrapheneProxyInstance) target).unwrap();
+ }
+ method.invoke(target);
+ }
// handle the GrapheneProxyInstance's method unwrap
if (method.equals(GrapheneProxyInstance.class.getMethod("unwrap"))) {
Object target = getTarget();
@@ -122,10 +140,10 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg
if (method.equals(GrapheneProxyInstance.class.getMethod("copy"))) {
GrapheneProxyInstance clone;
if (this.future != null) {
- clone = (GrapheneProxyInstance) GrapheneProxy.getProxyForFutureTarget(this.future, this.future.getTarget()
+ clone = (GrapheneProxyInstance) GrapheneProxy.getProxyForFutureTarget(context, this.future, this.future.getTarget()
.getClass(), this.future.getTarget().getClass().getInterfaces());
} else {
- clone = (GrapheneProxyInstance) GrapheneProxy.getProxyForTarget(this.target);
+ clone = (GrapheneProxyInstance) GrapheneProxy.getProxyForTarget(context, this.target);
}
for (Interceptor interceptor : interceptors.values()) {
clone.registerInterceptor(interceptor);
@@ -136,6 +154,10 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg
if (method.equals(GrapheneProxyInstance.class.getMethod("getHandler"))) {
return this;
}
+ // handle GrapheneProxyInstance's method getContext
+ if (method.equals(GrapheneProxyInstance.class.getMethod("getContext"))) {
+ return context;
+ }
InvocationContext invocationContext = new InvocationContext() {
@@ -147,7 +169,7 @@ public Object invoke() throws Throwable {
}
if (isProxyable(method, args) && !(result instanceof GrapheneProxyInstance)) {
Class<?>[] interfaces = GrapheneProxyUtil.getInterfaces(result.getClass());
- Object newProxy = GrapheneProxy.getProxyForTargetWithInterfaces(result, interfaces);
+ Object newProxy = GrapheneProxy.getProxyForTargetWithInterfaces(context, result, interfaces);
// List<Interceptor> inheritingInterceptors = ((GrapheneProxyInstance)proxy).getInheritingInterceptors();
@@ -171,11 +193,39 @@ public Object getTarget() {
return GrapheneProxyHandler.this.getTarget();
}
+ @Override
+ public Object getProxy() {
+ return proxy;
+ }
+
+ @Override
+ public GrapheneContext getGrapheneContext() {
+ return context;
+ }
+
};
for (Interceptor interceptor : interceptors.values()) {
invocationContext = new InvocationContextImpl(interceptor, invocationContext);
}
- return invocationContext.invoke();
+ final InvocationContext finalInvocationContext = invocationContext;
+ if (context != null) {
+ return context.getBrowserActions().performAction(new Callable<Object>() {
+ @Override
+ public Object call() throws Exception {
+ try {
+ return finalInvocationContext.invoke();
+ } catch (Throwable e) {
+ if (e instanceof Exception) {
+ throw (Exception) e;
+ } else {
+ throw new IllegalStateException("Can't invoke method " + method.getName() + ".", e);
+ }
+ }
+ }
+ });
+ } else {
+ return finalInvocationContext.invoke();
+ }
}
/**
@@ -183,7 +233,7 @@ public Object getTarget() {
*/
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
- return invoke(proxy, method, args);
+ return invoke(obj, method, args);
}
/**
@@ -220,7 +270,7 @@ Object invokeReal(Object target, Method method, Object[] args) throws Throwable
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception during invocation of "
+ method.getDeclaringClass().getName() + "#" + method.getName() + "(), on target '"
- + target.getClass().getName() + "': " + e.getMessage(), e);
+ + target + "': " + e.getMessage(), e);
}
return result;
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyInstance.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyInstance.java
index cfd6aefa6..470381d6c 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyInstance.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyInstance.java
@@ -21,6 +21,8 @@
*/
package org.jboss.arquillian.graphene.proxy;
+import org.jboss.arquillian.graphene.GrapheneContext;
+
/**
* <p>
@@ -40,4 +42,6 @@ public interface GrapheneProxyInstance {
<T> T copy();
<T> T unwrap();
+
+ GrapheneContext getContext();
}
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyUtil.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyUtil.java
index ece13c16f..919593844 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyUtil.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/GrapheneProxyUtil.java
@@ -21,6 +21,7 @@
*/
package org.jboss.arquillian.graphene.proxy;
+import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
@@ -100,4 +101,25 @@ public static Class<?>[] concatClasses(Class<?>[] classes, Class<?> clazz) {
out[length] = clazz;
return out;
}
+
+ public static boolean isProxy(Class<?> clazz) {
+ if (clazz.equals(Object.class)) {
+ return false;
+ }
+ if (net.sf.cglib.proxy.Proxy.isProxyClass(clazz) || Proxy.isProxyClass(clazz)) {
+ return true;
+ } else {
+ for (Class<?> interfaze: clazz.getInterfaces()) {
+ if (interfaze.getName().endsWith(".cglib.proxy.Factory")) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ public static boolean isProxy(Object target) {
+ return isProxy(target.getClass());
+
+ }
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContext.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContext.java
index 47bc28e26..15f97d57e 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContext.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContext.java
@@ -22,6 +22,7 @@
package org.jboss.arquillian.graphene.proxy;
import java.lang.reflect.Method;
+import org.jboss.arquillian.graphene.GrapheneContext;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
@@ -48,6 +49,11 @@ public interface InvocationContext extends GrapheneProxy.FutureTarget {
/**
* @return the target object of the method invocation
*/
+ @Override
Object getTarget();
+ Object getProxy();
+
+ GrapheneContext getGrapheneContext();
+
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContextImpl.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContextImpl.java
index 78534e1fb..f2be44ba2 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContextImpl.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/InvocationContextImpl.java
@@ -22,6 +22,7 @@
package org.jboss.arquillian.graphene.proxy;
import java.lang.reflect.Method;
+import org.jboss.arquillian.graphene.GrapheneContext;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
@@ -31,24 +32,34 @@ public class InvocationContextImpl implements InvocationContext {
private final InvocationContext following;
private final Interceptor interceptor;
private final Object target;
+ private final Object proxy;
private final Method method;
private final Object[] arguments;
+ private final GrapheneContext context;
- public InvocationContextImpl(Object target, Method method, Object[] arguments) {
+ public InvocationContextImpl(GrapheneContext context, Object target, Object proxy, Method method, Object[] arguments) {
if (target == null) {
throw new IllegalArgumentException("The parameter [target] is null.");
}
+ if (proxy == null) {
+ throw new IllegalArgumentException("The parameter [proxy] is null.");
+ }
if (method == null) {
throw new IllegalArgumentException("The parameter [method] is null.");
}
if (arguments == null) {
throw new IllegalArgumentException("The parameter [arguments] is null.");
}
+ if (context == null) {
+ throw new IllegalArgumentException("The parameter [context] is null.");
+ }
this.following = null;
this.interceptor = null;
this.arguments = arguments;
this.method = method;
this.target = target;
+ this.context = context;
+ this.proxy = proxy;
}
public InvocationContextImpl(Interceptor interceptor, InvocationContext following) {
@@ -63,6 +74,8 @@ public InvocationContextImpl(Interceptor interceptor, InvocationContext followin
this.arguments = null;
this.method = null;
this.target = null;
+ this.context = null;
+ this.proxy = null;
}
@Override
@@ -89,4 +102,14 @@ public Object getTarget() {
return target == null ? following.getTarget() : target;
}
+ @Override
+ public Object getProxy() {
+ return proxy == null ? following.getProxy() : proxy;
+ }
+
+ @Override
+ public GrapheneContext getGrapheneContext() {
+ return context == null ? following.getGrapheneContext() : context;
+ }
+
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriver.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriver.java
similarity index 97%
rename from graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriver.java
rename to graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriver.java
index e766996eb..e68242532 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriver.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriver.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.context;
+package org.jboss.arquillian.graphene;
import org.openqa.selenium.HasCapabilities;
import org.openqa.selenium.HasInputDevices;
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStub.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStub.java
similarity index 98%
rename from graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStub.java
rename to graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStub.java
index 6bf76ae9c..a77b3f59b 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStub.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStub.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.context;
+package org.jboss.arquillian.graphene;
import java.util.List;
import java.util.Set;
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStubExtension.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStubExtension.java
similarity index 95%
rename from graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStubExtension.java
rename to graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStubExtension.java
index 44e1eae3f..591967efc 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestingDriverStubExtension.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/TestingDriverStubExtension.java
@@ -19,7 +19,7 @@
* 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.arquillian.graphene.context;
+package org.jboss.arquillian.graphene;
/**
* @author Lukas Fryc
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java
index 1065ab1f0..19aecbf08 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java
@@ -32,7 +32,6 @@
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.config.descriptor.api.ExtensionDef;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
import org.jboss.arquillian.graphene.spi.configuration.GrapheneConfigured;
import org.jboss.arquillian.graphene.spi.configuration.GrapheneUnconfigured;
import org.jboss.arquillian.test.spi.annotation.SuiteScoped;
@@ -73,11 +72,12 @@ public void testConfigurationViaDescriptor() {
getManager().bind(SuiteScoped.class, ArquillianDescriptor.class, descriptor);
fire(new BeforeClass(Object.class));
assertEventFired(GrapheneConfigured.class);
- assertNotNull("Configuration instance has to be available.", GrapheneConfigurationContext.getProxy());
- GrapheneConfigurationContext.getProxy().validate();
- assertEquals("'waitGuiInterval' should be 5", 5, GrapheneConfigurationContext.getProxy().getWaitGuiInterval());
- assertEquals("'waitAjaxInterval' should be 25", 25, GrapheneConfigurationContext.getProxy().getWaitAjaxInterval());
- assertEquals("'waitModelInterval' should be 125", 125, GrapheneConfigurationContext.getProxy().getWaitModelInterval());
+ GrapheneConfiguration configuration = getManager().resolve(GrapheneConfiguration.class);
+ assertNotNull("Configuration instance has to be available.", configuration);
+ configuration.validate();
+ assertEquals("'waitGuiInterval' should be 5", 5, configuration.getWaitGuiInterval());
+ assertEquals("'waitAjaxInterval' should be 25", 25, configuration.getWaitAjaxInterval());
+ assertEquals("'waitModelInterval' should be 125", 125, configuration.getWaitModelInterval());
fire(new AfterClass(Object.class));
assertEventFired(GrapheneUnconfigured.class);
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextHolding.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextHolding.java
deleted file mode 100644
index c948c3f3e..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextHolding.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, 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.arquillian.graphene.context;
-
-import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Collection;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.openqa.selenium.TakesScreenshot;
-import org.openqa.selenium.WebDriver;
-
-/**
- * @author Lukas Fryc
- */
-public class TestGrapheneContextHolding {
-
- @Mock
- WebDriver driver;
-
- @Mock(extraInterfaces = GrapheneProxyInstance.class)
- WebDriver driverProxy;
-
- @Before
- public void initMocks() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void when_instance_is_provided_to_context_then_context_holds_it() {
- // having
- // when
- GrapheneContext.set(driver);
-
- // then
- assertSame(driver, GrapheneContext.get());
- }
-
- @Test
- public void when_instance_is_provided_to_context_then_context_is_initialized() {
- // having
- // when
- GrapheneContext.set(driver);
-
- // then
- assertTrue(GrapheneContext.isInitialized());
- }
-
- @Test
- public void when_context_is_reset_then_context_is_not_initialized() {
- // having
- GrapheneContext.set(driver);
-
- // when
- GrapheneContext.reset();
-
- // then
- assertFalse(GrapheneContext.isInitialized());
- }
-
- @Test(expected = NullPointerException.class)
- public void when_calling_get_on_not_initialized_context_then_context_throws_exception() {
- GrapheneContext.reset();
- GrapheneContext.get();
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void when_set_null_instance_to_context_then_context_throws_exception() {
- GrapheneContext.set(null);
- }
-
- @Test
- public void context_should_determine_that_holds_instance_of_some_interface() {
- GrapheneContext.set(new TestingDriverStub());
- assertTrue(GrapheneContext.holdsInstanceOf(TakesScreenshot.class));
- }
-
- @Test
- public void context_should_fail_when_checked_for_being_instance_of_non_implemented_class() {
- GrapheneContext.set(new TestingDriverStub());
- assertFalse(GrapheneContext.holdsInstanceOf(Collection.class));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void when_set_proxy_instance_to_context_then_context_throws_exception() {
- GrapheneContext.set(driverProxy);
- }
-}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextProxying.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextProxying.java
deleted file mode 100644
index 9e23028b1..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextProxying.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, 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.arquillian.graphene.context;
-
-import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.only;
-import static org.mockito.Mockito.atLeastOnce;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.openqa.selenium.By;
-import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebDriver.Navigation;
-import org.openqa.selenium.WebElement;
-
-/**
- * @author Lukas Fryc
- */
-@RunWith(MockitoJUnitRunner.class)
-public class TestGrapheneContextProxying {
-
- private static final String SAMPLE_STRING = "sample";
-
- @Mock
- WebDriver driver;
-
- @Test
- public void context_provides_proxy_which_delegates_to_current_context() {
- // having
- WebDriver driver = new DriverReturningSampleString();
-
- // when
- GrapheneContext.set(driver);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
-
- // then
- WebDriver proxy = GrapheneContext.getProxy();
- assertEquals(SAMPLE_STRING, proxy.toString());
- }
-
- @Test
- public void when_proxy_returns_webdriver_api_then_another_proxy_is_returned_wrapping_the_result_of_invocation() {
- // having
- Navigation navigation = mock(Navigation.class);
-
- // when
- GrapheneContext.set(driver);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- when(driver.navigate()).thenReturn(navigation);
-
- // then
- WebDriver driverProxy = GrapheneContext.getProxy();
- Navigation navigationProxy = driverProxy.navigate();
- assertTrue(navigationProxy instanceof GrapheneProxyInstance);
-
- // verify
- verify(driver, only()).navigate();
- }
-
- @Test
- public void when_proxy_returns_result_of_invocation_with_arguments_then_returned_object_is_proxied() {
- // having
- WebElement webElement = mock(WebElement.class);
- By byId = By.id("id");
-
- // when
- GrapheneContext.set(driver);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- when(driver.findElement(byId)).thenReturn(webElement);
-
- // then
- WebDriver driverProxy = GrapheneContext.getProxy();
- WebElement webElementProxy = driverProxy.findElement(byId);
- webElementProxy.clear();
- assertTrue(webElementProxy instanceof GrapheneProxyInstance);
-
- // verify
- verify(driver, atLeastOnce()).findElement(byId);
- }
-
- @Test
- public void when_proxy_returns_result_of_invocation_with_arguments_then_returned_object_can_be_invoked() {
- // having
- WebElement webElement = mock(WebElement.class);
- By byId = By.id("id");
-
- // when
- GrapheneContext.set(driver);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- when(driver.findElement(byId)).thenReturn(webElement);
-
- // then
- WebDriver driverProxy = GrapheneContext.getProxy();
- WebElement webElementProxy = driverProxy.findElement(byId);
- webElementProxy.clear();
-
- // verify
- verify(webElement, only()).clear();
- }
-
- @Test
-
- public void test_that_context_can_be_unwrapped() {
- // having
- GrapheneContext.set(driver);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- WebDriver driverProxy = GrapheneContext.getProxy();
-
- // when
- WebDriver unwrapped = ((GrapheneProxyInstance) driverProxy).unwrap();
-
- // then
- assertSame(driver, unwrapped);
- }
-
- private static class DriverReturningSampleString extends TestingDriverStub {
- @Override
- public String toString() {
- return SAMPLE_STRING;
- }
- }
-}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextTheadLocality.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextTheadLocality.java
deleted file mode 100644
index 7e4853163..000000000
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/context/TestGrapheneContextTheadLocality.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * JBoss, Home of Professional Open Source
- * Copyright 2012, 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.arquillian.graphene.context;
-
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.junit.Test;
-import org.openqa.selenium.WebDriver;
-
-/**
- * @author Lukas Fryc
- */
-public class TestGrapheneContextTheadLocality {
-
- @Test
- public void context_holds_one_instance_per_thread() {
- final CountDownLatch secondInstanceSet = new CountDownLatch(1);
- final CountDownLatch firstInstanceVerified = new CountDownLatch(1);
- final WebDriver driver1 = mock(WebDriver.class);
- final WebDriver driver2 = mock(WebDriver.class);
-
- new Thread(new Runnable() {
- public void run() {
- GrapheneContext.set(driver1);
- await(secondInstanceSet);
- assertSame(driver1, GrapheneContext.get());
- firstInstanceVerified.countDown();
- }
- }).start();
-
- new Thread(new Runnable() {
- public void run() {
- GrapheneContext.set(driver2);
- secondInstanceSet.countDown();
- assertSame(driver2, GrapheneContext.get());
- }
- }).start();
- await(firstInstanceVerified);
- }
-
- private void await(CountDownLatch condition) {
- try {
- condition.await();
- } catch (InterruptedException e) {
- fail("thread has been interrupted");
- }
- }
-}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractGrapheneEnricherTest.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractGrapheneEnricherTest.java
index 5725af5b7..7a3b57876 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractGrapheneEnricherTest.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/AbstractGrapheneEnricherTest.java
@@ -27,9 +27,12 @@
import java.util.Arrays;
import org.jboss.arquillian.core.api.Instance;
+import org.jboss.arquillian.core.impl.InstanceImpl;
import org.jboss.arquillian.core.spi.ServiceLoader;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.TestingDriver;
import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
import org.jboss.arquillian.graphene.spi.enricher.SearchContextTestEnricher;
import org.jboss.arquillian.test.spi.TestEnricher;
import org.junit.Before;
@@ -49,6 +52,9 @@ public abstract class AbstractGrapheneEnricherTest {
@Mock
private Instance<ServiceLoader> serviceLoaderInstance;
+ @Mock
+ protected TestingDriver browser;
+
@Mock
private ServiceLoader serviceLoader;
@@ -63,9 +69,16 @@ public abstract class AbstractGrapheneEnricherTest {
@Before
public void prepareServiceLoader() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
grapheneEnricher = new GrapheneEnricher();
- webElementEnricher = new WebElementEnricher();
+ Instance<GrapheneConfiguration> configuration = new Instance() {
+ @Override
+ public Object get() {
+ return new GrapheneConfiguration();
+ }
+
+ };
+ webElementEnricher = new WebElementEnricher(configuration);
pageObjectEnricher = new PageObjectEnricher();
- pageFragmentEnricher = new PageFragmentEnricher();
+ pageFragmentEnricher = new PageFragmentEnricher(configuration);
when(serviceLoaderInstance.get()).thenReturn(serviceLoader);
when(serviceLoader.all(TestEnricher.class)).thenReturn(Arrays.asList(grapheneEnricher));
when(serviceLoader.all(SearchContextTestEnricher.class)).thenReturn(Arrays.asList(webElementEnricher, pageObjectEnricher, pageFragmentEnricher));
@@ -82,7 +95,7 @@ public void prepareServiceLoader() throws NoSuchFieldException, IllegalArgumentE
serviceLoaderField.set(o, serviceLoaderInstance);
}
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
+ GrapheneContext.setContextFor(new GrapheneConfiguration(), browser, Default.class);
}
protected final TestEnricher getGrapheneEnricher() {
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestSeleniumResourceProvider.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestSeleniumResourceProvider.java
index 6e3faa53d..31f8a1da1 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestSeleniumResourceProvider.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestSeleniumResourceProvider.java
@@ -1,17 +1,22 @@
package org.jboss.arquillian.graphene.enricher;
+import java.util.Arrays;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider.ActionsProvider;
import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider.KeyboardProvider;
import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider.MouseProvider;
import org.jboss.arquillian.graphene.enricher.SeleniumResourceProvider.WebDriverProvider;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -21,9 +26,11 @@
import org.openqa.selenium.HasInputDevices;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keyboard;
+import org.openqa.selenium.Keys;
import org.openqa.selenium.Mouse;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
+import org.openqa.selenium.interactions.internal.Coordinates;
/**
* @author Lukas Fryc
@@ -36,12 +43,65 @@ public class TestSeleniumResourceProvider {
@Before
public void setUp() {
- GrapheneContext.set(driver);
+ when(((HasInputDevices) driver).getKeyboard()).thenReturn(new Keyboard() {
+ @Override
+ public void sendKeys(CharSequence... keysToSend) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void pressKey(Keys keyToPress) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void releaseKey(Keys keyToRelease) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+ });
+ when(((HasInputDevices) driver).getMouse()).thenReturn(new Mouse() {
+
+ @Override
+ public void click(Coordinates where) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void doubleClick(Coordinates where) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void mouseDown(Coordinates where) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void mouseUp(Coordinates where) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void mouseMove(Coordinates where) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void mouseMove(Coordinates where, long xOffset, long yOffset) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void contextClick(Coordinates where) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+ });
+ GrapheneContext.setContextFor(new GrapheneConfiguration(), driver, Default.class);
}
@After
public void tearDown() {
- GrapheneContext.reset();
+ GrapheneContext.removeContextFor(Default.class);
}
@Test
@@ -79,7 +139,9 @@ public void testIndirectProviderLookup() {
// when
Object object = provider.lookup(null, null);
// then
+ assertNotNull(object);
assertTrue(object instanceof Keyboard);
+ assertTrue(object instanceof GrapheneProxyInstance);
}
@Test
@@ -89,7 +151,9 @@ public void testMouseProviderLookup() {
// when
Object object = provider.lookup(null, null);
// then
+ assertNotNull(object);
assertTrue(object instanceof Mouse);
+ assertTrue(object instanceof GrapheneProxyInstance);
}
@Test
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java
index 43f08645c..9ca56910b 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementEnricher.java
@@ -21,12 +21,13 @@
*/
package org.jboss.arquillian.graphene.enricher;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -55,10 +56,10 @@ public void generated_webelement_implements_WrapsElement_interface() {
assertTrue(page.element instanceof WrapsElement);
- GrapheneContext.set(driver);
+ GrapheneContext.setContextFor(new GrapheneConfiguration(), driver, Default.class);
when(driver.findElement(Mockito.any(By.class))).thenReturn(element);
WebElement wrappedElement = ((WrapsElement) page.element).getWrappedElement();
- GrapheneContext.reset();
+ GrapheneContext.removeContextFor(Default.class);
assertEquals(element, wrappedElement);
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementLazyEvaluation.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementLazyEvaluation.java
index dc17a08fb..12b1a4a8d 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementLazyEvaluation.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementLazyEvaluation.java
@@ -8,7 +8,6 @@
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
@@ -19,63 +18,65 @@ public class TestWebElementLazyEvaluation extends AbstractGrapheneEnricherTest {
@Test
public void when_WebElement_is_injected_then_it_is_first_evaluated_at_first_interaction() {
- WebDriver driver = mock(WebDriver.class);
WebElement element = mock(WebElement.class);
- when(driver.findElement(any(By.class))).thenReturn(element);
-
- GrapheneContext.set(driver);
+ when(browser.findElement(any(By.class))).thenReturn(element);
TPageFragment fragment = new TPageFragment();
getGrapheneEnricher().enrich(fragment);
- verifyZeroInteractions(driver, element);
+ verifyZeroInteractions(browser, element);
- fragment.element.click();
- fragment.element.click();
+ fragment.getElement().click();
+ fragment.getElement().click();
// the search for element should be done for every invocation
- verify(driver, times(2)).findElement(any(By.class));
+ verify(browser, times(2)).findElement(any(By.class));
verify(element, times(2)).click();
- verifyNoMoreInteractions(driver, element);
+ verifyNoMoreInteractions(browser, element);
}
@Test
public void when_page_fragment_is_injected_then_searching_for_its_siblings_is_done_for_each_invocation() {
- WebDriver driver = mock(WebDriver.class);
WebElement rootElement = mock(WebElement.class);
WebElement element = mock(WebElement.class);
- when(driver.findElement(any(By.class))).thenReturn(rootElement);
+ when(browser.findElement(any(By.class))).thenReturn(rootElement);
when(rootElement.findElement(any(By.class))).thenReturn(element);
- GrapheneContext.set(driver);
-
TPage page = new TPage();
getGrapheneEnricher().enrich(page);
- verifyZeroInteractions(driver, element);
+ verifyZeroInteractions(browser, element);
- page.fragment.element.click();
- page.fragment.element.click();
- page.fragment.element.click();
+ page.getFragment().getElement().click();
+ page.getFragment().getElement().click();
+ page.getFragment().getElement().click();
// the search for element should be done for every invocation
- verify(driver, times(3)).findElement(any(By.class));
+ verify(browser, times(3)).findElement(any(By.class));
verify(rootElement, times(3)).findElement(any(By.class));
verify(element, times(3)).click();
- verifyNoMoreInteractions(driver, element);
+ verifyNoMoreInteractions(browser, element);
}
- private static class TPage {
+ public static class TPage {
@FindBy(id = "test")
TPageFragment fragment;
+
+ public TPageFragment getFragment() {
+ return fragment;
+ }
}
- private static class TPageFragment {
+ public static class TPageFragment {
@FindBy(id = "test")
WebElement element;
+
+ public WebElement getElement() {
+ return element;
+ }
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementStaleness.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementStaleness.java
index ff12f9cf9..a2db9d7a1 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementStaleness.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/TestWebElementStaleness.java
@@ -10,7 +10,6 @@
import java.util.HashMap;
import java.util.Map;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -20,7 +19,6 @@
import org.mockito.stubbing.Answer;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
-import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
@@ -29,7 +27,6 @@ public class TestWebElementStaleness extends AbstractGrapheneEnricherTest {
private Map<WebElement, Boolean> staleness = new HashMap<WebElement, Boolean>();
- private WebDriver driver;
private WebElement rootElement;
private WebElement webElement;
@@ -37,13 +34,10 @@ public class TestWebElementStaleness extends AbstractGrapheneEnricherTest {
@Before
public void prepare() {
- driver = mock(WebDriver.class);
- GrapheneContext.set(driver);
-
rootElement = mock(WebElement.class, new StaleElementAnswer());
webElement = mock(WebElement.class, new StaleElementAnswer());
- when(driver.findElement(any(By.class))).thenReturn(rootElement);
+ when(browser.findElement(any(By.class))).thenReturn(rootElement);
when(rootElement.findElement(any(By.class))).thenReturn(webElement);
page = new Page();
@@ -54,14 +48,14 @@ public void prepare() {
public void test_fragment_subelement_is_stale() {
// when
makeStale(webElement);
- page.fragment.element.click();
+ page.getFragment().getElement().click();
// then
- verify(driver, times(2)).findElement(any(By.class));
+ verify(browser, times(2)).findElement(any(By.class));
verify(rootElement, times(2)).findElement(any(By.class));
verify(webElement, times(2)).click();
- verifyNoMoreInteractions(driver, webElement);
+ verifyNoMoreInteractions(browser, webElement);
}
@Test
@@ -69,14 +63,14 @@ public void test_page_where_page_fragment_reference_is_stale() {
// when
makeStale(rootElement);
makeStale(webElement);
- page.fragment.element.click();
+ page.getFragment().getElement().click();
// then
- verify(driver, times(2)).findElement(any(By.class));
+ verify(browser, times(2)).findElement(any(By.class));
verify(rootElement, times(2)).findElement(any(By.class));
verify(webElement, times(2)).click();
- verifyNoMoreInteractions(driver, webElement);
+ verifyNoMoreInteractions(browser, webElement);
}
private boolean isStale(WebElement element) {
@@ -95,16 +89,24 @@ private void makeStale(WebElement element) {
private static class Page {
@FindBy(id = "test")
- PageFragment fragment;
+ private PageFragment fragment;
+
+ public PageFragment getFragment() {
+ return fragment;
+ }
}
- private static class PageFragment {
+ public static class PageFragment {
@FindBy(id = "test")
- WebElement element;
+ private WebElement element;
+
+ public WebElement getElement() {
+ return element;
+ }
}
- private class StaleElementAnswer implements Answer<Object> {
+ public class StaleElementAnswer implements Answer<Object> {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/WrongPageFragmentTooManyRoots.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/WrongPageFragmentTooManyRoots.java
index 2428e8cf4..e4a7b0a21 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/WrongPageFragmentTooManyRoots.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/enricher/fragment/WrongPageFragmentTooManyRoots.java
@@ -33,12 +33,15 @@ public class WrongPageFragmentTooManyRoots {
@SuppressWarnings("unused")
@Root
private WebElement root1;
-
+
@SuppressWarnings("unused")
@Root
private WebElement root2;
-
+
@SuppressWarnings("unused")
@FindBy(className="randomClassName")
private WebElement foo;
+
+ public void doSomething() {
+ }
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java
index 9f6fd17d0..2dc096e8d 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java
@@ -12,10 +12,11 @@ public class TestIntercepting {
public void testInterceptorCalling() {
// having
MyObject target = new MyObject();
- MyObject proxy = GrapheneProxy.getProxyForTarget(target);
+ MyObject proxy = GrapheneProxy.getProxyForTarget(null, target);
// when
((GrapheneProxyInstance) proxy).registerInterceptor(new Interceptor() {
+ @Override
public Object intercept(InvocationContext context) throws Throwable {
return context.invoke();
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestInterceptorBuilder.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestInterceptorBuilder.java
index c4a538224..d7d531012 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestInterceptorBuilder.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestInterceptorBuilder.java
@@ -1,5 +1,8 @@
package org.jboss.arquillian.graphene.intercept;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -35,6 +38,8 @@ public class TestInterceptorBuilder {
@Mock
By by;
+ GrapheneContext context;
+
@Before
public void before() throws Throwable {
Answer invoke = new Answer<Object>() {
@@ -46,6 +51,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable {
when(interceptor1.intercept(Mockito.any(InvocationContext.class))).thenAnswer(invoke);
when(interceptor2.intercept(Mockito.any(InvocationContext.class))).thenAnswer(invoke);
+ context = GrapheneContext.setContextFor(new GrapheneConfiguration(), driver, Default.class);
}
@Test
@@ -55,7 +61,7 @@ public void test() throws Throwable {
builder.interceptInvocation(WebDriver.class, interceptor2).findElement(Interceptors.any(By.class));
Interceptor builtInterceptor = builder.build();
- WebDriver driverProxy = GrapheneProxy.getProxyForTargetWithInterfaces(driver, WebDriver.class);
+ WebDriver driverProxy = GrapheneProxy.getProxyForTargetWithInterfaces(context, driver, WebDriver.class);
GrapheneProxyInstance proxy = (GrapheneProxyInstance) driverProxy;
proxy.registerInterceptor(builtInterceptor);
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestExecution.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestExecution.java
index 4af4a5588..99f6393da 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestExecution.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestExecution.java
@@ -1,12 +1,9 @@
package org.jboss.arquillian.graphene.javascript;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.TestingDriverStub;
import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext;
-import org.jboss.arquillian.graphene.context.TestingDriverStub;
-import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistryImpl;
-import org.jboss.arquillian.graphene.page.extension.RemotePageExtensionInstallatorProvider;
import org.junit.Test;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.spy;
@@ -32,11 +29,7 @@ public void test_execution() {
when(executor.executeScript("return true;")).thenReturn(true);
// when
- GrapheneContext.set(executor);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl());
- GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor));
- TestingInterface instance = JSInterfaceFactory.create(TestingInterface.class);
+ TestingInterface instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterface.class);
instance.method();
// then
@@ -51,11 +44,7 @@ public void test_execution_with_named_method() {
when(executor.executeScript("return true;")).thenReturn(true);
// when
- GrapheneContext.set(executor);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl());
- GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor));
- TestingInterface instance = JSInterfaceFactory.create(TestingInterface.class);
+ TestingInterface instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterface.class);
instance.namedMethod();
// then
@@ -75,11 +64,7 @@ public void test_execution_with_base() {
when(executor.executeScript("return true;")).thenReturn(true);
// when
- GrapheneContext.set(executor);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl());
- GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor));
- TestingInterfaceWithBase instance = JSInterfaceFactory.create(TestingInterfaceWithBase.class);
+ TestingInterfaceWithBase instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterfaceWithBase.class);
instance.method();
// then
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestInstantiation.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestInstantiation.java
index fe3124019..0202d972f 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestInstantiation.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestInstantiation.java
@@ -1,17 +1,24 @@
package org.jboss.arquillian.graphene.javascript;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
+import org.jboss.arquillian.graphene.TestingDriverStub;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
+import org.mockito.Spy;
public class TestInstantiation {
+ @Spy
+ TestingDriverStub executor = new TestingDriverStub();
+
@JavaScript
public static interface TestingInterface {
}
@Test
public void factory_should_create_valid_instance_of_given_interface() {
- TestingInterface instance = JSInterfaceFactory.create(TestingInterface.class);
+ TestingInterface instance = JSInterfaceFactory.create(GrapheneContext.getContextFor(Default.class), TestingInterface.class);
assertTrue("instance should implement the provided interface", instance instanceof TestingInterface);
}
@@ -21,6 +28,6 @@ public static class InvalidClass {
@Test(expected = IllegalArgumentException.class)
public void factory_should_fail_when_class_provided() {
- JSInterfaceFactory.create(InvalidClass.class);
+ InvalidClass instance = JSInterfaceFactory.create(GrapheneContext.getContextFor(Default.class), InvalidClass.class);
}
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestParameters.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestParameters.java
index 2f1a11146..be2d82f11 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestParameters.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestParameters.java
@@ -1,17 +1,15 @@
package org.jboss.arquillian.graphene.javascript;
-import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
+import java.util.Arrays;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext;
-import org.jboss.arquillian.graphene.context.TestingDriverStub;
-import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistryImpl;
-import org.jboss.arquillian.graphene.page.extension.RemotePageExtensionInstallatorProvider;
+import org.jboss.arquillian.graphene.TestingDriverStub;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
@@ -42,11 +40,7 @@ public interface TestingInterface {
public void prepareTest() {
// given
MockitoAnnotations.initMocks(this);
- GrapheneContext.set(executor);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl());
- GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor));
- instance = JSInterfaceFactory.create(TestingInterface.class);
+ instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterface.class);
when(executor.executeScript("return true;")).thenReturn(true);
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestReturnValues.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestReturnValues.java
index a57077fc0..6d0ea78fb 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestReturnValues.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/javascript/TestReturnValues.java
@@ -1,17 +1,14 @@
package org.jboss.arquillian.graphene.javascript;
-import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
-import org.jboss.arquillian.graphene.context.GrapheneConfigurationContext;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import org.jboss.arquillian.graphene.context.GrapheneContext;
-import org.jboss.arquillian.graphene.context.GraphenePageExtensionsContext;
-import org.jboss.arquillian.graphene.context.TestingDriverStub;
-import org.jboss.arquillian.graphene.page.extension.PageExtensionRegistryImpl;
-import org.jboss.arquillian.graphene.page.extension.RemotePageExtensionInstallatorProvider;
+import org.jboss.arquillian.graphene.TestingDriverStub;
+import org.jboss.arquillian.graphene.configuration.GrapheneConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -46,13 +43,10 @@ public interface TestingInterface {
public void prepareTest() {
// given
MockitoAnnotations.initMocks(this);
- GrapheneContext.set(executor);
- GrapheneConfigurationContext.set(new GrapheneConfiguration());
- GraphenePageExtensionsContext.setRegistry(new PageExtensionRegistryImpl());
- GraphenePageExtensionsContext.setInstallatorProvider(new RemotePageExtensionInstallatorProvider(GraphenePageExtensionsContext.getRegistryProxy(), executor));
- instance = JSInterfaceFactory.create(TestingInterface.class);
+ instance = JSInterfaceFactory.create(GrapheneContext.setContextFor(new GrapheneConfiguration(), executor, Default.class), TestingInterface.class);
when(executor.executeScript(Mockito.anyString())).then(new Answer<Object>() {
+ @Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return answer;
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyHandler.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyHandler.java
index 3886d4fc7..44b8aca76 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyHandler.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyHandler.java
@@ -21,7 +21,6 @@
*/
package org.jboss.arquillian.graphene.proxy;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxyHandler;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
@@ -32,6 +31,8 @@
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
+import org.jboss.arquillian.drone.api.annotation.Default;
+import org.jboss.arquillian.graphene.GrapheneContext;
import org.junit.Before;
import org.junit.Test;
@@ -60,6 +61,7 @@ private class IsProxyable implements Answer<Object> {
List<Method> violations = new LinkedList<Method>();
+ @Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Method method = invocation.getMethod();
if (!handler.isProxyable(method, invocation.getArguments())) {
@@ -77,6 +79,7 @@ private class IsNotProxyable implements Answer<Object> {
List<Method> violations = new LinkedList<Method>();
+ @Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Method method = invocation.getMethod();
if (handler.isProxyable(method, invocation.getArguments())) {
@@ -92,7 +95,7 @@ public List<Method> getViolations() {
@Before
public void prepare() {
- handler = GrapheneProxyHandler.forTarget(null);
+ handler = GrapheneProxyHandler.forTarget(GrapheneContext.getContextFor(Default.class), null);
}
@Test
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyInstantiation.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyInstantiation.java
index a098e73bd..a91778ace 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyInstantiation.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyInstantiation.java
@@ -21,8 +21,7 @@
*/
package org.jboss.arquillian.graphene.proxy;
-import org.jboss.arquillian.graphene.context.TestingDriverStub;
-import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
+import org.jboss.arquillian.graphene.TestingDriverStub;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
@@ -43,7 +42,7 @@ public Object getTarget() {
};
// when
- TestingDriver driver = GrapheneProxy.<TestingDriver>getProxyForFutureTarget(target, TestingDriver.class);
+ TestingDriver driver = GrapheneProxy.<TestingDriver>getProxyForFutureTarget(null, target, TestingDriver.class);
try {
driver.quit();
fail("exception should be thrown because of FutureTarget definition");
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyUtil.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyUtil.java
index 68e081cea..5000a1e86 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyUtil.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/proxy/TestGrapheneProxyUtil.java
@@ -27,9 +27,9 @@
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
-import org.jboss.arquillian.graphene.context.TestingDriver;
-import org.jboss.arquillian.graphene.context.TestingDriverStub;
-import org.jboss.arquillian.graphene.context.TestingDriverStubExtension;
+import org.jboss.arquillian.graphene.TestingDriver;
+import org.jboss.arquillian.graphene.TestingDriverStub;
+import org.jboss.arquillian.graphene.TestingDriverStubExtension;
import org.junit.Test;
import org.openqa.selenium.SearchContext;
|
982eebf70ff4aebfc200c6373511f1ce0e8667ed
|
kotlin
|
better root ns--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaBridgeConfiguration.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaBridgeConfiguration.java
index 10f6b61ae373a..c41515e932cb0 100644
--- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaBridgeConfiguration.java
+++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaBridgeConfiguration.java
@@ -19,7 +19,6 @@
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.lang.ModuleConfiguration;
-import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor;
import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor;
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
import org.jetbrains.jet.lang.psi.JetImportDirective;
@@ -72,24 +71,4 @@ public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull Namespace
}
- @Override
- public NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName) {
- NamespaceDescriptor namespaceDescriptor = javaSemanticServices.getDescriptorResolver().resolveNamespace(FqName.topLevel(shortName));
- if (namespaceDescriptor != null) {
- return namespaceDescriptor;
- }
- return delegateConfiguration.getTopLevelNamespace(shortName);
- }
-
- @Override
- public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces) {
- NamespaceDescriptor defaultPackage = javaSemanticServices.getDescriptorResolver().resolveNamespace(FqName.ROOT);
- assert defaultPackage != null : "Cannot resolve Java's default package";
- for (DeclarationDescriptor declarationDescriptor : defaultPackage.getMemberScope().getAllDescriptors()) {
- if (declarationDescriptor instanceof NamespaceDescriptor) {
- NamespaceDescriptor namespaceDescriptor = (NamespaceDescriptor) declarationDescriptor;
- topLevelNamespaces.add(namespaceDescriptor);
- }
- }
- }
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/DefaultModuleConfiguration.java b/compiler/frontend/src/org/jetbrains/jet/lang/DefaultModuleConfiguration.java
index 790b1b184ee79..82bf46581b5ae 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/DefaultModuleConfiguration.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/DefaultModuleConfiguration.java
@@ -53,13 +53,4 @@ public void addDefaultImports(@NotNull WritableScope rootScope, @NotNull Collect
public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull NamespaceDescriptor namespaceDescriptor, @NotNull WritableScope namespaceMemberScope) {
}
- @Override
- public NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName) {
- return null;
- }
-
- @Override
- public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces) {
- }
-
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/ModuleConfiguration.java b/compiler/frontend/src/org/jetbrains/jet/lang/ModuleConfiguration.java
index 0ed59fcb0383d..5c9c34bedb3e9 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/ModuleConfiguration.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/ModuleConfiguration.java
@@ -17,8 +17,6 @@
package org.jetbrains.jet.lang;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.jet.lang.descriptors.ModuleDescriptor;
import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor;
import org.jetbrains.jet.lang.psi.JetImportDirective;
import org.jetbrains.jet.lang.resolve.BindingTrace;
@@ -39,14 +37,6 @@ public void addDefaultImports(@NotNull WritableScope rootScope, @NotNull Collect
public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull NamespaceDescriptor namespaceDescriptor, @NotNull WritableScope namespaceMemberScope) {
}
- @Override
- public NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName) {
- return null;
- }
-
- @Override
- public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces) {
- }
};
void addDefaultImports(@NotNull WritableScope rootScope, @NotNull Collection<JetImportDirective> directives);
@@ -57,10 +47,4 @@ public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDesc
*/
void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull NamespaceDescriptor namespaceDescriptor, @NotNull WritableScope namespaceMemberScope);
- /** This method is called only if no namespace with the same short name is declared in the module itself, or to merge namespaces */
- @Nullable
- NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName);
-
- /** Add all the top-level namespaces from the dependencies of this module into the given collection */
- void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces);
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java
index 408fc93b1b543..1b6e1b055d7eb 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java
@@ -288,28 +288,11 @@ private void doAnalyzeFilesWithGivenTrance2(Collection<JetFile> files) {
// Import the lang package
scope.importScope(JetStandardLibrary.getInstance().getLibraryScope());
+ NamespaceDescriptorImpl rootNs = typeHierarchyResolver.createNamespaceDescriptorIfNeeded(null, moduleDescriptor, "<root>", true);
+
// Import a scope that contains all top-level namespaces that come from dependencies
// This makes the namespaces visible at all, does not import themselves
- scope.importScope(new JetScopeAdapter(JetScope.EMPTY) {
- @Override
- public NamespaceDescriptor getNamespace(@NotNull String name) {
- // Is it a top-level namespace coming from the dependencies?
- NamespaceDescriptor topLevelNamespaceFromConfiguration = configuration.getTopLevelNamespace(name);
- if (topLevelNamespaceFromConfiguration != null) {
- return topLevelNamespaceFromConfiguration;
- }
- // Should be null, we are delegating to EMPTY
- return super.getNamespace(name);
- }
-
- @NotNull
- @Override
- public Collection<DeclarationDescriptor> getAllDescriptors() {
- List<DeclarationDescriptor> allDescriptors = Lists.newArrayList();
- configuration.addAllTopLevelNamespacesTo(allDescriptors);
- return allDescriptors;
- }
- });
+ scope.importScope(rootNs.getMemberScope());
// dummy builder is used because "root" is module descriptor,
// namespaces added to module explicitly in
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
index da814eeaa06d1..63a49dd678514 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
@@ -263,7 +263,7 @@ private NamespaceDescriptorImpl createNamespaceDescriptorPathIfNeeded(JetFile fi
}
@NotNull
- private NamespaceDescriptorImpl createNamespaceDescriptorIfNeeded(@Nullable JetFile file, @NotNull NamespaceDescriptorParent owner, @NotNull String name, boolean root) {
+ public NamespaceDescriptorImpl createNamespaceDescriptorIfNeeded(@Nullable JetFile file, @NotNull NamespaceDescriptorParent owner, @NotNull String name, boolean root) {
FqName fqName;
NamespaceDescriptorImpl namespaceDescriptor;
diff --git a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java
index a001856ead064..76209a93f713a 100644
--- a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java
+++ b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java
@@ -129,13 +129,5 @@ public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull Namespace
@NotNull WritableScope namespaceMemberScope) {
}
- @Override
- public NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName) {
- return null;
- }
-
- @Override
- public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces) {
- }
}
}
|
66de48a353197903c0b45c4af25be24c5588cfe1
|
hadoop
|
HDFS-2500. Avoid file system operations in- BPOfferService thread while processing deletes. Contributed by Todd Lipcon.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1190072 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 2ce3a9765a8ce..9a0ecbea52e77 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -761,6 +761,9 @@ Release 0.23.0 - Unreleased
HDFS-2118. Couple dfs data dir improvements. (eli)
+ HDFS-2500. Avoid file system operations in BPOfferService thread while
+ processing deletes. (todd)
+
BUG FIXES
HDFS-2344. Fix the TestOfflineEditsViewer test failure in 0.23 branch.
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
index eb953ab7eb241..3f7733608999c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
@@ -1108,8 +1108,15 @@ private void offerService() throws Exception {
if (!heartbeatsDisabledForTests) {
DatanodeCommand[] cmds = sendHeartBeat();
metrics.addHeartbeat(now() - startTime);
+
+ long startProcessCommands = now();
if (!processCommand(cmds))
continue;
+ long endProcessCommands = now();
+ if (endProcessCommands - startProcessCommands > 2000) {
+ LOG.info("Took " + (endProcessCommands - startProcessCommands) +
+ "ms to process " + cmds.length + " commands from NN");
+ }
}
}
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java
index 08b40fed2aae4..53c5525908440 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java
@@ -2088,10 +2088,9 @@ public void invalidate(String bpid, Block invalidBlks[]) throws IOException {
volumeMap.remove(bpid, invalidBlks[i]);
}
File metaFile = getMetaFile(f, invalidBlks[i].getGenerationStamp());
- long dfsBytes = f.length() + metaFile.length();
// Delete the block asynchronously to make sure we can do it fast enough
- asyncDiskService.deleteAsync(v, bpid, f, metaFile, dfsBytes,
+ asyncDiskService.deleteAsync(v, bpid, f, metaFile,
invalidBlks[i].toString());
}
if (error) {
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java
index 176f8825d9fb2..0c2523b834176 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java
@@ -148,11 +148,11 @@ synchronized void shutdown() {
* dfsUsed statistics accordingly.
*/
void deleteAsync(FSDataset.FSVolume volume, String bpid, File blockFile,
- File metaFile, long dfsBytes, String blockName) {
+ File metaFile, String blockName) {
DataNode.LOG.info("Scheduling block " + blockName + " file " + blockFile
+ " for deletion");
ReplicaFileDeleteTask deletionTask =
- new ReplicaFileDeleteTask(volume, bpid, blockFile, metaFile, dfsBytes,
+ new ReplicaFileDeleteTask(volume, bpid, blockFile, metaFile,
blockName);
execute(volume.getCurrentDir(), deletionTask);
}
@@ -165,16 +165,14 @@ static class ReplicaFileDeleteTask implements Runnable {
final String blockPoolId;
final File blockFile;
final File metaFile;
- final long dfsBytes;
final String blockName;
ReplicaFileDeleteTask(FSDataset.FSVolume volume, String bpid,
- File blockFile, File metaFile, long dfsBytes, String blockName) {
+ File blockFile, File metaFile, String blockName) {
this.volume = volume;
this.blockPoolId = bpid;
this.blockFile = blockFile;
this.metaFile = metaFile;
- this.dfsBytes = dfsBytes;
this.blockName = blockName;
}
@@ -192,6 +190,7 @@ public String toString() {
@Override
public void run() {
+ long dfsBytes = blockFile.length() + metaFile.length();
if ( !blockFile.delete() || ( !metaFile.delete() && metaFile.exists() ) ) {
DataNode.LOG.warn("Unexpected error trying to delete block "
+ blockPoolId + " " + blockName + " at file " + blockFile
|
c7c8f2fe48d3a16ac70fb98f662d3d77292ba0cd
|
hadoop
|
MAPREDUCE-2603. Disable High-Ram emulation in- system tests. (Vinay Kumar Thota via amarrk)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1138301 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/mapreduce/CHANGES.txt b/mapreduce/CHANGES.txt
index 988c40eda0b45..75c454e91447b 100644
--- a/mapreduce/CHANGES.txt
+++ b/mapreduce/CHANGES.txt
@@ -186,6 +186,9 @@ Trunk (unreleased changes)
BUG FIXES
+ MAPREDUCE-2603. Disable High-Ram emulation in system tests.
+ (Vinay Kumar Thota via amarrk)
+
MAPREDUCE-2539. Fixed NPE in getMapTaskReports in JobClient. (Robert Evans via
acmurthy)
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationEnableForAllTypesOfJobs.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationEnableForAllTypesOfJobs.java
index 4144bae842e87..3ade9e34e687b 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationEnableForAllTypesOfJobs.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationEnableForAllTypesOfJobs.java
@@ -56,6 +56,7 @@ public void testInputCompressionEmualtionEnableForAllJobsWithDefaultRatios()
final String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=true",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_INPUT_DECOMPRESS_ENABLE + "=true",
"-D", GridMixConfig.GRIDMIX_INPUT_COMPRESS_RATIO + "=0.46",
"-D", GridMixConfig.GRIDMIX_INTERMEDIATE_COMPRESSION_RATIO + "=0.35",
@@ -84,6 +85,7 @@ public void testInputCompressionEmulationEnableForAllJobsWithCustomRatios()
final String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationForCompressInAndUncompressOut.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationForCompressInAndUncompressOut.java
index 6f0dcbff0f056..4b7fc3a15aada 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationForCompressInAndUncompressOut.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationForCompressInAndUncompressOut.java
@@ -56,6 +56,7 @@ public void testCompressionEmulationOfCompressedInputWithDefaultRatios()
final String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=true"
};
@@ -85,6 +86,7 @@ public void testCompressionEmulationOfCompressedInputWithCustomRatios()
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=true",
"-D", GridMixConfig.GRIDMIX_INPUT_DECOMPRESS_ENABLE + "=true",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_INPUT_COMPRESS_RATIO + "=0.58",
"-D", GridMixConfig.GRIDMIX_INTERMEDIATE_COMPRESSION_RATIO + "=0.42"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationForUncompressInAndCompressOut.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationForUncompressInAndCompressOut.java
index 70dc0d1276451..383fc83de4b1d 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationForUncompressInAndCompressOut.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationForUncompressInAndCompressOut.java
@@ -54,6 +54,7 @@ public void testCompressionEmulationOfCompressedOuputWithDefaultRatios()
final String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=true"
};
@@ -82,6 +83,7 @@ public void testCompressionEmulationOfCompressedOutputWithCustomRatios()
final String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=true",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_OUTPUT_COMPRESSION_RATIO + "=0.38"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSAndLocalFSDCFiles.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSAndLocalFSDCFiles.java
index d98b259177ab4..a1ae1e9dfafe7 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSAndLocalFSDCFiles.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSAndLocalFSDCFiles.java
@@ -59,6 +59,7 @@ public void testGenerateDataEmulateHDFSAndLocalFSDCFiles()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -85,6 +86,7 @@ public void testEmulationOfHDFSAndLocalFSDCFiles()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSDCFileUsesMultipleJobs.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSDCFileUsesMultipleJobs.java
index 00d2e4825a2a2..7f8938f88a742 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSDCFileUsesMultipleJobs.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSDCFileUsesMultipleJobs.java
@@ -58,6 +58,7 @@ public void testGenerateAndEmulationOfHDFSDCFile()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -81,6 +82,7 @@ public void testGridmixEmulationOfHDFSPublicDCFile()
tracePath};
final String [] otherArgs = {
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSDCFilesWithDifferentVisibilities.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSDCFilesWithDifferentVisibilities.java
index 3840f1bbeafa0..453e5b990815b 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSDCFilesWithDifferentVisibilities.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfHDFSDCFilesWithDifferentVisibilities.java
@@ -60,6 +60,7 @@ public void testGenerateAndEmulateOfHDFSDCFilesWithDiffVisibilities()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -81,6 +82,7 @@ public void testHDFSDCFilesWithoutEnableDCEmulation()
"REPLAY",
tracePath};
final String [] otherArgs = {
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfLocalFSDCFiles.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfLocalFSDCFiles.java
index e50eb6e2e8138..eff47f2d64134 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfLocalFSDCFiles.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestEmulationOfLocalFSDCFiles.java
@@ -57,6 +57,7 @@ public void testGenerateInputAndEmulateLocalFSDCFile()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -83,6 +84,7 @@ public void testEmulationOfLocalFSDCFile()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridMixDataGeneration.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridMixDataGeneration.java
index f1501bf850b77..ef273b5fd2519 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridMixDataGeneration.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridMixDataGeneration.java
@@ -93,6 +93,7 @@ public void testGenerateDataWithSTRESSSubmission() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
int exitCode =
@@ -123,6 +124,7 @@ public void testGenerateDataWithREPLAYSubmission() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
@@ -154,6 +156,7 @@ public void testGenerateDataWithSERIALSubmission() throws Exception {
long bytesPerFile = 200 * 1024 * 1024; // 200 mb per file of data
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_BYTES_PER_FILE + "=" + bytesPerFile,
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridMixFilePool.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridMixFilePool.java
index 1ad10d8af50fe..883feec88fcbe 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridMixFilePool.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridMixFilePool.java
@@ -80,6 +80,7 @@ public void testFilesCountAndSizesForSpecifiedFilePool() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixCompressionEmulationWithCompressInput.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixCompressionEmulationWithCompressInput.java
index adaa0d2363be8..3fdd16d7f6f90 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixCompressionEmulationWithCompressInput.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixCompressionEmulationWithCompressInput.java
@@ -59,6 +59,7 @@ public void testGridmixCompressionRatiosAgainstDefaultCompressionRatio()
final String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -89,6 +90,7 @@ public void testGridmixOuputCompressionRatiosAgainstCustomRatios()
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=true",
"-D", GridMixConfig.GRIDMIX_INPUT_DECOMPRESS_ENABLE + "=true",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_INPUT_COMPRESS_RATIO + "=0.68",
"-D", GridMixConfig.GRIDMIX_INTERMEDIATE_COMPRESSION_RATIO + "=0.35",
"-D", GridMixConfig.GRIDMIX_OUTPUT_COMPRESSION_RATIO + "=0.40"
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfHDFSPrivateDCFile.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfHDFSPrivateDCFile.java
index 5289bf3c8a140..e6c7e6af46ba3 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfHDFSPrivateDCFile.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfHDFSPrivateDCFile.java
@@ -56,6 +56,7 @@ public void testGenerateAndEmulateOfHDFSPrivateDCFile()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -78,6 +79,7 @@ public void testGridmixEmulationOfHDFSPrivateDCFile()
"REPLAY",
tracePath};
final String [] otherArgs = {
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfHDFSPublicDCFile.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfHDFSPublicDCFile.java
index e12180c72e428..0bf07fdf4d208 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfHDFSPublicDCFile.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfHDFSPublicDCFile.java
@@ -55,6 +55,7 @@ public void testGenerateAndEmulationOfSingleHDFSDCFile()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -80,6 +81,7 @@ public void testGridmixEmulationOfSingleHDFSPublicDCFile()
tracePath};
final String [] otherArgs = {
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfMultipleHDFSPrivateDCFiles.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfMultipleHDFSPrivateDCFiles.java
index 4dca1a214ce82..5f464ce39be56 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfMultipleHDFSPrivateDCFiles.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfMultipleHDFSPrivateDCFiles.java
@@ -58,6 +58,7 @@ public void testGenerateAndEmulationOfMultipleHDFSPrivateDCFiles()
tracePath};
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -81,6 +82,7 @@ public void testGridmixEmulationOfMultipleHDFSPrivateDCFiles()
"STRESS",
tracePath};
final String [] otherArgs = {
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfMultipleHDFSPublicDCFiles.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfMultipleHDFSPublicDCFiles.java
index 09bbf181226c1..cca5da83ecb48 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfMultipleHDFSPublicDCFiles.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixEmulationOfMultipleHDFSPublicDCFiles.java
@@ -59,6 +59,7 @@ public void testGenerateAndEmulationOfMultipleHDFSDCFiles()
final String [] otherArgs = {
"-D", MRJobConfig.JOB_CANCEL_DELEGATION_TOKEN + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
@@ -81,6 +82,7 @@ public void testGridmixEmulationOfMulitpleHDFSPublicDCFile()
tracePath};
final String [] otherArgs = {
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=true"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath,
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith10minTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith10minTrace.java
index c48a7461d3fd2..ec11a2b36e66c 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith10minTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith10minTrace.java
@@ -55,6 +55,7 @@ public void testGridmixWith10minTrace() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_MINIMUM_FILE_SIZE + "=" + minFileSize,
"-D", GridMixConfig.GRIDMIX_JOB_SUBMISSION_QUEUE_IN_TRACE + "=false",
"-D", GridMixConfig.GRIDMIX_SLEEPJOB_MAPTASK_ONLY + "=true",
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith12minTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith12minTrace.java
index ec2a1377bd6cb..9bcb45a3fbb6c 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith12minTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith12minTrace.java
@@ -51,6 +51,7 @@ public void testGridmixWith12minTrace() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_SLEEP_MAP_MAX_TIME + "=10",
"-D", GridMixConfig.GRIDMIX_SLEEP_REDUCE_MAX_TIME + "=5"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith1minTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith1minTrace.java
index ed2648448fa5a..c583e6d3a29fc 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith1minTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith1minTrace.java
@@ -49,6 +49,7 @@ public void testGridmixWith1minTrace() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith2minStreamingJobTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith2minStreamingJobTrace.java
index 9628dd2db8d6c..d9fb7c70f7f84 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith2minStreamingJobTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith2minStreamingJobTrace.java
@@ -56,6 +56,7 @@ public void testGridmixWith2minStreamJobTrace() throws Exception {
"-D", GridMixConfig.GRIDMIX_JOB_SUBMISSION_QUEUE_IN_TRACE + "=true",
"-D", GridMixConfig.GRIDMIX_MINIMUM_FILE_SIZE + "=" + minFileSize,
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
runGridmixAndVerify(runtimeValues, otherArgs, tracePath);
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith3minStreamingJobTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith3minStreamingJobTrace.java
index 926f795b747df..85dedf6675f96 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith3minStreamingJobTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith3minStreamingJobTrace.java
@@ -59,6 +59,7 @@ public void testGridmixWith3minStreamJobTrace() throws Exception {
"-D", GridMixConfig.GRIDMIX_JOB_SUBMISSION_QUEUE_IN_TRACE + "=true",
"-D", GridMixConfig.GRIDMIX_BYTES_PER_FILE + "=" + bytesPerFile,
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith3minTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith3minTrace.java
index bed33d0dd3ebc..5f2171fb40196 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith3minTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith3minTrace.java
@@ -52,6 +52,7 @@ public void testGridmixWith3minTrace() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith5minStreamingJobTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith5minStreamingJobTrace.java
index 370f120aa961a..ef1878c0855b5 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith5minStreamingJobTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith5minStreamingJobTrace.java
@@ -56,6 +56,7 @@ public void testGridmixWith5minStreamJobTrace() throws Exception {
"-D", GridMixConfig.GRIDMIX_KEY_FRC + "=0.5f",
"-D", GridMixConfig.GRIDMIX_BYTES_PER_FILE + "=" + bytesPerFile,
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false"
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith5minTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith5minTrace.java
index 5a141d4c8153d..c55167e3b4f51 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith5minTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith5minTrace.java
@@ -51,6 +51,7 @@ public void testGridmixWith5minTrace() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_MINIMUM_FILE_SIZE + "=" + minFileSize
};
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith7minTrace.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith7minTrace.java
index 0791d68aee28b..55be37b17dd89 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith7minTrace.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/TestGridmixWith7minTrace.java
@@ -51,6 +51,7 @@ public void testGridmixWith7minTrace() throws Exception {
String [] otherArgs = {
"-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false",
+ "-D", GridmixJob.GRIDMIX_HIGHRAM_EMULATION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false",
"-D", GridMixConfig.GRIDMIX_MINIMUM_FILE_SIZE + "=" + minFileSize,
"-D", GridMixConfig.GRIDMIX_JOB_SUBMISSION_QUEUE_IN_TRACE + "=false"
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/test/system/GridmixJobVerification.java b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/test/system/GridmixJobVerification.java
index 46872b2418cd4..ae71ec5764bde 100644
--- a/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/test/system/GridmixJobVerification.java
+++ b/mapreduce/src/contrib/gridmix/src/test/system/org/apache/hadoop/mapred/gridmix/test/system/GridmixJobVerification.java
@@ -316,7 +316,9 @@ public JobConf getSimulatedJobConf(JobID simulatedJobID, File tmpJHFolder)
Path jhpath = new Path(historyFilePath);
fs = jhpath.getFileSystem(conf);
fs.copyToLocalFile(jhpath,new Path(tmpJHFolder.toString()));
- fs.copyToLocalFile(new Path(historyFilePath + "_conf.xml"),
+ String historyPath =
+ historyFilePath.substring(0,historyFilePath.lastIndexOf("_"));
+ fs.copyToLocalFile(new Path(historyPath + "_conf.xml"),
new Path(tmpJHFolder.toString()));
JobConf jobConf = new JobConf();
jobConf.addResource(new Path(tmpJHFolder.toString()
diff --git a/mapreduce/src/contrib/gridmix/src/test/system/resources/highram_mr_jobs_case4.json.gz b/mapreduce/src/contrib/gridmix/src/test/system/resources/highram_mr_jobs_case4.json.gz
index c4d4657c3cb7f..229d8d321bc4a 100644
Binary files a/mapreduce/src/contrib/gridmix/src/test/system/resources/highram_mr_jobs_case4.json.gz and b/mapreduce/src/contrib/gridmix/src/test/system/resources/highram_mr_jobs_case4.json.gz differ
|
afb1efaa343a4341f9883741adeae77589210df6
|
kotlin
|
Refactored reference provider logic.--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index d0362e355ceec..99bc02b26e7aa 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -8,48 +8,12 @@
</component>
<component name="ChangeListManager">
<list default="true" id="f02ef53d-47a4-4f5e-a1aa-3df68aae9b20" name="Default" comment="">
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionTranslator.java" />
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java" />
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java" />
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/PatternTranslator.java" />
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/WhenTranslator.java" />
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/AbstractTranslator.java" />
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslationContext.java" />
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslatorVisitor.java" />
- <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/BindingUtils.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\AbstractTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/AbstractTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\BinaryOperationTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/BinaryOperationTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\BindingUtils.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/BindingUtils.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\ExpressionTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\ExpressionVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\FunctionTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\GenerationState.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/GenerationState.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\Namer.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/Namer.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\OperationTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/OperationTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\OperatorTable.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/OperatorTable.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\PatternTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/PatternTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\PropertyAccessTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\ReferenceProvider.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\ReferenceTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\Translation.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\TranslationContext.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslationContext.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\TranslationUtils.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\TranslatorVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslatorVisitor.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\UnaryOperationTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/UnaryOperationTranslator.java" />
- <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\WhenTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/WhenTranslator.java" />
<change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/K2JSTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/K2JSTranslator.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/declarations/ExtractionVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/declarations/ExtractionVisitor.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/ClassDeclarationTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/ClassDeclarationTranslator.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/ClassTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/ClassTranslator.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/DeclarationBodyVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/DeclarationBodyVisitor.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/NamespaceTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/NamespaceTranslator.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/PropertyTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/PropertyTranslator.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/AbstractInitializerTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/AbstractInitializerTranslator.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/ClassInitializerTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/ClassInitializerTranslator.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/InitializerVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/InitializerVisitor.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/NamespaceInitializerTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/NamespaceInitializerTranslator.java" />
- <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/utils/ClassSorter.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/utils/ClassSorter.java" />
+ <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java" />
+ <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java" />
+ <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java" />
+ <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java" />
+ <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java" />
</list>
<ignored path="k2js.iws" />
<ignored path=".idea/workspace.xml" />
@@ -160,7 +124,7 @@
<favorites_list name="k2js" />
</component>
<component name="FileEditorManager">
- <splitter split-orientation="horizontal" split-proportion="0.3907068">
+ <splitter split-orientation="horizontal" split-proportion="0.5281414">
<split-first>
<leaf>
<file leaf-file-name="UnaryOperationTranslator.java" pinned="false" current="false" current-in-tab="false">
@@ -176,7 +140,9 @@
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/OperationTranslator.java">
<provider selected="true" editor-type-id="text-editor">
<state line="49" column="0" selection-start="1957" selection-end="1957" vertical-scroll-proportion="0.0">
- <folding />
+ <folding>
+ <element signature="imports" expanded="false" />
+ </folding>
</state>
</provider>
</entry>
@@ -220,16 +186,34 @@
<file leaf-file-name="ReferenceProvider.java" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java">
<provider selected="true" editor-type-id="text-editor">
- <state line="13" column="19" selection-start="468" selection-end="468" vertical-scroll-proportion="0.0">
+ <state line="41" column="59" selection-start="1836" selection-end="1836" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
</file>
- <file leaf-file-name="ReferenceTranslator.java" pinned="false" current="true" current-in-tab="true">
+ <file leaf-file-name="ReferenceTranslator.java" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java">
<provider selected="true" editor-type-id="text-editor">
- <state line="30" column="11" selection-start="1117" selection-end="1117" vertical-scroll-proportion="0.30357143">
+ <state line="68" column="83" selection-start="2716" selection-end="2716" vertical-scroll-proportion="0.0">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ </file>
+ <file leaf-file-name="PropertyAccessTranslator.java" pinned="false" current="true" current-in-tab="true">
+ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="120" column="100" selection-start="5315" selection-end="5315" vertical-scroll-proportion="0.23214285">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ </file>
+ <file leaf-file-name="TraitTest.java" pinned="false" current="false" current-in-tab="false">
+ <entry file="file://$PROJECT_DIR$/translator/test/org/jetbrains/k2js/test/TraitTest.java">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="58" column="60" selection-start="1296" selection-end="1296" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
@@ -251,10 +235,8 @@
<file leaf-file-name="TranslationUtils.java" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java">
<provider selected="true" editor-type-id="text-editor">
- <state line="105" column="5" selection-start="4607" selection-end="4607" vertical-scroll-proportion="0.0">
- <folding>
- <element signature="imports" expanded="false" />
- </folding>
+ <state line="36" column="0" selection-start="1468" selection-end="1468" vertical-scroll-proportion="0.0">
+ <folding />
</state>
</provider>
</entry>
@@ -275,7 +257,9 @@
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/DeclarationBodyVisitor.java">
<provider selected="true" editor-type-id="text-editor">
<state line="55" column="0" selection-start="2216" selection-end="2216" vertical-scroll-proportion="0.0">
- <folding />
+ <folding>
+ <element signature="imports" expanded="false" />
+ </folding>
</state>
</provider>
</entry>
@@ -307,19 +291,19 @@
</provider>
</entry>
</file>
- <file leaf-file-name="Translation.java" pinned="false" current="false" current-in-tab="false">
+ <file leaf-file-name="Translation.java" pinned="false" current="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java">
<provider selected="true" editor-type-id="text-editor">
- <state line="36" column="56" selection-start="1761" selection-end="1761" vertical-scroll-proportion="0.0">
+ <state line="97" column="0" selection-start="4431" selection-end="4431" vertical-scroll-proportion="1.1111112">
<folding />
</state>
</provider>
</entry>
</file>
- <file leaf-file-name="ExpressionVisitor.java" pinned="false" current="false" current-in-tab="true">
+ <file leaf-file-name="ExpressionVisitor.java" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java">
<provider selected="true" editor-type-id="text-editor">
- <state line="159" column="66" selection-start="7163" selection-end="7163" vertical-scroll-proportion="0.3023622">
+ <state line="159" column="66" selection-start="7163" selection-end="7163" vertical-scroll-proportion="-7.3846154">
<folding />
</state>
</provider>
@@ -355,10 +339,6 @@
<component name="IdeDocumentHistory">
<option name="changedFiles">
<list>
- <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/ReferenceTranslator.java" />
- <option value="$PROJECT_DIR$/translator/test/org/jetbrains/k2js/test/BasicClassTest.java" />
- <option value="$PROJECT_DIR$/translator/testFiles/class/out/propertiesAsParametersInitialized.js" />
- <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/ClassInitializerTranslator.java" />
<option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/TranslationUtils.java" />
<option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/TranslationContext.java" />
<option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/Translation.java" />
@@ -370,7 +350,11 @@
<option value="$PROJECT_DIR$/translator/testFiles/operatorOverloading/cases/usingModInCaseModAssignNotAvailable.kt" />
<option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/OperatorTable.java" />
<option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/OperatorTable.java" />
+ <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java" />
+ <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java" />
<option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java" />
+ <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java" />
+ <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java" />
</list>
</option>
</component>
@@ -985,7 +969,7 @@
</component>
<component name="ToolWindowManager">
<frame x="-8" y="-8" width="1936" height="1176" extended-state="6" />
- <editor active="false" />
+ <editor active="true" />
<layout>
<window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32853025" sideWeight="0.49812934" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
@@ -1002,8 +986,8 @@
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="true" content_ui="tabs" />
<window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32977018" sideWeight="0.728146" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3997862" sideWeight="0.6705998" order="0" side_tool="false" content_ui="tabs" />
- <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.18332443" sideWeight="0.728146" order="0" side_tool="false" content_ui="tabs" />
- <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.27185398" sideWeight="0.64190274" order="2" side_tool="false" content_ui="tabs" />
+ <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.18332443" sideWeight="0.728146" order="0" side_tool="false" content_ui="tabs" />
+ <window_info id="Run" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.27185398" sideWeight="0.64190274" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
<window_info id="Metrics" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3275862" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" />
@@ -1047,7 +1031,7 @@
<option name="INCLUDE_TEXT_INTO_SHELF" value="false" />
<option name="CREATE_PATCH_EXPAND_DETAILS_DEFAULT" value="true" />
<option name="FORCE_NON_EMPTY_COMMENT" value="false" />
- <option name="LAST_COMMIT_MESSAGE" value="Added test." />
+ <option name="LAST_COMMIT_MESSAGE" value="Reorganised project structure." />
<option name="MAKE_NEW_CHANGELIST_ACTIVE" value="true" />
<option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="true" />
<option name="CHECK_FILES_UP_TO_DATE_BEFORE_COMMIT" value="false" />
@@ -1060,7 +1044,6 @@
<option name="UPDATE_GROUP_BY_CHANGELIST" value="false" />
<option name="SHOW_FILE_HISTORY_AS_TREE" value="false" />
<option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" />
- <MESSAGE value="Rewrote name resolving logic. Improved DeclarationExtractor and renamed to Declarations." />
<MESSAGE value="Added support for basic case of function literal." />
<MESSAGE value="Added tests for simple closure examples." />
<MESSAGE value="Added some tests from jet project." />
@@ -1085,6 +1068,7 @@
<MESSAGE value="Added support for initialization of properties as constructor parameters." />
<MESSAGE value="Refactoring function translator." />
<MESSAGE value="Added test." />
+ <MESSAGE value="Reorganised project structure." />
</component>
<component name="XDebuggerManager">
<breakpoint-manager />
@@ -1094,29 +1078,6 @@
<option name="FILTER_TARGETS" value="false" />
</component>
<component name="editorHistoryManager">
- <entry file="file://$PROJECT_DIR$/translator/testFiles/inheritance/out/valuePassedToAncestorConstructor.js">
- <provider selected="true" editor-type-id="text-editor">
- <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
- <folding />
- </state>
- </provider>
- </entry>
- <entry file="file://$PROJECT_DIR$/translator/testFiles/class/out/propertiesAsParametersInitialized.js">
- <provider selected="true" editor-type-id="text-editor">
- <state line="3" column="102" selection-start="97" selection-end="97" vertical-scroll-proportion="0.0">
- <folding />
- </state>
- </provider>
- </entry>
- <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java">
- <provider selected="true" editor-type-id="text-editor">
- <state line="105" column="5" selection-start="4607" selection-end="4607" vertical-scroll-proportion="0.0">
- <folding>
- <element signature="imports" expanded="false" />
- </folding>
- </state>
- </provider>
- </entry>
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslationContext.java">
<provider selected="true" editor-type-id="text-editor">
<state line="120" column="29" selection-start="4917" selection-end="4917" vertical-scroll-proportion="0.0">
@@ -1131,13 +1092,6 @@
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java">
- <provider selected="true" editor-type-id="text-editor">
- <state line="36" column="56" selection-start="1761" selection-end="1761" vertical-scroll-proportion="0.0">
- <folding />
- </state>
- </provider>
- </entry>
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java">
<provider selected="true" editor-type-id="text-editor">
<state line="70" column="93" selection-start="2680" selection-end="2680" vertical-scroll-proportion="0.0">
@@ -1151,7 +1105,9 @@
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/DeclarationBodyVisitor.java">
<provider selected="true" editor-type-id="text-editor">
<state line="55" column="0" selection-start="2216" selection-end="2216" vertical-scroll-proportion="0.0">
- <folding />
+ <folding>
+ <element signature="imports" expanded="false" />
+ </folding>
</state>
</provider>
</entry>
@@ -1183,30 +1139,58 @@
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java">
+ <entry file="file://$PROJECT_DIR$/translator/testFiles/operatorOverloading/cases/usingModInCaseModAssignNotAvailable.kt">
<provider selected="true" editor-type-id="text-editor">
- <state line="13" column="19" selection-start="468" selection-end="468" vertical-scroll-proportion="0.0">
+ <state line="13" column="30" selection-start="201" selection-end="201" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/translator/testFiles/operatorOverloading/cases/usingModInCaseModAssignNotAvailable.kt">
+ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java">
<provider selected="true" editor-type-id="text-editor">
- <state line="13" column="30" selection-start="201" selection-end="201" vertical-scroll-proportion="0.0">
+ <state line="159" column="66" selection-start="7163" selection-end="7163" vertical-scroll-proportion="-7.3846154">
<folding />
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java">
+ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java">
<provider selected="true" editor-type-id="text-editor">
- <state line="159" column="66" selection-start="7163" selection-end="7163" vertical-scroll-proportion="0.3023622">
+ <state line="41" column="59" selection-start="1836" selection-end="1836" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java">
<provider selected="true" editor-type-id="text-editor">
- <state line="30" column="11" selection-start="1117" selection-end="1117" vertical-scroll-proportion="0.30357143">
+ <state line="68" column="83" selection-start="2716" selection-end="2716" vertical-scroll-proportion="0.0">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="36" column="0" selection-start="1468" selection-end="1468" vertical-scroll-proportion="0.0">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="97" column="0" selection-start="4431" selection-end="4431" vertical-scroll-proportion="1.1111112">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ <entry file="file://$PROJECT_DIR$/translator/test/org/jetbrains/k2js/test/TraitTest.java">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="58" column="60" selection-start="1296" selection-end="1296" vertical-scroll-proportion="0.0">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="120" column="100" selection-start="5315" selection-end="5315" vertical-scroll-proportion="0.23214285">
<folding />
</state>
</provider>
diff --git a/translator/src/org/jetbrains/k2js/translate/general/Translation.java b/translator/src/org/jetbrains/k2js/translate/general/Translation.java
index 9e25f9cb70f12..63f32d507de43 100644
--- a/translator/src/org/jetbrains/k2js/translate/general/Translation.java
+++ b/translator/src/org/jetbrains/k2js/translate/general/Translation.java
@@ -15,7 +15,6 @@
import org.jetbrains.k2js.translate.initializer.ClassInitializerTranslator;
import org.jetbrains.k2js.translate.initializer.NamespaceInitializerTranslator;
import org.jetbrains.k2js.translate.reference.PropertyAccessTranslator;
-import org.jetbrains.k2js.translate.reference.ReferenceProvider;
import org.jetbrains.k2js.translate.reference.ReferenceTranslator;
/**
@@ -96,13 +95,6 @@ static public JsPropertyInitializer generateNamespaceInitializerMethod(@NotNull
return (new NamespaceInitializerTranslator(namespace, context)).generateInitializeMethod();
}
- @NotNull
- static public JsNameRef generateCorrectReference(@NotNull TranslationContext context,
- @NotNull JetSimpleNameExpression expression,
- @NotNull JsName referencedName) {
- return (new ReferenceProvider(context, expression, referencedName)).generateCorrectReference();
- }
-
public static void generateAst(@NotNull JsProgram result, @NotNull BindingContext bindingContext,
@NotNull Declarations declarations, @NotNull JetNamespace namespace) {
JsBlock block = result.getFragmentBlock(0);
diff --git a/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java b/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java
index f1d4d5123de62..44d6f941d0ae3 100644
--- a/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java
+++ b/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java
@@ -20,7 +20,6 @@
import org.jetbrains.k2js.translate.general.Translation;
import org.jetbrains.k2js.translate.general.TranslationContext;
import org.jetbrains.k2js.translate.utils.BindingUtils;
-import org.jetbrains.k2js.translate.utils.TranslationUtils;
/**
* @author Talanov Pavel
@@ -94,7 +93,7 @@ private JsInvocation resolveAsPropertyGet(@NotNull JetQualifiedExpression expres
@NotNull
private JsInvocation resolveAsPropertyGet(@NotNull JetSimpleNameExpression expression) {
JsName getterName = getNotNullGetterName(expression);
- JsNameRef getterReference = TranslationUtils.getReference(context(), expression, getterName);
+ JsNameRef getterReference = ReferenceProvider.getReference(getterName, context(), expression);
return AstUtil.newInvocation(getterReference);
}
@@ -118,7 +117,7 @@ private JsInvocation resolveAsPropertySet(@NotNull JetDotQualifiedExpression dot
@NotNull
private JsInvocation resolveAsPropertySet(@NotNull JetSimpleNameExpression expression) {
JsName setterName = getNotNullSetterName(expression);
- JsNameRef setterReference = Translation.generateCorrectReference(context(), expression, setterName);
+ JsNameRef setterReference = ReferenceProvider.getReference(setterName, context(), expression);
return AstUtil.newInvocation(setterReference);
}
diff --git a/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java b/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java
index 1262f7f2ad8be..7e4e57f1676fa 100644
--- a/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java
+++ b/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java
@@ -17,16 +17,29 @@ public final class ReferenceProvider {
private final TranslationContext context;
@NotNull
private final JsName referencedName;
+ private boolean isBackingFieldAccess;
private boolean requiresThisQualifier;
private boolean requiresNamespaceQualifier;
+ public static JsNameRef getReference(@NotNull JsName referencedName, @NotNull TranslationContext context,
+ boolean isBackingFieldAccess) {
+ return (new ReferenceProvider(referencedName, context, isBackingFieldAccess)).generateCorrectReference();
+ }
+
+
+ public static JsNameRef getReference(@NotNull JsName referencedName, @NotNull TranslationContext context,
+ JetSimpleNameExpression expression) {
+ boolean isBackingFieldAccess = expression.getReferencedNameElementType() == JetTokens.FIELD_IDENTIFIER;
+ return (new ReferenceProvider(referencedName, context, isBackingFieldAccess))
+ .generateCorrectReference();
+ }
- public ReferenceProvider(@NotNull TranslationContext context,
- @NotNull JetSimpleNameExpression expression,
- @NotNull JsName referencedName) {
+ private ReferenceProvider(@NotNull JsName referencedName, @NotNull TranslationContext context,
+ boolean isBackingFieldAccess) {
this.context = context;
this.referencedName = referencedName;
- this.requiresThisQualifier = requiresThisQualifier(expression);
+ this.isBackingFieldAccess = isBackingFieldAccess;
+ this.requiresThisQualifier = requiresThisQualifier();
this.requiresNamespaceQualifier = requiresNamespaceQualifier();
}
@@ -44,10 +57,9 @@ private boolean requiresNamespaceQualifier() {
return context.namespaceScope().ownsName(referencedName);
}
- private boolean requiresThisQualifier(@NotNull JetSimpleNameExpression expression) {
+ private boolean requiresThisQualifier() {
JsName name = context.enclosingScope().findExistingName(referencedName.getIdent());
boolean isClassMember = context.classScope().ownsName(name);
- boolean isBackingFieldAccess = expression.getReferencedNameElementType() == JetTokens.FIELD_IDENTIFIER;
return isClassMember || isBackingFieldAccess;
}
}
diff --git a/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java b/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java
index e474a95066550..9dd63d6753247 100644
--- a/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java
+++ b/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java
@@ -66,7 +66,7 @@ private JsExpression resolveAsGlobalReference(@NotNull JetSimpleNameExpression e
return null;
}
JsName referencedName = context().getNameForDescriptor(referencedDescriptor);
- return TranslationUtils.getReference(context(), expression, referencedName);
+ return ReferenceProvider.getReference(referencedName, context(), expression);
}
@Nullable
diff --git a/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java b/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java
index 2b48825fb9add..26ec095bc35e5 100644
--- a/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java
+++ b/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java
@@ -7,7 +7,6 @@
import org.jetbrains.jet.lang.descriptors.PropertyDescriptor;
import org.jetbrains.jet.lang.psi.JetExpression;
import org.jetbrains.jet.lang.psi.JetProperty;
-import org.jetbrains.jet.lang.psi.JetSimpleNameExpression;
import org.jetbrains.jet.lang.psi.ValueArgument;
import org.jetbrains.k2js.translate.general.Translation;
import org.jetbrains.k2js.translate.general.TranslationContext;
@@ -35,14 +34,6 @@ static public JsBinaryOperation isNullCheck(@NotNull TranslationContext context,
return AstUtil.equals(expressionToCheck, nullLiteral);
}
- @NotNull
- static public JsNameRef getReference(@NotNull TranslationContext context,
- @NotNull JetSimpleNameExpression expression,
- @NotNull JsName referencedName) {
- return (new ReferenceProvider(context, expression, referencedName)).generateCorrectReference();
- }
-
-
@Nullable
static public JsName getLocalReferencedName(@NotNull TranslationContext context,
@NotNull String name) {
@@ -69,25 +60,24 @@ static public JsExpression translateArgument(@NotNull TranslationContext context
return Translation.translateAsExpression(jetExpression, context);
}
- //TODO: refactor
@NotNull
static public JsNameRef backingFieldReference(@NotNull TranslationContext context,
@NotNull JetProperty expression) {
JsName backingFieldName = getBackingFieldName(getPropertyName(expression), context);
- if (BindingUtils.belongsToNamespace(context.bindingContext(), expression)) {
- return context.getNamespaceQualifiedReference(backingFieldName);
- }
- return AstUtil.thisQualifiedReference(backingFieldName);
+ return generateReference(context, backingFieldName);
}
@NotNull
static public JsNameRef backingFieldReference(@NotNull TranslationContext context,
@NotNull PropertyDescriptor descriptor) {
JsName backingFieldName = getBackingFieldName(descriptor.getName(), context);
- if (BindingUtils.belongsToNamespace(context.bindingContext(), descriptor)) {
- return context.getNamespaceQualifiedReference(backingFieldName);
- }
- return AstUtil.thisQualifiedReference(backingFieldName);
+ return generateReference(context, backingFieldName);
+ }
+
+ @NotNull
+ private static JsNameRef generateReference(@NotNull TranslationContext context,
+ @NotNull JsName backingFieldName) {
+ return ReferenceProvider.getReference(backingFieldName, context, true);
}
@NotNull
@@ -100,7 +90,8 @@ static public String getPropertyName(@NotNull JetProperty expression) {
}
@NotNull
- static private JsName getBackingFieldName(@NotNull String propertyName, @NotNull TranslationContext context) {
+ static private JsName getBackingFieldName(@NotNull String propertyName,
+ @NotNull TranslationContext context) {
String backingFieldName = Namer.getKotlinBackingFieldName(propertyName);
return context.enclosingScope().findExistingName(backingFieldName);
}
|
aded57f8faa5c23934839ac6b44e1376ea99c07b
|
Delta Spike
|
DELTASPIKE-289 windowId detection code with JavaScript and intermediate page
partly ported over from MyFaces CODI, partly rewritten.
Passing the windowId via hidden input field
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponent.java
similarity index 91%
rename from deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java
rename to deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponent.java
index e4f73268b..4ec76c50b 100644
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponent.java
@@ -16,8 +16,9 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.deltaspike.jsf.impl.scope.window;
+package org.apache.deltaspike.jsf.impl.component.window;
+import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponent;
import javax.faces.component.UIOutput;
import javax.faces.component.UIViewRoot;
@@ -32,8 +33,11 @@
* We store this component as direct child in the ViewRoot
* and evaluate it's value on postbacks.
*/
+@FacesComponent(WindowIdHolderComponent.COMPONENT_TYPE)
public class WindowIdHolderComponent extends UIOutput
{
+ public static final String COMPONENT_TYPE = "org.apache.deltaspike.WindowIdHolder";
+
private static final Logger logger = Logger.getLogger(WindowIdHolderComponent.class.getName());
private String windowId;
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponentHtmlRenderer.java
similarity index 53%
rename from deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java
rename to deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponentHtmlRenderer.java
index bb939d516..ff3193303 100644
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponentHtmlRenderer.java
@@ -16,64 +16,57 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.deltaspike.jsf.impl.scope.window;
+package org.apache.deltaspike.jsf.impl.component.window;
+import javax.faces.application.ResourceDependencies;
+import javax.faces.application.ResourceDependency;
+import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
-import javax.faces.render.RenderKit;
-import javax.faces.render.RenderKitWrapper;
-import java.io.Writer;
+import javax.faces.render.FacesRenderer;
+import javax.faces.render.Renderer;
+import java.io.IOException;
import org.apache.deltaspike.core.api.provider.BeanProvider;
import org.apache.deltaspike.core.spi.scope.window.WindowContext;
+
/**
- * Wraps the RenderKit and adds the
- * {@link WindowIdHolderComponent} to the view tree
+ * HtmlRenderer for our dsWindowId hidden field.
+ * This gets used for post requests.
*/
-public class WindowIdRenderKitWrapper extends RenderKitWrapper
+@FacesRenderer(componentFamily = WindowIdHolderComponent.COMPONENT_FAMILY,
+ rendererType = WindowIdHolderComponent.COMPONENT_TYPE)
+@ResourceDependencies( {
+ @ResourceDependency(library = "js", name = "windowhandler.js", target = "head"),
+ @ResourceDependency(library = "javax.faces", name = "jsf.js", target = "head") } )
+public class WindowIdHolderComponentHtmlRenderer extends Renderer
{
- private final RenderKit wrapped;
-
- /**
- * This will get initialized lazily to prevent boot order issues
- * with the JSF and CDI containers.
- */
private volatile WindowContext windowContext;
- //needed if the renderkit gets proxied - see EXTCDI-215
- protected WindowIdRenderKitWrapper()
- {
- this.wrapped = null;
- }
-
- public WindowIdRenderKitWrapper(RenderKit wrapped)
- {
- this.wrapped = wrapped;
- }
-
- @Override
- public RenderKit getWrapped()
- {
- return wrapped;
- }
-
/**
- * Adds a {@link WindowIdHolderComponent} with the
- * current windowId to the component tree.
+ * Write a simple hidden field into the form.
+ * This might change in the future...
+ * @param context
+ * @param component
+ * @throws IOException
*/
- public ResponseWriter createResponseWriter(Writer writer, String s, String s1)
+ @Override
+ public void encodeBegin(FacesContext context, UIComponent component) throws IOException
{
- FacesContext facesContext = FacesContext.getCurrentInstance();
+ super.encodeBegin(context, component);
+
String windowId = getWindowContext().getCurrentWindowId();
- WindowIdHolderComponent.addWindowIdHolderComponent(facesContext, windowId);
+ ResponseWriter writer = context.getResponseWriter();
+ writer.startElement("script", component);
+ writer.writeAttribute("type", "text/javascript", null);
+ writer.write("window.deltaspikeJsWindowId=" + windowId + ";");
- return wrapped.createResponseWriter(writer, s, s1);
+ writer.endElement("script");
}
-
private WindowContext getWindowContext()
{
if (windowContext == null)
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
index 3ea94788a..31185029f 100644
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
@@ -20,7 +20,6 @@
import javax.enterprise.context.ApplicationScoped;
import javax.faces.FacesException;
-import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
@@ -29,6 +28,8 @@
import java.io.IOException;
import java.io.OutputStream;
+import java.util.Map;
+import java.util.Random;
import java.util.logging.Logger;
import org.apache.deltaspike.core.spi.scope.window.WindowContext;
@@ -51,8 +52,26 @@
@ApplicationScoped
public class DefaultClientWindow implements ClientWindow
{
+
+ /**
+ * Value which can be used as "window-id" by external clients which aren't aware of windows.
+ * It deactivates e.g. the redirect for the initial request.
+ */
+ public static final String AUTOMATED_ENTRY_POINT_PARAMETER_KEY = "automatedEntryPoint";
+
+ /**
+ * The parameter for the windowId for GET requests
+ */
+ public static final String DELTASPIKE_WINDOW_ID_PARAM = "windowId";
+
+ /**
+ * The parameter for the windowId for POST requests
+ */
+ public static final String DELTASPIKE_WINDOW_ID_POST_PARAM = "dsPostWindowId";
+
private static final Logger logger = Logger.getLogger(DefaultClientWindow.class.getName());
+
private static final String WINDOW_ID_COOKIE_PREFIX = "dsWindowId-";
private static final String DELTASPIKE_REQUEST_TOKEN = "dsRid";
@@ -60,6 +79,7 @@ public class DefaultClientWindow implements ClientWindow
private static final String WINDOW_ID_REPLACE_PATTERN = "$$windowIdValue$$";
private static final String NOSCRIPT_URL_REPLACE_PATTERN = "$$noscriptUrl$$";
+
/**
* Use this parameter to force a 'direct' request from the clients without any windowId detection
* We keep this name for backward compat with CODI.
@@ -106,10 +126,19 @@ public String getWindowId(FacesContext facesContext)
}
String windowId = getVerifiedWindowIdFromCookie(externalContext);
- if (windowId == null)
+
+ boolean newWindowIdRequested = false;
+ if (AUTOMATED_ENTRY_POINT_PARAMETER_KEY.equals(windowId))
+ {
+ // this is a marker for generating a new windowId
+ windowId = generateNewWindowId();
+ newWindowIdRequested = true;
+ }
+
+ if (windowId == null || newWindowIdRequested)
{
// GET request without windowId - send windowhandlerfilter.html to get the windowId
- sendWindowHandlerHtml(externalContext, null);
+ sendWindowHandlerHtml(externalContext, windowId);
facesContext.responseComplete();
}
@@ -117,24 +146,24 @@ public String getWindowId(FacesContext facesContext)
return windowId;
}
+ /**
+ * Create a unique windowId
+ * @return
+ */
+ private String generateNewWindowId()
+ {
+ //X TODO proper mechanism
+ return "" + (new Random()).nextInt() % 10000;
+ }
+
/**
* Extract the windowId for http POST
*/
private String getPostBackWindowId(FacesContext facesContext)
{
- UIViewRoot uiViewRoot = facesContext.getViewRoot();
-
- if (uiViewRoot != null)
- {
- WindowIdHolderComponent existingWindowIdHolder
- = WindowIdHolderComponent.getWindowIdHolderComponent(uiViewRoot);
- if (existingWindowIdHolder != null)
- {
- return existingWindowIdHolder.getWindowId();
- }
- }
-
- return null;
+ Map<String, String> requestParams = facesContext.getExternalContext().getRequestParameterMap();
+ String windowId = requestParams.get(DELTASPIKE_WINDOW_ID_POST_PARAM);
+ return windowId;
}
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java
deleted file mode 100644
index 883ddb022..000000000
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * 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.deltaspike.jsf.impl.scope.window;
-
-import javax.faces.context.FacesContext;
-import javax.faces.render.RenderKit;
-import javax.faces.render.RenderKitFactory;
-import java.util.Iterator;
-
-import org.apache.deltaspike.core.spi.activation.Deactivatable;
-import org.apache.deltaspike.core.util.ClassDeactivationUtils;
-
-
-/**
- * Registers the @{link WindowIdRenderKit}
- */
-public class WindowIdRenderKitFactory extends RenderKitFactory implements Deactivatable
-{
- private final RenderKitFactory wrapped;
-
- private final boolean deactivated;
-
- /**
- * Constructor for wrapping the given {@link javax.faces.render.RenderKitFactory}
- * @param wrapped render-kit-factory which will be wrapped
- */
- public WindowIdRenderKitFactory(RenderKitFactory wrapped)
- {
- this.wrapped = wrapped;
- this.deactivated = !isActivated();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void addRenderKit(String s, RenderKit renderKit)
- {
- wrapped.addRenderKit(s, renderKit);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public RenderKit getRenderKit(FacesContext facesContext, String s)
- {
- RenderKit renderKit = wrapped.getRenderKit(facesContext, s);
-
- if (renderKit == null)
- {
- return null;
- }
-
- if (deactivated)
- {
- return renderKit;
- }
-
- return new WindowIdRenderKitWrapper(renderKit);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Iterator<String> getRenderKitIds()
- {
- return wrapped.getRenderKitIds();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public RenderKitFactory getWrapped()
- {
- return wrapped;
- }
-
- public boolean isActivated()
- {
- return ClassDeactivationUtils.isActivated(getClass());
- }
-}
diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/deltaspike.taglib.xml b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/deltaspike.taglib.xml
new file mode 100644
index 000000000..947063f16
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/deltaspike.taglib.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
+ version="2.0">
+ <namespace>http://deltaspike.apache.org/jsf</namespace>
+
+ <tag>
+ <tag-name>windowId</tag-name>
+ <component>
+ <component-type>org.apache.deltaspike.WindowIdHolder</component-type>
+ <renderer-type>org.apache.deltaspike.WindowIdHolder</renderer-type>
+ </component>
+ </tag>
+</facelet-taglib>
diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
index 8b7b43a7e..de8ef13d4 100644
--- a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
+++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
@@ -37,6 +37,6 @@
<factory>
<lifecycle-factory>org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeLifecycleFactoryWrapper</lifecycle-factory>
<faces-context-factory>org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeFacesContextFactory</faces-context-factory>
- <render-kit-factory>org.apache.deltaspike.jsf.impl.scope.window.WindowIdRenderKitFactory</render-kit-factory>
</factory>
+
</faces-config>
diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js
index b563b3120..c7f6bca2a 100644
--- a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js
+++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js
@@ -73,28 +73,43 @@ function equalsIgnoreCase(source, destination) {
}
/** This method will be called onWindowLoad and after AJAX success */
-function applyOnClick() {
- var links = document.getElementsByTagName("a");
- for (var i = 0; i < links.length; i++) {
- if (!links[i].onclick) {
- links[i].onclick = function() {storeWindowTree(); return true;};
- } else {
- // prevent double decoration
- if (!("" + links[i].onclick).match(".*storeWindowTree().*")) {
- //the function wrapper is important otherwise the
- //last onclick handler would be assigned to oldonclick
- (function storeEvent() {
- var oldonclick = links[i].onclick;
- links[i].onclick = function(evt) {
- //ie handling added
- evt = evt || window.event;
+function applyWindowId() {
+ if (isHtml5()) { // onClick handling
+ var links = document.getElementsByTagName("a");
+ for (var i = 0; i < links.length; i++) {
+ if (!links[i].onclick) {
+ links[i].onclick = function() {storeWindowTree(); return true;};
+ } else {
+ // prevent double decoration
+ if (!("" + links[i].onclick).match(".*storeWindowTree().*")) {
+ //the function wrapper is important otherwise the
+ //last onclick handler would be assigned to oldonclick
+ (function storeEvent() {
+ var oldonclick = links[i].onclick;
+ links[i].onclick = function(evt) {
+ //ie handling added
+ evt = evt || window.event;
- return storeWindowTree() && oldonclick(evt);
- };
- })();
+ return storeWindowTree() && oldonclick(evt);
+ };
+ })();
+ }
}
}
}
+ var forms = document.getElementsByTagName("form");
+ for (var i = 0; i < forms.length; i++) {
+ var form = forms[i];
+ var windowIdHolder = form.elements["dsPostWindowId"];
+ if (!windowIdHolder) {
+ windowIdHolder = document.createElement("INPUT");
+ windowIdHolder.name = "dsPostWindowId";
+ windowIdHolder.type = "hidden";
+ form.appendChild(windowIdHolder);
+ }
+
+ windowIdHolder.value = window.deltaspikeJsWindowId;
+ }
}
function getUrlParameter(name) {
@@ -159,7 +174,7 @@ function eraseRequestCookie() {
var ajaxOnClick = function ajaxDecorateClick(event) {
if (event.status=="success") {
- applyOnClick();
+ applyWindowId();
}
}
@@ -171,10 +186,8 @@ window.onload = function(evt) {
} finally {
eraseRequestCookie(); // manually erase the old dsRid cookie because Firefox doesn't do it properly
assertWindowId();
- if (isHtml5()) {
- applyOnClick();
- jsf.ajax.addOnEvent(ajaxOnClick);
- }
+ applyWindowId();
+ jsf.ajax.addOnEvent(ajaxOnClick);
}
}
})();
diff --git a/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html b/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html
index c0967228f..30e622ad3 100644
--- a/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html
+++ b/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html
@@ -135,29 +135,35 @@
replaceContent();
window.onload = function() {
+ // uncomment the following line to debug the intermediate page
+ // if (!confirm('reload?')) { return true; }
+
loadCss(true);
// this will be replaced in the phase listener
- var windowId = '$$windowIdValue$$';
- if (windowId == 'uninitializedWindowId') {
- windowId = window.name
- }
+ var windowId = window.name;
+ var urlId = windowId;
if (!windowId || windowId.length < 1) {
- // request a new windowId
- windowId = 'automatedEntryPoint';
+ var newWindowId = '$$windowIdValue$$';
+ if (newWindowId != 'uninitializedWindowId') {
+ window.name = newWindowId; // set the window.name with our windowId
+ windowId = newWindowId;
+ urlId = windowId;
+ }
+ else {
+ windowId = 'automatedEntryPoint';
+ urlId = null;
+ }
}
- window.name = windowId;
-
- // uncomment the following line to debug the intermediate page
- // if (!confirm('reload?')) { return true; }
-
// 3 seconds expiry time
var expdt = new Date();
expdt.setTime(expdt.getTime()+(3*1000));
var expires = "; expires="+expdt.toGMTString();
- var requestToken = Math.floor(Math.random()*1001);
+ var requestToken = Math.floor(Math.random()*999);
var newUrl = setUrlParam(window.location.href, "dsRid", requestToken);
+
+ // we still add hte windowId page param to support lazy windowId dropping for some clients
newUrl = setUrlParam(newUrl, "windowId", windowId);
document.cookie = 'dsWindowId-' + requestToken + '=' + windowId + expires+"; path=/";
diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java
new file mode 100644
index 000000000..6f84fe88e
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java
@@ -0,0 +1,99 @@
+/*
+ * 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.deltaspike.test.jsf.impl.scope.window;
+
+
+import java.net.URL;
+
+import org.apache.deltaspike.test.category.WebProfileCategory;
+import org.apache.deltaspike.test.jsf.impl.scope.window.beans.WindowScopedBackingBean;
+import org.apache.deltaspike.test.jsf.impl.util.ArchiveUtils;
+import org.jboss.arquillian.container.test.api.Deployment;
+import org.jboss.arquillian.container.test.api.RunAsClient;
+import org.jboss.arquillian.drone.api.annotation.Drone;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.arquillian.test.api.ArquillianResource;
+import org.jboss.arquillian.warp.WarpTest;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.asset.EmptyAsset;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.support.ui.ExpectedConditions;
+
+
+/**
+ * Test for the DeltaSpike JsfMessage Producer
+ */
+@WarpTest
+@RunWith(Arquillian.class)
+@Category(WebProfileCategory.class)
+public class WindowScopedContextTest
+{
+ @Drone
+ private WebDriver driver;
+
+ @ArquillianResource
+ private URL contextPath;
+
+ @Deployment
+ public static WebArchive deploy()
+ {
+ return ShrinkWrap
+ .create(WebArchive.class, "windowScopedContextTest.war")
+ .addPackage(WindowScopedBackingBean.class.getPackage())
+ .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndJsfArchive())
+ .addAsLibraries(ArchiveUtils.getDeltaSpikeSecurityArchive())
+ .addAsWebInfResource("default/WEB-INF/web.xml", "web.xml")
+ .addAsWebResource("META-INF/resources/js/windowhandler.js", "resources/js/windowhandler.js")
+ .addAsWebResource("windowScopedContextTest/page.xhtml", "page.xhtml")
+ .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
+ }
+
+
+ @Test
+ @RunAsClient
+ public void testWindowId() throws Exception
+ {
+ System.out.println("contextpath= " + contextPath);
+ //X Thread.sleep(600000L);
+
+ driver.get(new URL(contextPath, "page.xhtml").toString());
+
+ //X comment this in if you like to debug the server
+ //X I've already reported ARQGRA-213 for it
+ //X
+
+ WebElement inputField = driver.findElement(By.id("test:valueInput"));
+ inputField.sendKeys("23");
+
+ WebElement button = driver.findElement(By.id("test:saveButton"));
+ button.click();
+
+ Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("test:valueOutput"), "23").apply(driver));
+
+ }
+
+
+}
diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/beans/WindowScopedBackingBean.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/beans/WindowScopedBackingBean.java
new file mode 100644
index 000000000..8a58d483f
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/beans/WindowScopedBackingBean.java
@@ -0,0 +1,50 @@
+/*
+* 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.deltaspike.test.jsf.impl.scope.window.beans;
+
+import javax.inject.Named;
+import java.io.Serializable;
+
+import org.apache.deltaspike.core.api.scope.WindowScoped;
+
+/**
+ * WindowScoped sample backing bean.
+ */
+@WindowScoped
+@Named("windowScopedBean")
+public class WindowScopedBackingBean implements Serializable
+{
+ private int i = 0;
+
+ public int getI()
+ {
+ return i;
+ }
+
+ public void setI(int i)
+ {
+ this.i = i;
+ }
+
+ public String someAction()
+ {
+ // stay on the page.
+ return null;
+ }
+}
diff --git a/deltaspike/modules/jsf/impl/src/test/resources/windowScopedContextTest/page.xhtml b/deltaspike/modules/jsf/impl/src/test/resources/windowScopedContextTest/page.xhtml
new file mode 100644
index 000000000..c0a64c4c6
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/test/resources/windowScopedContextTest/page.xhtml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"
+ xmlns:h="http://java.sun.com/jsf/html"
+ xmlns:f="http://java.sun.com/jsf/core"
+ xmlns:ui="http://java.sun.com/jsf/facelets"
+ xmlns:c="http://java.sun.com/jsp/jstl/core"
+ xmlns:ds="http://deltaspike.apache.org/jsf">
+
+<h:head>
+
+</h:head>
+
+<h:body>
+<ds:windowId/>
+<div>
+ <h:form id="test">
+ <h:outputLabel for="valueInput" value="WindowScoped value:"/>
+ <h:inputText id="valueInput" value="#{windowScopedBean.i}"/>
+ <br/>
+ <h:outputLabel for="valueOutput" value="backing bean value:"/>
+ <h:outputText id="valueOutput" value="#{windowScopedBean.i}"/>
+ <br/>
+ <h:commandButton id="saveButton" action="#{windowScopedBean.someAction}" value="save"/>
+ </h:form>
+</div>
+</h:body>
+</html>
|
de9c73d84625565731b5b92f0534ca1a09b032df
|
Delta Spike
|
DELTASPIKE-157 log Test Class for @Deployment
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/ShrinkWrapArchiveUtil.java b/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/ShrinkWrapArchiveUtil.java
index edece79cf..8e445f6f7 100644
--- a/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/ShrinkWrapArchiveUtil.java
+++ b/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/ShrinkWrapArchiveUtil.java
@@ -45,6 +45,7 @@
public class ShrinkWrapArchiveUtil
{
private static final Logger LOG = Logger.getLogger(ShrinkWrapArchiveUtil.class.getName());
+ private static String testName;
private ShrinkWrapArchiveUtil()
{
@@ -54,8 +55,9 @@ private ShrinkWrapArchiveUtil()
/**
* Resolve all markerFiles from the current ClassPath and package the root nodes
* into a JavaArchive.
- * @param classLoader to use
- * @param markerFile finding this marker file will trigger creating the JavaArchive.
+ *
+ * @param classLoader to use
+ * @param markerFile finding this marker file will trigger creating the JavaArchive.
* @param includeIfPackageExists if not null, we will only create JavaArchives if the given package exists
* @param excludeIfPackageExists if not null, we will <b>not</b> create JavaArchives if the given package exists.
* This has a higher precedence than includeIfPackageExists.
@@ -85,7 +87,8 @@ public static JavaArchive[] getArchives(ClassLoader classLoader,
= createArchive(foundFile, markerFile, includeIfPackageExists, excludeIfPackageExists);
if (archive != null)
{
- LOG.info("Adding Java ClassPath URL as JavaArchive " + foundFile.toExternalForm());
+ LOG.info("Test " + getTestName()
+ + " Adding Java ClassPath URL as JavaArchive " + foundFile.toExternalForm());
archives.add(archive);
}
}
@@ -366,4 +369,19 @@ private static String pathToClassName(String pathName)
}
+ public static String getTestName()
+ {
+ StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
+ String testName = "unknown";
+ for (StackTraceElement ste : stackTraceElements)
+ {
+ if (ste.getClassName().contains("Test"))
+ {
+ testName = ste.getClassName();
+ break;
+ }
+ }
+
+ return testName;
+ }
}
|
2a590b78e4c9e814faa61457a04ec4f5f2c9a176
|
orientdb
|
Distributed: fixed issue -2008 on deploying- database--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedDatabase.java b/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedDatabase.java
index 693ea430372..756b5bf021b 100644
--- a/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedDatabase.java
+++ b/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedDatabase.java
@@ -23,7 +23,6 @@
import com.orientechnologies.orient.core.db.OScenarioThreadLocal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal.RUN_MODE;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
-import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.server.config.OServerUserConfiguration;
import com.orientechnologies.orient.server.distributed.*;
import com.orientechnologies.orient.server.distributed.ODistributedRequest.EXECUTION_MODE;
@@ -533,9 +532,7 @@ protected void checkLocalNodeInConfiguration() {
}
if (dirty) {
- final ODocument doc = cfg.serialize();
- manager.updateCachedDatabaseConfiguration(databaseName, doc);
- manager.getConfigurationMap().put(OHazelcastPlugin.CONFIG_DATABASE_PREFIX + databaseName, doc);
+ manager.updateCachedDatabaseConfiguration(databaseName, cfg.serialize(), true, true);
}
}
@@ -573,9 +570,7 @@ protected void removeNodeInConfiguration(final String iNode, final boolean iForc
}
if (dirty) {
- final ODocument doc = cfg.serialize();
- manager.updateCachedDatabaseConfiguration(databaseName, doc);
- manager.getConfigurationMap().put(OHazelcastPlugin.CONFIG_DATABASE_PREFIX + databaseName, doc);
+ manager.updateCachedDatabaseConfiguration(databaseName, cfg.serialize(), true, true);
}
}
diff --git a/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastPlugin.java b/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastPlugin.java
index e6d399d7a38..39964738933 100755
--- a/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastPlugin.java
+++ b/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastPlugin.java
@@ -470,7 +470,7 @@ public void entryAdded(EntryEvent<String, Object> iEvent) {
}
} else if (key.startsWith(CONFIG_DATABASE_PREFIX)) {
- saveDatabaseConfiguration(key.substring(CONFIG_DATABASE_PREFIX.length()), (ODocument) iEvent.getValue());
+ updateCachedDatabaseConfiguration(key.substring(CONFIG_DATABASE_PREFIX.length()), (ODocument) iEvent.getValue(), true, false);
OClientConnectionManager.instance().pushDistribCfg2Clients(getClusterConfiguration());
}
}
@@ -493,7 +493,7 @@ public void entryUpdated(EntryEvent<String, Object> iEvent) {
getNodeName(iEvent.getMember()));
installNewDatabases(false);
- saveDatabaseConfiguration(dbName, (ODocument) iEvent.getValue());
+ updateCachedDatabaseConfiguration(dbName, (ODocument) iEvent.getValue(), true, false);
OClientConnectionManager.instance().pushDistribCfg2Clients(getClusterConfiguration());
}
}
@@ -671,15 +671,20 @@ protected void installNewDatabases(final boolean iStartup) {
ODistributedDatabaseChunk chunk = (ODistributedDatabaseChunk) value;
final String fileName = System.getProperty("java.io.tmpdir") + "/orientdb/install_" + databaseName + ".zip";
+
+ ODistributedServerLog.warn(this, getLocalNodeName(), r.getKey(), DIRECTION.NONE,
+ "copying remote database '%s' to: %s", databaseName, fileName);
+
final File file = new File(fileName);
if (file.exists())
file.delete();
+ FileOutputStream out = null;
try {
- final FileOutputStream out = new FileOutputStream(fileName, false);
+ out = new FileOutputStream(fileName, false);
- out.write(chunk.buffer);
- for (int chunkNum = 1; !chunk.last; chunkNum++) {
+ long fileSize = writeDatabaseChunk(1, chunk, out);
+ for (int chunkNum = 2; !chunk.last; chunkNum++) {
distrDatabase.setWaitForTaskType(OCopyDatabaseChunkTask.class);
final Map<String, Object> result = (Map<String, Object>) sendRequest(databaseName, null,
@@ -691,14 +696,25 @@ protected void installNewDatabases(final boolean iStartup) {
continue;
else {
chunk = (ODistributedDatabaseChunk) res.getValue();
- out.write(chunk.buffer);
+ fileSize += writeDatabaseChunk(chunkNum, chunk, out);
}
}
}
+ ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE,
+ "database copied correctly, size=%s", OFileUtils.getSizeAsString(fileSize));
+
} catch (Exception e) {
ODistributedServerLog.error(this, getLocalNodeName(), null, DIRECTION.NONE,
"error on transferring database '%s' to '%s'", e, databaseName, fileName);
+ } finally {
+ try {
+ if (out != null) {
+ out.flush();
+ out.close();
+ }
+ } catch (IOException e) {
+ }
}
installDatabase(distrDatabase, databaseName, dbPath, r.getKey(), fileName);
@@ -720,29 +736,51 @@ protected void installNewDatabases(final boolean iStartup) {
}
}
- private void installDatabase(final OHazelcastDistributedDatabase distrDatabase, final String databaseName, final String dbPath,
+ public void updateCachedDatabaseConfiguration(String iDatabaseName, ODocument cfg, boolean iSaveToDisk, boolean iDeployToCluster) {
+ super.updateCachedDatabaseConfiguration(iDatabaseName, cfg, iSaveToDisk);
+
+ if (iDeployToCluster)
+ // DEPLOY THE CONFIGURATION TO THE CLUSTER
+ getConfigurationMap().put(OHazelcastPlugin.CONFIG_DATABASE_PREFIX + iDatabaseName, cfg);
+ }
+
+ protected long writeDatabaseChunk(final int iChunkId, final ODistributedDatabaseChunk chunk, final FileOutputStream out)
+ throws IOException {
+
+ ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "- writing chunk #%d offset=%d size=%s", iChunkId,
+ chunk.offset, OFileUtils.getSizeAsString(chunk.buffer.length));
+ out.write(chunk.buffer);
+
+ return chunk.buffer.length;
+ }
+
+ protected void installDatabase(final OHazelcastDistributedDatabase distrDatabase, final String databaseName, final String dbPath,
final String iNode, final String iDatabaseCompressedFile) {
- ODistributedServerLog.warn(this, getLocalNodeName(), iNode, DIRECTION.IN, "installing database %s in %s...", databaseName,
+ ODistributedServerLog.warn(this, getLocalNodeName(), iNode, DIRECTION.IN, "installing database '%s' to: %s...", databaseName,
dbPath);
try {
- final FileInputStream in = new FileInputStream(iDatabaseCompressedFile);
+ File f = new File(iDatabaseCompressedFile);
new File(dbPath).mkdirs();
final ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:" + dbPath);
- db.restore(in, null, null);
- in.close();
+ final FileInputStream in = new FileInputStream(f);
+ try {
+ db.restore(in, null, null);
+ } finally {
+ in.close();
+ }
db.close();
Orient.instance().unregisterStorageByName(db.getName());
- ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE,
- "installed database %s in %s, setting it online...", databaseName, dbPath);
+ ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "installed database '%s', setting it online...",
+ databaseName);
distrDatabase.setOnline();
- ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "database %s is online", databaseName);
+ ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "database '%s' is online", databaseName);
} catch (IOException e) {
ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.IN, "error on copying database '%s' on local server", e,
@@ -759,7 +797,7 @@ protected ODocument loadDatabaseConfiguration(final String iDatabaseName, final
ODistributedServerLog.info(this, getLocalNodeName(), null, DIRECTION.NONE,
"loaded database configuration from active cluster");
- updateCachedDatabaseConfiguration(iDatabaseName, cfg);
+ updateCachedDatabaseConfiguration(iDatabaseName, cfg, false, false);
return cfg;
}
}
diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedAbstractPlugin.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedAbstractPlugin.java
index 3c3b2797e7b..4282649d130 100755
--- a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedAbstractPlugin.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedAbstractPlugin.java
@@ -15,14 +15,6 @@
*/
package com.orientechnologies.orient.server.distributed;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.parser.OSystemVariableResolver;
import com.orientechnologies.orient.core.Orient;
@@ -38,6 +30,14 @@
import com.orientechnologies.orient.server.distributed.conflict.OReplicationConflictResolver;
import com.orientechnologies.orient.server.plugin.OServerPluginAbstract;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* Abstract plugin to manage the distributed environment.
*
@@ -197,7 +197,7 @@ protected ODocument loadDatabaseConfiguration(final String iDatabaseName, final
f.read(buffer);
final ODocument doc = (ODocument) new ODocument().fromJSON(new String(buffer), "noMap");
- updateCachedDatabaseConfiguration(iDatabaseName, doc);
+ updateCachedDatabaseConfiguration(iDatabaseName, doc, false);
return doc;
} catch (Exception e) {
@@ -211,12 +211,51 @@ protected ODocument loadDatabaseConfiguration(final String iDatabaseName, final
return null;
}
- public void updateCachedDatabaseConfiguration(final String iDatabaseName, final ODocument cfg) {
+ public void updateCachedDatabaseConfiguration(final String iDatabaseName, final ODocument cfg, final boolean iSaveToDisk) {
synchronized (cachedDatabaseConfiguration) {
+ final ODocument oldCfg = cachedDatabaseConfiguration.get(iDatabaseName);
+ if (oldCfg != null && (oldCfg == cfg || Arrays.equals(oldCfg.toStream(), cfg.toStream())))
+ // NO CHANGE, SKIP IT
+ return;
+
+ // INCREMENT VERSION
+ Integer oldVersion = cfg.field("version");
+ if (oldVersion == null)
+ oldVersion = 0;
+ cfg.field("version", oldVersion.intValue() + 1);
+
+ // SAVE IN NODE'S LOCAL RAM
cachedDatabaseConfiguration.put(iDatabaseName, cfg);
+ // PRINT THE NEW CONFIGURATION
OLogManager.instance().info(this, "updated distributed configuration for database: %s:\n----------\n%s\n----------",
iDatabaseName, cfg.toJSON("prettyPrint"));
+
+ if (iSaveToDisk) {
+ // SAVE THE CONFIGURATION TO DISK
+ FileOutputStream f = null;
+ try {
+ File file = getDistributedConfigFile(iDatabaseName);
+
+ OLogManager.instance().info(this, "Saving distributed configuration file for database '%s' to: %s", iDatabaseName, file);
+
+ if (!file.exists())
+ file.createNewFile();
+
+ f = new FileOutputStream(file);
+ f.write(cfg.toJSON().getBytes());
+ f.flush();
+ } catch (Exception e) {
+ OLogManager.instance().error(this, "Error on saving distributed configuration file", e);
+
+ } finally {
+ if (f != null)
+ try {
+ f.close();
+ } catch (IOException e) {
+ }
+ }
+ }
}
}
@@ -235,42 +274,6 @@ public ODistributedConfiguration getDatabaseConfiguration(final String iDatabase
}
}
- protected void saveDatabaseConfiguration(final String iDatabaseName, final ODocument cfg) {
- synchronized (cachedDatabaseConfiguration) {
- final ODocument oldCfg = cachedDatabaseConfiguration.get(iDatabaseName);
- if (oldCfg != null && Arrays.equals(oldCfg.toStream(), cfg.toStream()))
- // NO CHANGE, SKIP IT
- return;
- }
-
- // INCREMENT VERSION
- Integer oldVersion = cfg.field("version");
- if (oldVersion == null)
- oldVersion = 0;
- cfg.field("version", oldVersion.intValue() + 1);
-
- updateCachedDatabaseConfiguration(iDatabaseName, cfg);
-
- FileOutputStream f = null;
- try {
- File file = getDistributedConfigFile(iDatabaseName);
-
- OLogManager.instance().config(this, "Saving distributed configuration file for database '%s' in: %s", iDatabaseName, file);
-
- f = new FileOutputStream(file);
- f.write(cfg.toJSON().getBytes());
- } catch (Exception e) {
- OLogManager.instance().error(this, "Error on saving distributed configuration file", e);
-
- } finally {
- if (f != null)
- try {
- f.close();
- } catch (IOException e) {
- }
- }
- }
-
public File getDistributedConfigFile(final String iDatabaseName) {
return new File(serverInstance.getDatabaseDirectory() + iDatabaseName + "/" + FILE_DISTRIBUTED_DB_CONFIG);
}
diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/ODeployDatabaseTask.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/ODeployDatabaseTask.java
index 99ead1c84eb..13b9c886960 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/ODeployDatabaseTask.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/ODeployDatabaseTask.java
@@ -60,18 +60,28 @@ public Object execute(final OServer iServer, ODistributedServerManager iManager,
ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT, "deploying database %s...",
databaseName);
- final File f = new File(BACKUP_DIRECTORY + "/" + database.getName());
+ final File f = new File(BACKUP_DIRECTORY + "/backup_" + database.getName() + ".zip");
if (f.exists())
f.delete();
+ else
+ f.getParentFile().mkdirs();
f.createNewFile();
+ ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT,
+ "creating backup of database '%s' in directory: %s...", databaseName, f.getAbsolutePath());
+
database.backup(new FileOutputStream(f), null, null);
ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT,
"sending the compressed database '%s' over the network to node '%s', size=%s...", databaseName, getNodeSource(),
OFileUtils.getSizeAsString(f.length()));
- return new ODistributedDatabaseChunk(f, 0, CHUNK_MAX_SIZE);
+ final ODistributedDatabaseChunk chunk = new ODistributedDatabaseChunk(f, 0, CHUNK_MAX_SIZE);
+
+ ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), ODistributedServerLog.DIRECTION.OUT,
+ "- transferring chunk #%d offset=%d size=%s...", 1, 0, OFileUtils.getSizeAsNumber(chunk.buffer.length));
+
+ return chunk;
} finally {
lock.unlock();
|
60eee421aac8d7ebbe44070979da88eb4e7371d7
|
hbase
|
HBASE-2156 HBASE-2037 broke Scan--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@902213 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 3e52e955d72d..66855c92e243 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -188,6 +188,7 @@ Release 0.21.0 - Unreleased
HBASE-2154 Fix Client#next(int) javadoc
HBASE-2152 Add default jmxremote.{access|password} files into conf
(Lars George and Gary Helmling via Stack)
+ HBASE-2156 HBASE-2037 broke Scan - only a test for trunk
IMPROVEMENTS
HBASE-1760 Cleanup TODOs in HTable
diff --git a/src/test/org/apache/hadoop/hbase/client/TestFromClientSide.java b/src/test/org/apache/hadoop/hbase/client/TestFromClientSide.java
index d5b97eca90cf..5227a050129a 100644
--- a/src/test/org/apache/hadoop/hbase/client/TestFromClientSide.java
+++ b/src/test/org/apache/hadoop/hbase/client/TestFromClientSide.java
@@ -3477,4 +3477,21 @@ public void testGetClosestRowBefore() throws IOException {
assertTrue(result.containsColumn(HConstants.CATALOG_FAMILY, null));
assertTrue(Bytes.equals(result.getValue(HConstants.CATALOG_FAMILY, null), one));
}
+
+ /**
+ * For HBASE-2156
+ * @throws Exception
+ */
+ public void testScanVariableReuse() throws Exception {
+ Scan scan = new Scan();
+ scan.addFamily(FAMILY);
+ scan.addColumn(FAMILY, ROW);
+
+ assertTrue(scan.getFamilyMap().get(FAMILY).size() == 1);
+
+ scan = new Scan();
+ scan.addFamily(FAMILY);
+
+ assertTrue(scan.getFamilyMap().get(FAMILY).size() == 0);
+ }
}
\ No newline at end of file
|
91517fad3eae6b93ded1cb16a518b1a37ec06e5c
|
restlet-framework-java
|
Fixed potential NPE when the product name is null.- Reported by Vincent Ricard.--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/Engine.java b/modules/com.noelios.restlet/src/com/noelios/restlet/Engine.java
index 99e1c21761..7dbcab4ed7 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/Engine.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/Engine.java
@@ -582,7 +582,7 @@ public String formatUserAgent(List<Product> products)
.hasNext();) {
final Product product = iterator.next();
if ((product.getName() == null)
- && (product.getName().length() == 0)) {
+ || (product.getName().length() == 0)) {
throw new IllegalArgumentException(
"Product name cannot be null.");
}
diff --git a/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java b/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java
index b52fa867bb..df932134a8 100644
--- a/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java
+++ b/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java
@@ -208,7 +208,7 @@ public String formatUserAgent(List<Product> products)
.hasNext();) {
final Product product = iterator.next();
if ((product.getName() == null)
- && (product.getName().length() == 0)) {
+ || (product.getName().length() == 0)) {
throw new IllegalArgumentException(
"Product name cannot be null.");
}
|
5d29c390bf81bd1c5ec171751d6da9c0f862063c
|
drools
|
refactoring--git-svn-id: https://svn.jboss.org/repos/labs/trunk/labs/jbossrules@2301 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java b/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
index 7be511bebf3..d4b69d473f5 100644
--- a/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
+++ b/drools-core/src/main/java/org/drools/leaps/RuleBaseImpl.java
@@ -1,6 +1,5 @@
package org.drools.leaps;
-import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -9,141 +8,125 @@
import java.util.Set;
import java.util.WeakHashMap;
+import org.drools.FactException;
import org.drools.RuleBase;
+import org.drools.RuleIntegrationException;
+import org.drools.RuleSetIntegrationException;
import org.drools.WorkingMemory;
-import org.drools.leaps.conflict.DefaultConflictResolver;
-import org.drools.reteoo.DefaultFactHandleFactory;
-import org.drools.rule.DuplicateRuleNameException;
+import org.drools.spi.FactHandleFactory;
import org.drools.rule.InvalidPatternException;
-import org.drools.rule.InvalidRuleException;
import org.drools.rule.Rule;
import org.drools.rule.RuleSet;
-import org.drools.spi.FactHandleFactory;
+import org.drools.spi.ClassObjectTypeResolver;
+import org.drools.spi.ObjectTypeResolver;
import org.drools.spi.RuleBaseContext;
/**
* This base class for the engine and analogous to Drool's RuleBase class. It
* has a similar interface adapted to the Leaps algorithm
- *
+ *
* @author Alexander Bagerman
*
*/
-public class RuleBaseImpl implements RuleBase, Serializable {
- private static final long serialVersionUID = 0L;
-
- // to store rules added just as addRule rather than as a part of ruleSet
- private final static String defaultRuleSet = "___default___rule___set___";
-
- private HashMap ruleSets;
-
- private Map applicationData;
-
- private RuleBaseContext ruleBaseContext;
-
- private ConflictResolver conflictResolver;
-
- private Builder builder;
+public class RuleBaseImpl implements RuleBase {
private HashMap leapsRules = new HashMap();
+ private final Builder builder;
+
/**
* TODO we do not need it here. and it references RETEoo class
*
* The fact handle factory.
*/
+ /** The fact handle factory. */
private final FactHandleFactory factHandleFactory;
- /* @todo: replace this with a weak HashSet */
+ private Set ruleSets;
+
+ private Map applicationData;
+
+ private RuleBaseContext ruleBaseContext;
+
+ // @todo: replace this with a weak HashSet
+ /**
+ * WeakHashMap to keep references of WorkingMemories but allow them to be
+ * garbage collected
+ */
private final transient Map workingMemories;
/** Special value when adding to the underlying map. */
private static final Object PRESENT = new Object();
+ // ------------------------------------------------------------
+ // Constructors
+ // ------------------------------------------------------------
+
/**
- * constractor that supplies default conflict resolution
+ * Construct.
*
- * @see LeapsDefaultConflictResolver
+ * @param rete
+ * The rete network.
*/
- public RuleBaseImpl() throws DuplicateRuleNameException,
- InvalidPatternException, InvalidRuleException {
- this(DefaultConflictResolver.getInstance(),
- new DefaultFactHandleFactory(), new HashSet(), new HashMap(),
+ public RuleBaseImpl() throws RuleIntegrationException,
+ RuleSetIntegrationException, FactException, InvalidPatternException {
+ this(new HandleFactory(), new HashSet(), new HashMap(),
new RuleBaseContext());
-
}
- public RuleBaseImpl(ConflictResolver conflictResolver,
- FactHandleFactory factHandleFactory, Set ruleSets,
+ /**
+ * Construct.
+ *
+ * @param rete
+ * The rete network.
+ * @param conflictResolver
+ * The conflict resolver.
+ * @param factHandleFactory
+ * The fact handle factory.
+ * @param ruleSets
+ * @param applicationData
+ */
+ public RuleBaseImpl(FactHandleFactory factHandleFactory, Set ruleSets,
Map applicationData, RuleBaseContext ruleBaseContext)
- throws DuplicateRuleNameException, InvalidPatternException,
- InvalidRuleException {
+ throws RuleIntegrationException, RuleSetIntegrationException,
+ FactException, InvalidPatternException {
+ ObjectTypeResolver resolver = new ClassObjectTypeResolver();
+ this.builder = new Builder(this, resolver);
this.factHandleFactory = factHandleFactory;
- this.conflictResolver = conflictResolver;
+ this.ruleSets = ruleSets;
this.applicationData = applicationData;
this.ruleBaseContext = ruleBaseContext;
this.workingMemories = new WeakHashMap();
- this.builder = new Builder();
-
- this.ruleSets = new HashMap();
- if (ruleSets != null) {
- int i = 0;
- RuleSet ruleSet;
- for (Iterator it = ruleSets.iterator(); it.hasNext(); i++) {
- ruleSet = (RuleSet) it.next();
- this.ruleSets.put(new Integer(i), ruleSet);
- Rule[] rules = ruleSet.getRules();
- for (int k = 0; k < rules.length; k++) {
- this.addRule(rules[k]);
- }
- }
+
+ this.ruleSets = new HashSet();
+ for (Iterator it = ruleSets.iterator(); it.hasNext();) {
+ this.addRuleSet((RuleSet) it.next());
}
- // default one to collect standalone rules
- this.ruleSets.put(defaultRuleSet, new RuleSet(defaultRuleSet,
- this.ruleBaseContext));
}
- /**
- * constractor. Takes conflict resolution class that for each fact and rule
- * sides must not return 0 if o1 != 02
- */
-
- public RuleBaseImpl(ConflictResolver conflictResolver)
- throws DuplicateRuleNameException, InvalidPatternException,
- InvalidRuleException {
- this(conflictResolver, new DefaultFactHandleFactory(), new HashSet(),
- new HashMap(), new RuleBaseContext());
-
- }
+ // ------------------------------------------------------------
+ // Instance methods
+ // ------------------------------------------------------------
/**
- * factory method for new working memory. will keep reference by default.
- * <b>Note:</b> references kept in a week hashmap.
- *
- * @return new working memory instance
- *
- * @see LeapsWorkingMemory
+ * @see RuleBase
*/
public WorkingMemory newWorkingMemory() {
- return this.newWorkingMemory(true);
+ return newWorkingMemory(true);
}
/**
- * factory method for new working memory. will keep reference by default.
- * <b>Note:</b> references kept in a week hashmap.
- *
- * @param keepReference
- * @return new working memory instance
- *
- * @see LeapsWorkingMemory
+ * @see RuleBase
*/
public WorkingMemory newWorkingMemory(boolean keepReference) {
- WorkingMemory workingMemory = new WorkingMemoryImpl(this);
- // process existing rules
+ WorkingMemoryImpl workingMemory = new WorkingMemoryImpl(this);
+ // add all rules added so far
for (Iterator it = this.leapsRules.values().iterator(); it.hasNext();) {
((WorkingMemoryImpl) workingMemory).addLeapsRules((List) it.next());
}
+ //
if (keepReference) {
- this.workingMemories.put(workingMemory, PRESENT);
+ this.workingMemories.put(workingMemory, RuleBaseImpl.PRESENT);
}
return workingMemory;
}
@@ -152,70 +135,127 @@ void disposeWorkingMemory(WorkingMemory workingMemory) {
this.workingMemories.remove(workingMemory);
}
- public Set getWorkingMemories() {
- return this.workingMemories.keySet();
- }
-
/**
- * TODO clash with leaps conflict resolver
+ * TODO do not understand its location here
*
* @see RuleBase
*/
- public org.drools.spi.ConflictResolver getConflictResolver() {
- return (org.drools.spi.ConflictResolver) null;
+ public FactHandleFactory getFactHandleFactory() {
+ return this.factHandleFactory;
}
- public ConflictResolver getLeapsConflictResolver() {
- return this.conflictResolver;
+ public FactHandleFactory newFactHandleFactory() {
+ return this.factHandleFactory.newInstance();
}
/**
- * @see RuleBase
+ * Assert a fact object.
+ *
+ * @param handle
+ * The handle.
+ * @param object
+ * The fact.
+ * @param workingMemory
+ * The working-memory.
+ *
+ * @throws FactException
+ * If an error occurs while performing the assertion.
*/
- public RuleSet[] getRuleSets() {
- return (RuleSet[]) this.ruleSets.values().toArray(
- new RuleSet[this.ruleSets.size()]);
- }
+// void assertObject(FactHandle handle, Object object,
+// PropagationContext context, WorkingMemoryImpl workingMemory)
+// throws FactException {
+// workingMemory.assertObject(object);
+// }
/**
- * Creates leaps rule wrappers and propagate rule to the working memories
+ * Retract a fact object.
*
- * @param rule
- * @throws DuplicateRuleNameException
- * @throws InvalidRuleException
- * @throws InvalidPatternException
+ * @param handle
+ * The handle.
+ * @param workingMemory
+ * The working-memory.
+ *
+ * @throws FactException
+ * If an error occurs while performing the retraction.
*/
- public void addRule(Rule rule) throws DuplicateRuleNameException,
- InvalidRuleException, InvalidPatternException {
- List rules = this.builder.processRule(rule);
-
- this.leapsRules.put(rule, rules);
-
- for(Iterator it = this.workingMemories.keySet().iterator(); it.hasNext();) {
- ((WorkingMemoryImpl)it.next()).addLeapsRules(rules);
- }
+// void retractObject(FactHandle handle, PropagationContext context,
+// WorkingMemoryImpl workingMemory) throws FactException {
+// workingMemory.retractObject(handle);
+// }
+//
+ public RuleSet[] getRuleSets() {
+ return (RuleSet[]) this.ruleSets.toArray(new RuleSet[this.ruleSets
+ .size()]);
}
- /**
- * @see RuleBase
- */
public Map getApplicationData() {
return this.applicationData;
}
- /**
- * @see RuleBase
- */
public RuleBaseContext getRuleBaseContext() {
return this.ruleBaseContext;
}
/**
- * TODO do not understand its location here
+ * Add a <code>RuleSet</code> to the network. Iterates through the
+ * <code>RuleSet</code> adding Each individual <code>Rule</code> to the
+ * network.
*
- * @see RuleBase
+ * @param ruleSet
+ * The rule-set to add.
+ *
+ * @throws RuleIntegrationException
+ * if an error prevents complete construction of the network for
+ * the <code>Rule</code>.
+ * @throws FactException
+ * @throws InvalidPatternException
*/
- public FactHandleFactory getFactHandleFactory() {
- return this.factHandleFactory;
+ public void addRuleSet(RuleSet ruleSet) throws RuleIntegrationException,
+ RuleSetIntegrationException, FactException, InvalidPatternException {
+ Map newApplicationData = ruleSet.getApplicationData();
+
+ // Check that the application data is valid, we cannot change the type
+ // of an already declared application data variable
+ for (Iterator it = newApplicationData.keySet().iterator(); it.hasNext();) {
+ String identifier = (String) it.next();
+ Class type = (Class) newApplicationData.get(identifier);
+ if (this.applicationData.containsKey(identifier)
+ && !this.applicationData.get(identifier).equals(type)) {
+ throw new RuleSetIntegrationException(ruleSet);
+ }
+ }
+ this.applicationData.putAll(newApplicationData);
+
+ this.ruleSets.add(ruleSet);
+
+ Rule[] rules = ruleSet.getRules();
+
+ for (int i = 0; i < rules.length; ++i) {
+ addRule(rules[i]);
+ }
+ }
+
+ /**
+ * Creates leaps rule wrappers and propagate rule to the working memories
+ *
+ * @param rule
+ * @throws FactException
+ * @throws RuleIntegrationException
+ * @throws InvalidPatternException
+ */
+ public void addRule(Rule rule) throws FactException,
+ RuleIntegrationException, InvalidPatternException {
+ List rules = this.builder.processRule(rule);
+
+ this.leapsRules.put(rule, rules);
+
+ for (Iterator it = this.workingMemories.keySet().iterator(); it
+ .hasNext();) {
+ ((WorkingMemoryImpl) it.next()).addLeapsRules(rules);
+ }
+ }
+
+ public Set getWorkingMemories() {
+ return this.workingMemories.keySet();
}
}
|
25b42d9807047c9d58eb2035f38554383de318d7
|
tapiji
|
Fixes minor bugs
|
c
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipselabs.tapiji.tools.jsf/plugin.xml b/org.eclipselabs.tapiji.tools.jsf/plugin.xml
index 6c7bf706..090b7fcd 100644
--- a/org.eclipselabs.tapiji.tools.jsf/plugin.xml
+++ b/org.eclipselabs.tapiji.tools.jsf/plugin.xml
@@ -21,7 +21,7 @@
<extension
point="org.eclipse.ui.ide.markerResolution">
<markerResolutionGenerator
- class="org.eclipselabs.tapiji.tools.jsf.builder.JSFViolationResolutionGenerator"
+ class="quickfix.JSFViolationResolutionGenerator"
markerType="org.eclipse.jst.jsf.ui.JSPSemanticsValidatorMarker">
</markerResolutionGenerator>
</extension>
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
index bced7ad7..b60d946c 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
@@ -35,7 +35,7 @@ public Image getImage() {
@Override
public String getLabel() {
- return "Export to resource bundle";
+ return "Export to Resource-Bundle";
}
@Override
@@ -79,8 +79,8 @@ public void run(IMarker marker) {
int quoteSingleIdx = document.get().substring(0, startPos).lastIndexOf ("'");
String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
- document.replace(startPos, endPos, bundleVar + "[" + quoteSign +
- key + quoteSign + "]");
+ document.replace(startPos, endPos, "#{" + bundleVar + "[" + quoteSign +
+ key + quoteSign + "]}");
} else {
document.replace(startPos, endPos, "#{" + bundleVar + "." + key +"}");
}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
new file mode 100644
index 00000000..7618d69d
--- /dev/null
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
@@ -0,0 +1,16 @@
+package quickfix;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.ui.IMarkerResolution;
+import org.eclipse.ui.IMarkerResolutionGenerator;
+
+public class JSFViolationResolutionGenerator implements
+ IMarkerResolutionGenerator {
+
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
index e165e8ba..5b6eae5c 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
@@ -14,8 +14,6 @@
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IMarkerResolution2;
-import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.InsertResourceBundleReferenceDialog;
import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
index c2f2c6ca..0e3d98f4 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
@@ -15,7 +15,7 @@
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IMarkerResolution2;
import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipselabs.tapiji.tools.core.ui.dialogs.InsertResourceBundleReferenceDialog;
+import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
import auditor.JSFResourceBundleDetector;
@@ -23,7 +23,7 @@ public class ReplaceResourceBundleReference implements IMarkerResolution2 {
private String key;
private String bundleId;
-
+
public ReplaceResourceBundleReference(String key, String bundleId) {
this.key = key;
this.bundleId = bundleId;
@@ -52,37 +52,43 @@ public void run(IMarker marker) {
int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- InsertResourceBundleReferenceDialog dialog = new InsertResourceBundleReferenceDialog(
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
Display.getDefault().getActiveShell(),
ResourceBundleManager.getManager(resource.getProject()),
bundleId);
if (dialog.open() != InputDialog.OK)
return;
-
+
String key = dialog.getSelectedResource();
Locale locale = dialog.getSelectedLocale();
-
- String jsfBundleVar = JSFResourceBundleDetector.getBundleVariableName(document.get().substring(startPos, startPos + endPos));
-
+
+ String jsfBundleVar = JSFResourceBundleDetector
+ .getBundleVariableName(document.get().substring(startPos,
+ startPos + endPos));
+
if (key.indexOf(".") >= 0) {
- int quoteDblIdx = document.get().substring(0, startPos).lastIndexOf("\"");
- int quoteSingleIdx = document.get().substring(0, startPos).lastIndexOf ("'");
+ int quoteDblIdx = document.get().substring(0, startPos)
+ .lastIndexOf("\"");
+ int quoteSingleIdx = document.get().substring(0, startPos)
+ .lastIndexOf("'");
String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
-
- document.replace(startPos, endPos, jsfBundleVar + "[" + quoteSign +
- key + quoteSign + "]");
+
+ document.replace(startPos, endPos, jsfBundleVar + "["
+ + quoteSign + key + quoteSign + "]");
} else {
document.replace(startPos, endPos, jsfBundleVar + "." + key);
}
-
+
textFileBuffer.commit(null, false);
} catch (Exception e) {
e.printStackTrace();
@@ -91,7 +97,7 @@ public void run(IMarker marker) {
bufferManager.disconnect(path, null);
} catch (CoreException e) {
e.printStackTrace();
- }
+ }
}
}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
index 797c1e87..401a67ab 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
@@ -23,15 +23,17 @@ public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
private IResource resource;
private String bundleName;
private String reference;
+ private boolean isKey;
public NewResourceBundleEntryProposal(IResource resource, String str, int startPos, int endPos,
- ResourceBundleManager manager, String bundleName) {
+ ResourceBundleManager manager, String bundleName, boolean isKey) {
this.startPos = startPos;
this.endPos = endPos;
this.manager = manager;
this.value = str;
this.resource = resource;
this.bundleName = bundleName;
+ this.isKey = isKey;
}
@Override
@@ -39,8 +41,8 @@ public void apply(IDocument document) {
CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
Display.getDefault().getActiveShell(),
manager,
- "",
- value,
+ isKey ? value : "",
+ !isKey ? value : "",
bundleName == null ? "" : bundleName,
"");
if (dialog.open() != InputDialog.OK)
@@ -76,11 +78,16 @@ public IContextInformation getContextInformation() {
@Override
public String getDisplayString() {
String displayStr = "";
- displayStr = "Create a new localized string literal";
- if (value != null && value.length() > 0)
- displayStr += " for '" + value + "'";
+ displayStr = "Create a new localized string literal";
+ if (this.isKey) {
+ if (value != null && value.length() > 0)
+ displayStr += " with the key '" + value + "'";
+ } else {
+ if (value != null && value.length() > 0)
+ displayStr += " for '" + value + "'";
+ }
return displayStr;
}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java
index cf9fcdc4..6b4c63e6 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java
@@ -59,7 +59,7 @@ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
int length = key.length();
proposals.add(new NewResourceBundleEntryProposal(resource, key, startpos, length, ResourceBundleManager.getManager(project)
- , bundleId));
+ , bundleId, true));
}
return proposals.toArray(new ICompletionProposal[proposals.size()]);
|
7147c843964a89cc4950ef8b9dc58cfe69aa974f
|
kotlin
|
Fix for KT-9897: Cannot pop operand off an empty- stack" with -= on ArrayList element-- -KT-9897 Fixed-
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/AsmUtil.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/AsmUtil.java
index 9e39ca54dae40..7a421644f0c20 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/AsmUtil.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/AsmUtil.java
@@ -835,7 +835,10 @@ public static void pop(@NotNull MethodVisitor v, @NotNull Type type) {
}
public static void dup(@NotNull InstructionAdapter v, @NotNull Type type) {
- int size = type.getSize();
+ dup(v, type.getSize());
+ }
+
+ private static void dup(@NotNull InstructionAdapter v, int size) {
if (size == 2) {
v.dup2();
}
@@ -847,6 +850,36 @@ else if (size == 1) {
}
}
+ public static void dup(@NotNull InstructionAdapter v, @NotNull Type topOfStack, @NotNull Type afterTop) {
+ if (topOfStack.getSize() == 0 && afterTop.getSize() == 0) {
+ return;
+ }
+
+ if (topOfStack.getSize() == 0) {
+ dup(v, afterTop);
+ }
+ else if (afterTop.getSize() == 0) {
+ dup(v, topOfStack);
+ }
+ else if (afterTop.getSize() == 1) {
+ if (topOfStack.getSize() == 1) {
+ dup(v, 2);
+ }
+ else {
+ v.dup2X1();
+ v.pop2();
+ v.dupX2();
+ v.dupX2();
+ v.pop();
+ v.dup2X1();
+ }
+ }
+ else {
+ //Note: it's possible to write dup3 and dup4
+ throw new UnsupportedOperationException("Don't know how generate dup3/dup4 for: " + topOfStack + " and " + afterTop);
+ }
+ }
+
public static void writeKotlinSyntheticClassAnnotation(@NotNull ClassBuilder v, @NotNull GenerationState state) {
AnnotationVisitor av = v.newAnnotation(asmDescByFqNameWithoutInnerClasses(KOTLIN_SYNTHETIC_CLASS), true);
JvmCodegenUtil.writeAbiVersion(av);
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/StackValue.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/StackValue.java
index 875d3d24bbdf3..03ff9b57ef631 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/StackValue.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/StackValue.java
@@ -771,12 +771,12 @@ public static class CollectionElementReceiver extends StackValue {
private final boolean isGetter;
private final ExpressionCodegen codegen;
private final ArgumentGenerator argumentGenerator;
- final List<ResolvedValueArgument> valueArguments;
+ private final List<ResolvedValueArgument> valueArguments;
private final FrameMap frame;
private final StackValue receiver;
private final ResolvedCall<FunctionDescriptor> resolvedGetCall;
private final ResolvedCall<FunctionDescriptor> resolvedSetCall;
- DefaultCallMask mask;
+ private DefaultCallMask mask;
public CollectionElementReceiver(
@NotNull Callable callable,
@@ -1424,6 +1424,11 @@ public void putSelector(@NotNull Type type, @NotNull InstructionAdapter v) {
currentExtensionReceiver
.moveToTopOfStack(hasExtensionReceiver ? type : currentExtensionReceiver.type, v, dispatchReceiver.type.getSize());
}
+
+ @Override
+ public void dup(@NotNull InstructionAdapter v, boolean withReceiver) {
+ AsmUtil.dup(v, extensionReceiver.type, dispatchReceiver.type);
+ }
}
public abstract static class StackValueWithSimpleReceiver extends StackValue {
diff --git a/compiler/testData/codegen/box/extensionProperties/kt9897.kt b/compiler/testData/codegen/box/extensionProperties/kt9897.kt
new file mode 100644
index 0000000000000..728323b1c649d
--- /dev/null
+++ b/compiler/testData/codegen/box/extensionProperties/kt9897.kt
@@ -0,0 +1,41 @@
+object Test {
+ var z = "0"
+ var l = 0L
+
+ fun changeObject(): String {
+ "1".someProperty += 1
+ return z
+ }
+
+ fun changeLong(): Long {
+ 2L.someProperty -= 1
+ return l
+ }
+
+ var String.someProperty: Int
+ get() {
+ return this.length
+ }
+ set(left) {
+ z += this + left
+ }
+
+ var Long.someProperty: Long
+ get() {
+ return l
+ }
+ set(left) {
+ l += this + left
+ }
+
+}
+
+fun box(): String {
+ val changeObject = Test.changeObject()
+ if (changeObject != "012") return "fail 1: $changeObject"
+
+ val changeLong = Test.changeLong()
+ if (changeLong != 1L) return "fail 1: $changeLong"
+
+ return "OK"
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/box/extensionProperties/kt9897_topLevel.kt b/compiler/testData/codegen/box/extensionProperties/kt9897_topLevel.kt
new file mode 100644
index 0000000000000..9ff0dd42c2291
--- /dev/null
+++ b/compiler/testData/codegen/box/extensionProperties/kt9897_topLevel.kt
@@ -0,0 +1,38 @@
+var z = "0"
+var l = 0L
+
+fun changeObject(): String {
+ "1".someProperty += 1
+ return z
+}
+
+fun changeLong(): Long {
+ 2L.someProperty -= 1
+ return l
+}
+
+var String.someProperty: Int
+ get() {
+ return this.length
+ }
+ set(left) {
+ z += this + left
+ }
+
+var Long.someProperty: Long
+ get() {
+ return l
+ }
+ set(left) {
+ l += this + left
+ }
+
+fun box(): String {
+ val changeObject = changeObject()
+ if (changeObject != "012") return "fail 1: $changeObject"
+
+ val changeLong = changeLong()
+ if (changeLong != 1L) return "fail 1: $changeLong"
+
+ return "OK"
+}
\ No newline at end of file
diff --git a/compiler/testData/codegen/boxWithStdlib/jvmStatic/kt9897_static.kt b/compiler/testData/codegen/boxWithStdlib/jvmStatic/kt9897_static.kt
new file mode 100644
index 0000000000000..66559576b7bc7
--- /dev/null
+++ b/compiler/testData/codegen/boxWithStdlib/jvmStatic/kt9897_static.kt
@@ -0,0 +1,41 @@
+object Test {
+ var z = "0"
+ var l = 0L
+
+ fun changeObject(): String {
+ "1".someProperty += 1
+ return z
+ }
+
+ fun changeLong(): Long {
+ 2L.someProperty -= 1
+ return l
+ }
+
+ @JvmStatic var String.someProperty: Int
+ get() {
+ return this.length
+ }
+ set(left) {
+ z += this + left
+ }
+
+ @JvmStatic var Long.someProperty: Long
+ get() {
+ return l
+ }
+ set(left) {
+ l += this + left
+ }
+
+}
+
+fun box(): String {
+ val changeObject = Test.changeObject()
+ if (changeObject != "012") return "fail 1: $changeObject"
+
+ val changeLong = Test.changeLong()
+ if (changeLong != 1L) return "fail 1: $changeLong"
+
+ return "OK"
+}
\ No newline at end of file
diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
index f9b23efc1bfff..982367afb326e 100644
--- a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
@@ -3883,6 +3883,18 @@ public void testInClassWithSetter() throws Exception {
doTest(fileName);
}
+ @TestMetadata("kt9897.kt")
+ public void testKt9897() throws Exception {
+ String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/extensionProperties/kt9897.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("kt9897_topLevel.kt")
+ public void testKt9897_topLevel() throws Exception {
+ String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/extensionProperties/kt9897_topLevel.kt");
+ doTest(fileName);
+ }
+
@TestMetadata("topLevel.kt")
public void testTopLevel() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/box/extensionProperties/topLevel.kt");
diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithStdlibCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithStdlibCodegenTestGenerated.java
index 18c59b627891e..1ae3240bb9dc3 100644
--- a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithStdlibCodegenTestGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxWithStdlibCodegenTestGenerated.java
@@ -2299,6 +2299,12 @@ public void testInline() throws Exception {
doTestWithStdlib(fileName);
}
+ @TestMetadata("kt9897_static.kt")
+ public void testKt9897_static() throws Exception {
+ String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/jvmStatic/kt9897_static.kt");
+ doTestWithStdlib(fileName);
+ }
+
@TestMetadata("postfixInc.kt")
public void testPostfixInc() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/codegen/boxWithStdlib/jvmStatic/postfixInc.kt");
|
deb17da4bbf1ddd29c88d7f0b39718c5c4473687
|
Mylyn Reviews
|
Hierarchical review scope
- scope table is now a tree.
- review section will be automatically collapsed if no scope is found.
- refined descriptions and types for scope items
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java
index e81f3b41..fd2459f7 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java
@@ -74,7 +74,12 @@ public List<IReviewFile> getReviewFiles(
@Override
public String getDescription() {
- return "patch";
+ return "Patch "+attachment.getFileName();
+ }
+
+ @Override
+ public String getType(int count) {
+ return count ==1? "patch":"patches";
}
}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java
index 55ec2e6a..195f30a0 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java
@@ -136,7 +136,13 @@ public String getType() {
@Override
public String getDescription() {
- return "resource";
+ return "Attachment "+attachment.getFileName();
}
+ @Override
+ public String getType(int count) {
+ return count==1?"resource":"resources";
+ }
+
+
}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScopeItem.java
index 62aafced..87bf3993 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScopeItem.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScopeItem.java
@@ -23,5 +23,6 @@ public interface ReviewScopeItem {
List<IReviewFile> getReviewFiles(NullProgressMonitor monitor)throws CoreException;
String getDescription();
+ String getType(int count);
}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java
index ba77e9cb..8299e9b4 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java
@@ -13,7 +13,6 @@
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
-import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
import org.eclipse.mylyn.reviews.tasks.core.Rating;
@@ -46,16 +45,22 @@ public String getDescription() {
}
return description;
}
-
+ private static class Counter {
+ int counter;
+ ReviewScopeItem item;
+ public Counter(ReviewScopeItem item) {
+ this.item=item;
+ }
+ }
private String convertScopeToDescription() {
StringBuilder sb = new StringBuilder();
- Map<String, AtomicInteger> counts = new TreeMap<String, AtomicInteger>();
+ Map<String, Counter> counts = new TreeMap<String, Counter>();
for (ReviewScopeItem item : scope.getItems()) {
- String key = item.getDescription();
+ String key = item.getType(1);
if (!counts.containsKey(key)) {
- counts.put(key, new AtomicInteger());
+ counts.put(key, new Counter(item));
}
- counts.get(key).incrementAndGet();
+ counts.get(key).counter++;
}
boolean isFirstElement = true;
for (String type : counts.keySet()) {
@@ -65,10 +70,10 @@ private String convertScopeToDescription() {
sb.append(", ");
}
- int count = counts.get(type).get();
+ int count = counts.get(type).counter;
sb.append(count);
sb.append(" ");
- sb.append(type);
+ sb.append(counts.get(type).item.getType(count));
}
return sb.toString();
}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java
index 26607f5e..bc582f6e 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java
@@ -38,7 +38,7 @@ public String getDescription() {
StringBuilder sb = new StringBuilder();
if(patchCount >0) {
sb.append(patchCount);
- sb.append(" Patch");
+ sb.append(" patch");
if(patchCount>1) {
sb.append("es");
}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java
index b99ea49f..657ed0a5 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java
@@ -120,9 +120,8 @@ public ReviewScope getReviewScope() throws CoreException {
return scope;
}
- /*package*/ ITreeNode getReviewResults(IProgressMonitor monitor) throws CoreException {
- return ReviewsUtil
- .getReviewSubTasksFor(getModel().getTask(),
+ /* package */ITreeNode getReviewResults(IProgressMonitor monitor) throws CoreException {
+ return ReviewsUtil.getReviewSubTasksFor(getModel().getTask(),
TasksUi.getTaskDataManager(),
ReviewsUiPlugin.getMapper(),
monitor);
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java
index 38861453..2881a1ed 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java
@@ -13,7 +13,6 @@
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
import java.util.List;
import org.eclipse.compare.CompareConfiguration;
@@ -27,7 +26,6 @@
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.CompositeImageDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
@@ -36,9 +34,10 @@
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
+import org.eclipse.jface.viewers.TreeNode;
+import org.eclipse.jface.viewers.TreeNodeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.mylyn.reviews.tasks.core.IReviewFile;
import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper;
import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
@@ -74,10 +73,11 @@
*/
public class ReviewTaskEditorPart extends AbstractReviewTaskEditorPart {
public static final String ID_PART_REVIEW = "org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPart"; //$NON-NLS-1$
- private TableViewer fileList;
+ private TreeViewer fileList;
private Composite composite;
private ITaskProperties taskProperties;
private ComboViewer ratingList;
+ private Section section;
public ReviewTaskEditorPart() {
setPartName("Review ");
@@ -86,53 +86,58 @@ public ReviewTaskEditorPart() {
@Override
public void createControl(Composite parent, FormToolkit toolkit) {
- Section section = createSection(parent, toolkit, true);
+ section = createSection(parent, toolkit, true);
GridLayout gl = new GridLayout(1, false);
gl.marginBottom = 16;
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.horizontalSpan = 4;
section.setLayout(gl);
section.setLayoutData(gd);
+setSection(toolkit, section);
composite = toolkit.createComposite(section);
composite.setLayout(new GridLayout(1, true));
- fileList = new TableViewer(composite);
+ fileList = new TreeViewer(composite);
fileList.getControl().setLayoutData(
new GridData(SWT.FILL, SWT.FILL, true, true));
- TableViewerColumn column = new TableViewerColumn(fileList, SWT.LEFT);
- column.getColumn().setText("Filename");
- column.getColumn().setWidth(100);
- column.getColumn().setResizable(true);
-
- TableLayout tableLayout = new TableLayout();
- tableLayout.addColumnData(new ColumnWeightData(100, true));
- fileList.getTable().setLayout(tableLayout);
+ createColumn(fileList, "Group", 100);
+ createColumn(fileList, "Filename", 100);
+ fileList.getTree().setLinesVisible(true);
+ fileList.getTree().setHeaderVisible(true);
fileList.setLabelProvider(new TableLabelProvider() {
- private final int COLUMN_FILE = 0;
+ private final int COLUMN_GROUP = 0;
+ private final int COLUMN_FILE = 1;
@Override
- public String getColumnText(Object element, int columnIndex) {
- if (columnIndex == COLUMN_FILE) {
+ public String getColumnText(Object node, int columnIndex) {
+ Object element = ((TreeNode) node).getValue();
+ switch (columnIndex) {
+ case COLUMN_GROUP:
+ if (element instanceof ReviewScopeItem) {
+ return ((ReviewScopeItem) element).getDescription();
+ }
+ break;
+ case COLUMN_FILE:
if (element instanceof IReviewFile) {
- IReviewFile file = ((IReviewFile) element);
-
- return file.getFileName();
+ return ((IReviewFile) element).getFileName();
}
+ break;
}
return null;
}
@Override
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == COLUMN_FILE) {
- ISharedImages sharedImages = PlatformUI.getWorkbench()
- .getSharedImages();
- if (element instanceof IReviewFile) {
+ public Image getColumnImage(Object node, int columnIndex) {
+ Object element = ((TreeNode) node).getValue();
+ if (element instanceof IReviewFile) {
+ if (columnIndex == COLUMN_FILE) {
+ ISharedImages sharedImages = PlatformUI.getWorkbench()
+ .getSharedImages();
IReviewFile file = ((IReviewFile) element);
if (file.isNewFile()) {
return new NewFile().createImage();
@@ -140,24 +145,25 @@ public Image getColumnImage(Object element, int columnIndex) {
if (!file.canReview()) {
return new MissingFile().createImage();
}
- }
- return sharedImages.getImage(ISharedImages.IMG_OBJ_FILE);
+ return sharedImages
+ .getImage(ISharedImages.IMG_OBJ_FILE);
+ }
}
return null;
}
});
- fileList.setContentProvider(ArrayContentProvider.getInstance());
+ fileList.setContentProvider(new TreeNodeContentProvider());
fileList.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof IStructuredSelection) {
IStructuredSelection sel = (IStructuredSelection) selection;
- if (sel.getFirstElement() instanceof IReviewFile) {
- final IReviewFile file = ((IReviewFile) sel
- .getFirstElement());
+ Object value = ((TreeNode)sel.getFirstElement()).getValue();
+ if (value instanceof IReviewFile) {
+ final IReviewFile file = (IReviewFile) value;
if (file.canReview()) {
CompareConfiguration configuration = new CompareConfiguration();
configuration.setLeftEditable(false);
@@ -173,7 +179,8 @@ public void doubleClick(DoubleClickEvent event) {
.setProperty(
CompareConfiguration.USE_OUTLINE_VIEW,
true);
- CompareUI.openCompareEditor(new CompareEditorInput(configuration) {
+ CompareUI.openCompareEditor(new CompareEditorInput(
+ configuration) {
@Override
protected Object prepareInput(
@@ -207,39 +214,62 @@ protected Object prepareInput(
setSection(toolkit, section);
SafeRunner.run(new ISafeRunnable() {
-
+
@Override
public void run() throws Exception {
- final List<IReviewFile> files = getInput();
+
+ ReviewScope reviewScope = getReviewScope();
+ if (reviewScope == null) {
+ section.setExpanded(false);
+ return;
+ }
+ List<ReviewScopeItem> files = reviewScope.getItems();
+
+ final TreeNode[] rootNodes = new TreeNode[files.size()];
+ int index = 0;
+ for (ReviewScopeItem item : files) {
+ TreeNode node = new TreeNode(item);
+ List<IReviewFile> reviewFiles = item
+ .getReviewFiles(new NullProgressMonitor());
+ TreeNode[] children = new TreeNode[reviewFiles.size()];
+ for (int i = 0; i < reviewFiles.size(); i++) {
+ children[i] = new TreeNode(reviewFiles.get(i));
+ children[i].setParent(node);
+ }
+ node.setChildren(children);
+
+ rootNodes[index++] = node;
+ }
+
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
- fileList.setInput(files);
+ fileList.setInput(rootNodes);
+ if(rootNodes.length==0) {
+ section.setExpanded(false);
+ }
}
});
-
+
}
-
+
@Override
public void handleException(Throwable exception) {
exception.printStackTrace();
}
- private List<IReviewFile> getInput() throws CoreException {
- List<IReviewFile> files = new ArrayList<IReviewFile>();
- ReviewScope reviewScope = getReviewScope();
- if (reviewScope != null) {
- // FIXME parse all scopes
- for (ReviewScopeItem scopeItem : reviewScope.getItems()) {
- files.addAll(scopeItem
- .getReviewFiles(new NullProgressMonitor()));
- }
- }
- return files;
- }
});
}
+ private TreeViewerColumn createColumn(TreeViewer tree, String title,
+ int width) {
+ TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT);
+ column.getColumn().setText(title);
+ column.getColumn().setWidth(width);
+ column.getColumn().setResizable(true);
+ return column;
+ }
+
private void createResultFields(Composite composite, FormToolkit toolkit) {
Composite resultComposite = toolkit.createComposite(composite);
toolkit.paintBordersFor(resultComposite);
@@ -368,7 +398,6 @@ private ReviewResult getCurrentResult() {
return res;
}
-
private static class MissingFile extends CompositeImageDescriptor {
ISharedImages sharedImages = PlatformUI.getWorkbench()
.getSharedImages();
|
473f7cf6ab558225908e9edaa56a1a6d9845b9c1
|
orientdb
|
fix for use of different serializer by the db- compare--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/tool/ODatabaseCompare.java b/core/src/main/java/com/orientechnologies/orient/core/db/tool/ODatabaseCompare.java
index a608f4f09a2..0babd7a27a0 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/db/tool/ODatabaseCompare.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/tool/ODatabaseCompare.java
@@ -18,6 +18,7 @@
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
+import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.OClusterPosition;
@@ -497,7 +498,9 @@ private boolean compareRecords(ODocumentHelper.RIDMapper ridMapper) {
final OClusterPosition db1Max = db1Range[1];
final OClusterPosition db2Max = db2Range[1];
+ ODatabaseRecordThreadLocal.INSTANCE.set(databaseDocumentTxOne);
final ODocument doc1 = new ODocument();
+ ODatabaseRecordThreadLocal.INSTANCE.set(databaseDocumentTxTwo);
final ODocument doc2 = new ODocument();
final ORecordId rid = new ORecordId(clusterId);
|
9e6fab3a6dcbf26e3aad60aa5cf371adbdc3b47b
|
elasticsearch
|
Added support for acknowledgements to update- cluster settings api--As a side note
|
a
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java
index ec018f8ca3b3d..73150e802b463 100644
--- a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java
+++ b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java
@@ -20,8 +20,9 @@
package org.elasticsearch.action.admin.cluster.settings;
import org.elasticsearch.ElasticSearchGenerationException;
+import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
-import org.elasticsearch.action.support.master.MasterNodeOperationRequest;
+import org.elasticsearch.action.support.master.AcknowledgedRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.ImmutableSettings;
@@ -39,8 +40,9 @@
import static org.elasticsearch.common.settings.ImmutableSettings.writeSettingsToStream;
/**
+ * Request for an update cluster settings action
*/
-public class ClusterUpdateSettingsRequest extends MasterNodeOperationRequest<ClusterUpdateSettingsRequest> {
+public class ClusterUpdateSettingsRequest extends AcknowledgedRequest<ClusterUpdateSettingsRequest> {
private Settings transientSettings = EMPTY_SETTINGS;
private Settings persistentSettings = EMPTY_SETTINGS;
@@ -65,21 +67,34 @@ Settings persistentSettings() {
return persistentSettings;
}
+ /**
+ * Sets the transient settings to be updated. They will not survive a full cluster restart
+ */
public ClusterUpdateSettingsRequest transientSettings(Settings settings) {
this.transientSettings = settings;
return this;
}
+ /**
+ * Sets the transient settings to be updated. They will not survive a full cluster restart
+ */
public ClusterUpdateSettingsRequest transientSettings(Settings.Builder settings) {
this.transientSettings = settings.build();
return this;
}
+ /**
+ * Sets the source containing the transient settings to be updated. They will not survive a full cluster restart
+ */
public ClusterUpdateSettingsRequest transientSettings(String source) {
this.transientSettings = ImmutableSettings.settingsBuilder().loadFromSource(source).build();
return this;
}
+ /**
+ * Sets the transient settings to be updated. They will not survive a full cluster restart
+ */
+ @SuppressWarnings("unchecked")
public ClusterUpdateSettingsRequest transientSettings(Map source) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -91,21 +106,34 @@ public ClusterUpdateSettingsRequest transientSettings(Map source) {
return this;
}
+ /**
+ * Sets the persistent settings to be updated. They will get applied cross restarts
+ */
public ClusterUpdateSettingsRequest persistentSettings(Settings settings) {
this.persistentSettings = settings;
return this;
}
+ /**
+ * Sets the persistent settings to be updated. They will get applied cross restarts
+ */
public ClusterUpdateSettingsRequest persistentSettings(Settings.Builder settings) {
this.persistentSettings = settings.build();
return this;
}
+ /**
+ * Sets the source containing the persistent settings to be updated. They will get applied cross restarts
+ */
public ClusterUpdateSettingsRequest persistentSettings(String source) {
this.persistentSettings = ImmutableSettings.settingsBuilder().loadFromSource(source).build();
return this;
}
+ /**
+ * Sets the persistent settings to be updated. They will get applied cross restarts
+ */
+ @SuppressWarnings("unchecked")
public ClusterUpdateSettingsRequest persistentSettings(Map source) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -117,12 +145,12 @@ public ClusterUpdateSettingsRequest persistentSettings(Map source) {
return this;
}
-
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
transientSettings = readSettingsFromStream(in);
persistentSettings = readSettingsFromStream(in);
+ readTimeout(in, Version.V_0_90_6);
}
@Override
@@ -130,5 +158,6 @@ public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
writeSettingsToStream(transientSettings, out);
writeSettingsToStream(persistentSettings, out);
+ writeTimeout(out, Version.V_0_90_6);
}
}
diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestBuilder.java b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestBuilder.java
index d7a849cc35853..991b9deae3b21 100644
--- a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestBuilder.java
+++ b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestBuilder.java
@@ -20,7 +20,7 @@
package org.elasticsearch.action.admin.cluster.settings;
import org.elasticsearch.action.ActionListener;
-import org.elasticsearch.action.support.master.MasterNodeOperationRequestBuilder;
+import org.elasticsearch.action.support.master.AcknowledgedRequestBuilder;
import org.elasticsearch.client.ClusterAdminClient;
import org.elasticsearch.client.internal.InternalClusterAdminClient;
import org.elasticsearch.common.settings.Settings;
@@ -28,48 +28,73 @@
import java.util.Map;
/**
+ * Builder for a cluster update settings request
*/
-public class ClusterUpdateSettingsRequestBuilder extends MasterNodeOperationRequestBuilder<ClusterUpdateSettingsRequest, ClusterUpdateSettingsResponse, ClusterUpdateSettingsRequestBuilder> {
+public class ClusterUpdateSettingsRequestBuilder extends AcknowledgedRequestBuilder<ClusterUpdateSettingsRequest, ClusterUpdateSettingsResponse, ClusterUpdateSettingsRequestBuilder> {
public ClusterUpdateSettingsRequestBuilder(ClusterAdminClient clusterClient) {
super((InternalClusterAdminClient) clusterClient, new ClusterUpdateSettingsRequest());
}
+ /**
+ * Sets the transient settings to be updated. They will not survive a full cluster restart
+ */
public ClusterUpdateSettingsRequestBuilder setTransientSettings(Settings settings) {
request.transientSettings(settings);
return this;
}
+ /**
+ * Sets the transient settings to be updated. They will not survive a full cluster restart
+ */
public ClusterUpdateSettingsRequestBuilder setTransientSettings(Settings.Builder settings) {
request.transientSettings(settings);
return this;
}
+ /**
+ * Sets the source containing the transient settings to be updated. They will not survive a full cluster restart
+ */
public ClusterUpdateSettingsRequestBuilder setTransientSettings(String settings) {
request.transientSettings(settings);
return this;
}
+ /**
+ * Sets the transient settings to be updated. They will not survive a full cluster restart
+ */
public ClusterUpdateSettingsRequestBuilder setTransientSettings(Map settings) {
request.transientSettings(settings);
return this;
}
+ /**
+ * Sets the persistent settings to be updated. They will get applied cross restarts
+ */
public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Settings settings) {
request.persistentSettings(settings);
return this;
}
+ /**
+ * Sets the persistent settings to be updated. They will get applied cross restarts
+ */
public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Settings.Builder settings) {
request.persistentSettings(settings);
return this;
}
+ /**
+ * Sets the source containing the persistent settings to be updated. They will get applied cross restarts
+ */
public ClusterUpdateSettingsRequestBuilder setPersistentSettings(String settings) {
request.persistentSettings(settings);
return this;
}
+ /**
+ * Sets the persistent settings to be updated. They will get applied cross restarts
+ */
public ClusterUpdateSettingsRequestBuilder setPersistentSettings(Map settings) {
request.persistentSettings(settings);
return this;
diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java
index 96598394bc061..0b7ed0a5f76ab 100644
--- a/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java
+++ b/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java
@@ -19,18 +19,19 @@
package org.elasticsearch.action.admin.cluster.settings;
-import java.io.IOException;
-
-import org.elasticsearch.action.ActionResponse;
+import org.elasticsearch.Version;
+import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
+import java.io.IOException;
+
/**
* A response for a cluster update settings action.
*/
-public class ClusterUpdateSettingsResponse extends ActionResponse {
+public class ClusterUpdateSettingsResponse extends AcknowledgedResponse {
Settings transientSettings;
Settings persistentSettings;
@@ -40,7 +41,8 @@ public class ClusterUpdateSettingsResponse extends ActionResponse {
this.transientSettings = ImmutableSettings.EMPTY;
}
- ClusterUpdateSettingsResponse(Settings transientSettings, Settings persistentSettings) {
+ ClusterUpdateSettingsResponse(boolean acknowledged, Settings transientSettings, Settings persistentSettings) {
+ super(acknowledged);
this.persistentSettings = persistentSettings;
this.transientSettings = transientSettings;
}
@@ -50,6 +52,7 @@ public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
transientSettings = ImmutableSettings.readSettingsFromStream(in);
persistentSettings = ImmutableSettings.readSettingsFromStream(in);
+ readAcknowledged(in, Version.V_0_90_6);
}
public Settings getTransientSettings() {
@@ -65,5 +68,6 @@ public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
ImmutableSettings.writeSettingsToStream(transientSettings, out);
ImmutableSettings.writeSettingsToStream(persistentSettings, out);
+ writeAcknowledged(out, Version.V_0_90_6);
}
}
diff --git a/src/main/java/org/elasticsearch/action/admin/cluster/settings/TransportClusterUpdateSettingsAction.java b/src/main/java/org/elasticsearch/action/admin/cluster/settings/TransportClusterUpdateSettingsAction.java
index 4dd19c9d90ed4..c320636b8a24e 100644
--- a/src/main/java/org/elasticsearch/action/admin/cluster/settings/TransportClusterUpdateSettingsAction.java
+++ b/src/main/java/org/elasticsearch/action/admin/cluster/settings/TransportClusterUpdateSettingsAction.java
@@ -22,16 +22,17 @@
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction;
+import org.elasticsearch.cluster.AckedClusterStateUpdateTask;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
-import org.elasticsearch.cluster.ClusterStateUpdateTask;
-import org.elasticsearch.cluster.TimeoutClusterStateUpdateTask;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.MetaData;
+import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.settings.ClusterDynamicSettings;
import org.elasticsearch.cluster.settings.DynamicSettings;
+import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ImmutableSettings;
@@ -42,6 +43,7 @@
import java.util.Map;
+import static org.elasticsearch.cluster.ClusterState.builder;
import static org.elasticsearch.cluster.ClusterState.newClusterStateBuilder;
/**
@@ -86,7 +88,91 @@ protected void masterOperation(final ClusterUpdateSettingsRequest request, final
final ImmutableSettings.Builder transientUpdates = ImmutableSettings.settingsBuilder();
final ImmutableSettings.Builder persistentUpdates = ImmutableSettings.settingsBuilder();
- clusterService.submitStateUpdateTask("cluster_update_settings", Priority.URGENT, new TimeoutClusterStateUpdateTask() {
+ clusterService.submitStateUpdateTask("cluster_update_settings", Priority.URGENT, new AckedClusterStateUpdateTask() {
+
+ private volatile boolean changed = false;
+
+ @Override
+ public boolean mustAck(DiscoveryNode discoveryNode) {
+ return true;
+ }
+
+ @Override
+ public void onAllNodesAcked(@Nullable Throwable t) {
+ if (changed) {
+ reroute(true);
+ } else {
+ listener.onResponse(new ClusterUpdateSettingsResponse(true, transientUpdates.build(), persistentUpdates.build()));
+ }
+
+ }
+
+ @Override
+ public void onAckTimeout() {
+ if (changed) {
+ reroute(false);
+ } else {
+ listener.onResponse(new ClusterUpdateSettingsResponse(false, transientUpdates.build(), persistentUpdates.build()));
+ }
+ }
+
+ private void reroute(final boolean updateSettingsAcked) {
+ clusterService.submitStateUpdateTask("reroute_after_cluster_update_settings", Priority.URGENT, new AckedClusterStateUpdateTask() {
+
+ @Override
+ public boolean mustAck(DiscoveryNode discoveryNode) {
+ //we wait for the reroute ack only if the update settings was acknowledged
+ return updateSettingsAcked;
+ }
+
+ @Override
+ public void onAllNodesAcked(@Nullable Throwable t) {
+ //we return when the cluster reroute is acked (the acknowledged flag depends on whether the update settings was acknowledged)
+ listener.onResponse(new ClusterUpdateSettingsResponse(updateSettingsAcked, transientUpdates.build(), persistentUpdates.build()));
+ }
+
+ @Override
+ public void onAckTimeout() {
+ //we return when the cluster reroute ack times out (acknowledged false)
+ listener.onResponse(new ClusterUpdateSettingsResponse(false, transientUpdates.build(), persistentUpdates.build()));
+ }
+
+ @Override
+ public TimeValue ackTimeout() {
+ return request.timeout();
+ }
+
+ @Override
+ public TimeValue timeout() {
+ return request.masterNodeTimeout();
+ }
+
+ @Override
+ public void onFailure(String source, Throwable t) {
+ //if the reroute fails we only log
+ logger.debug("failed to perform [{}]", t, source);
+ }
+
+ @Override
+ public ClusterState execute(final ClusterState currentState) {
+ // now, reroute in case things that require it changed (e.g. number of replicas)
+ RoutingAllocation.Result routingResult = allocationService.reroute(currentState);
+ if (!routingResult.changed()) {
+ return currentState;
+ }
+ return newClusterStateBuilder().state(currentState).routingResult(routingResult).build();
+ }
+
+ @Override
+ public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
+ }
+ });
+ }
+
+ @Override
+ public TimeValue ackTimeout() {
+ return request.timeout();
+ }
@Override
public TimeValue timeout() {
@@ -101,7 +187,6 @@ public void onFailure(String source, Throwable t) {
@Override
public ClusterState execute(final ClusterState currentState) {
- boolean changed = false;
ImmutableSettings.Builder transientSettings = ImmutableSettings.settingsBuilder();
transientSettings.put(currentState.metaData().transientSettings());
for (Map.Entry<String, String> entry : request.transientSettings().getAsMap().entrySet()) {
@@ -152,38 +237,12 @@ public ClusterState execute(final ClusterState currentState) {
blocks.removeGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK);
}
- return ClusterState.builder().state(currentState).metaData(metaData).blocks(blocks).build();
+ return builder().state(currentState).metaData(metaData).blocks(blocks).build();
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
- if (oldState == newState) {
- // nothing changed...
- listener.onResponse(new ClusterUpdateSettingsResponse(transientUpdates.build(), persistentUpdates.build()));
- return;
- }
- // now, reroute
- clusterService.submitStateUpdateTask("reroute_after_cluster_update_settings", Priority.URGENT, new ClusterStateUpdateTask() {
- @Override
- public ClusterState execute(final ClusterState currentState) {
- try {
- // now, reroute in case things change that require it (like number of replicas)
- RoutingAllocation.Result routingResult = allocationService.reroute(currentState);
- if (!routingResult.changed()) {
- return currentState;
- }
- return newClusterStateBuilder().state(currentState).routingResult(routingResult).build();
- } finally {
- listener.onResponse(new ClusterUpdateSettingsResponse(transientUpdates.build(), persistentUpdates.build()));
- }
- }
- @Override
- public void onFailure(String source, Throwable t) {
- logger.warn("unexpected failure during [{}]", t, source);
- listener.onResponse(new ClusterUpdateSettingsResponse(transientUpdates.build(), persistentUpdates.build()));
- }
- });
}
});
}
diff --git a/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java b/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java
index 6e62adae2de81..9be3a61be50e4 100644
--- a/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java
+++ b/src/main/java/org/elasticsearch/rest/action/admin/cluster/settings/RestClusterUpdateSettingsAction.java
@@ -19,7 +19,6 @@
package org.elasticsearch.rest.action.admin.cluster.settings;
-import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest;
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsResponse;
import org.elasticsearch.client.Client;
@@ -29,7 +28,6 @@
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.rest.*;
-import org.elasticsearch.rest.action.support.RestXContentBuilder;
import java.io.IOException;
import java.util.Map;
@@ -48,6 +46,7 @@ public RestClusterUpdateSettingsAction(Settings settings, Client client, RestCon
public void handleRequest(final RestRequest request, final RestChannel channel) {
final ClusterUpdateSettingsRequest clusterUpdateSettingsRequest = Requests.clusterUpdateSettingsRequest();
clusterUpdateSettingsRequest.listenerThreaded(false);
+ clusterUpdateSettingsRequest.timeout(request.paramAsTime("timeout", clusterUpdateSettingsRequest.timeout()));
clusterUpdateSettingsRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterUpdateSettingsRequest.masterNodeTimeout()));
try {
Map<String, Object> source = XContentFactory.xContent(request.content()).createParser(request.content()).mapAndClose();
@@ -66,31 +65,21 @@ public void handleRequest(final RestRequest request, final RestChannel channel)
return;
}
- client.admin().cluster().updateSettings(clusterUpdateSettingsRequest, new ActionListener<ClusterUpdateSettingsResponse>() {
- @Override
- public void onResponse(ClusterUpdateSettingsResponse response) {
- try {
- XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
- builder.startObject();
-
- builder.startObject("persistent");
- for (Map.Entry<String, String> entry : response.getPersistentSettings().getAsMap().entrySet()) {
- builder.field(entry.getKey(), entry.getValue());
- }
- builder.endObject();
-
- builder.startObject("transient");
- for (Map.Entry<String, String> entry : response.getTransientSettings().getAsMap().entrySet()) {
- builder.field(entry.getKey(), entry.getValue());
- }
- builder.endObject();
+ client.admin().cluster().updateSettings(clusterUpdateSettingsRequest, new AcknowledgedRestResponseActionListener<ClusterUpdateSettingsResponse>(request, channel, logger) {
- builder.endObject();
+ @Override
+ protected void addCustomFields(XContentBuilder builder, ClusterUpdateSettingsResponse response) throws IOException {
+ builder.startObject("persistent");
+ for (Map.Entry<String, String> entry : response.getPersistentSettings().getAsMap().entrySet()) {
+ builder.field(entry.getKey(), entry.getValue());
+ }
+ builder.endObject();
- channel.sendResponse(new XContentRestResponse(request, RestStatus.OK, builder));
- } catch (Throwable e) {
- onFailure(e);
+ builder.startObject("transient");
+ for (Map.Entry<String, String> entry : response.getTransientSettings().getAsMap().entrySet()) {
+ builder.field(entry.getKey(), entry.getValue());
}
+ builder.endObject();
}
@Override
@@ -98,11 +87,7 @@ public void onFailure(Throwable e) {
if (logger.isDebugEnabled()) {
logger.debug("failed to handle cluster state", e);
}
- try {
- channel.sendResponse(new XContentThrowableRestResponse(request, e));
- } catch (IOException e1) {
- logger.error("Failed to send failure response", e1);
- }
+ super.onFailure(e);
}
});
}
diff --git a/src/test/java/org/elasticsearch/cluster/ack/AckTests.java b/src/test/java/org/elasticsearch/cluster/ack/AckTests.java
index b2dc9332e9736..b4e36b3b23e8f 100644
--- a/src/test/java/org/elasticsearch/cluster/ack/AckTests.java
+++ b/src/test/java/org/elasticsearch/cluster/ack/AckTests.java
@@ -33,10 +33,7 @@
import org.elasticsearch.action.admin.indices.warmer.put.PutWarmerResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
-import org.elasticsearch.cluster.routing.IndexRoutingTable;
-import org.elasticsearch.cluster.routing.MutableShardRouting;
-import org.elasticsearch.cluster.routing.RoutingNode;
-import org.elasticsearch.cluster.routing.ShardRoutingState;
+import org.elasticsearch.cluster.routing.*;
import org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
@@ -238,4 +235,49 @@ private static MoveAllocationCommand getAllocationCommand() {
return new MoveAllocationCommand(shardToBeMoved.shardId(), fromNodeId, toNodeId);
}
+
+ @Test
+ public void testClusterUpdateSettingsAcknowledgement() {
+ client().admin().indices().prepareCreate("test")
+ .setSettings(settingsBuilder()
+ .put("number_of_shards", atLeast(cluster().numNodes()))
+ .put("number_of_replicas", 0)).get();
+ ensureGreen();
+
+ NodesInfoResponse nodesInfo = client().admin().cluster().prepareNodesInfo().get();
+ String excludedNodeId = null;
+ for (NodeInfo nodeInfo : nodesInfo) {
+ if (nodeInfo.getNode().isDataNode()) {
+ excludedNodeId = nodesInfo.getAt(0).getNode().id();
+ break;
+ }
+ }
+ assert excludedNodeId != null;
+
+ ClusterUpdateSettingsResponse clusterUpdateSettingsResponse = client().admin().cluster().prepareUpdateSettings()
+ .setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._id", excludedNodeId)).get();
+ assertThat(clusterUpdateSettingsResponse.isAcknowledged(), equalTo(true));
+ assertThat(clusterUpdateSettingsResponse.getTransientSettings().get("cluster.routing.allocation.exclude._id"), equalTo(excludedNodeId));
+
+ for (Client client : clients()) {
+ ClusterState clusterState = client.admin().cluster().prepareState().setLocal(true).get().getState();
+ assertThat(clusterState.routingNodes().metaData().transientSettings().get("cluster.routing.allocation.exclude._id"), equalTo(excludedNodeId));
+ for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
+ for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
+ for (ShardRouting shardRouting : indexShardRoutingTable) {
+ if (clusterState.nodes().get(shardRouting.currentNodeId()).id().equals(excludedNodeId)) {
+ //if the shard is still there it must be relocating and all nodes need to know, since the request was acknowledged
+ assertThat(shardRouting.relocating(), equalTo(true));
+ }
+ }
+ }
+ }
+ }
+
+ //let's wait for the relocation to be completed, otherwise there can be issues with after test checks (mock directory wrapper etc.)
+ waitForRelocation();
+
+ //removes the allocation exclude settings
+ client().admin().cluster().prepareUpdateSettings().setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._id", "")).get();
+ }
}
diff --git a/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationTests.java b/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationTests.java
index 23f92eaafa149..e1f4fdfaaec8f 100644
--- a/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationTests.java
+++ b/src/test/java/org/elasticsearch/cluster/allocation/AwarenessAllocationTests.java
@@ -204,9 +204,7 @@ public void testAwarenessZonesIncrementalNodes() throws InterruptedException {
assertThat(counts.get(B_1), equalTo(2));
assertThat(counts.containsKey(noZoneNode), equalTo(false));
client().admin().cluster().prepareUpdateSettings().setTransientSettings(ImmutableSettings.settingsBuilder().put("cluster.routing.allocation.awareness.attributes", "").build()).get();
-
-
- client().admin().cluster().prepareReroute().get();
+
health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("4").setWaitForActiveShards(10).setWaitForRelocatingShards(0).execute().actionGet();
assertThat(health.isTimedOut(), equalTo(false));
diff --git a/src/test/java/org/elasticsearch/cluster/allocation/FilteringAllocationTests.java b/src/test/java/org/elasticsearch/cluster/allocation/FilteringAllocationTests.java
index 4a03798c27dd0..9bbea5b043b3d 100644
--- a/src/test/java/org/elasticsearch/cluster/allocation/FilteringAllocationTests.java
+++ b/src/test/java/org/elasticsearch/cluster/allocation/FilteringAllocationTests.java
@@ -35,8 +35,6 @@
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.hamcrest.Matchers.equalTo;
-/**
- */
@ClusterScope(scope=Scope.TEST, numNodes=0)
public class FilteringAllocationTests extends AbstractIntegrationTest {
@@ -65,9 +63,7 @@ public void testDecommissionNodeNoReplicas() throws Exception {
client().admin().cluster().prepareUpdateSettings()
.setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._name", node_1))
.execute().actionGet();
-
- client().admin().cluster().prepareReroute().get();
- ensureGreen();
+ waitForRelocation();
logger.info("--> verify all are allocated on node1 now");
ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
@@ -140,7 +136,6 @@ public void testDisablingAllocationFiltering() throws Exception {
client().admin().indices().prepareUpdateSettings("test")
.setSettings(settingsBuilder().put("index.routing.allocation.exclude._name", ""))
.execute().actionGet();
-
client().admin().cluster().prepareReroute().get();
ensureGreen();
|
14c657d448b6dd743806c4df2a321d58f4e0618e
|
kotlin
|
Extract Function: Consider reference "broken" if- corresponding diagnostics are changed after code fragment extraction - -KT-8633 Fixed--
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionData.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionData.kt
index 867f02f713b50..f3f1edbef9762 100644
--- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionData.kt
+++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionData.kt
@@ -28,6 +28,7 @@ import org.jetbrains.kotlin.idea.codeInsight.JetFileReferencesResolver
import org.jetbrains.kotlin.idea.core.compareDescriptors
import org.jetbrains.kotlin.idea.core.refactoring.getContextForContainingDeclarationBody
import org.jetbrains.kotlin.idea.util.psi.patternMatching.JetPsiRange
+import org.jetbrains.kotlin.idea.util.psi.patternMatching.JetPsiUnifier
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
@@ -213,7 +214,9 @@ data class ExtractionData(
if (parent is JetUserType && (parent.getParent() as? JetUserType)?.getQualifier() == parent) continue
val descriptor = context[BindingContext.REFERENCE_TARGET, ref]
- val isBadRef = !compareDescriptors(project, originalResolveResult.descriptor, descriptor) || smartCast != null
+ val isBadRef = !(compareDescriptors(project, originalResolveResult.descriptor, descriptor)
+ && originalContext.diagnostics.forElement(originalResolveResult.originalRefExpr) == context.diagnostics.forElement(ref))
+ || smartCast != null
if (isBadRef && !originalResolveResult.declaration.isInsideOf(originalElements)) {
val originalResolvedCall = originalResolveResult.resolvedCall as? VariableAsFunctionResolvedCall
val originalFunctionCall = originalResolvedCall?.functionCall
diff --git a/idea/testData/refactoring/extractFunction/parameters/extractThis/missingReceiver.kt b/idea/testData/refactoring/extractFunction/parameters/extractThis/missingReceiver.kt
new file mode 100644
index 0000000000000..941a0f255843f
--- /dev/null
+++ b/idea/testData/refactoring/extractFunction/parameters/extractThis/missingReceiver.kt
@@ -0,0 +1,14 @@
+// PARAM_TYPES: kotlin.String
+// PARAM_DESCRIPTOR: internal final fun kotlin.String.foo(): kotlin.Unit defined in X
+
+fun print(a: Any) {
+
+}
+
+class X {
+ fun String.foo() {
+ <selection>print(extension)</selection>
+ }
+
+ val String.extension: Int get() = length()
+}
\ No newline at end of file
diff --git a/idea/testData/refactoring/extractFunction/parameters/extractThis/missingReceiver.kt.after b/idea/testData/refactoring/extractFunction/parameters/extractThis/missingReceiver.kt.after
new file mode 100644
index 0000000000000..ef79504739a12
--- /dev/null
+++ b/idea/testData/refactoring/extractFunction/parameters/extractThis/missingReceiver.kt.after
@@ -0,0 +1,18 @@
+// PARAM_TYPES: kotlin.String
+// PARAM_DESCRIPTOR: internal final fun kotlin.String.foo(): kotlin.Unit defined in X
+
+fun print(a: Any) {
+
+}
+
+class X {
+ fun String.foo() {
+ __dummyTestFun__()
+ }
+
+ private fun String.__dummyTestFun__() {
+ print(extension)
+ }
+
+ val String.extension: Int get() = length()
+}
\ No newline at end of file
diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java
index a6ac3eca9ac2a..1d659de3d14c1 100644
--- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java
+++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java
@@ -1979,6 +1979,12 @@ public void testImplicitThisWithSmartCast() throws Exception {
doExtractFunctionTest(fileName);
}
+ @TestMetadata("missingReceiver.kt")
+ public void testMissingReceiver() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("idea/testData/refactoring/extractFunction/parameters/extractThis/missingReceiver.kt");
+ doExtractFunctionTest(fileName);
+ }
+
@TestMetadata("paramAsExplicitInvoke.kt")
public void testParamAsExplicitInvoke() throws Exception {
String fileName = JetTestUtils.navigationMetadata("idea/testData/refactoring/extractFunction/parameters/extractThis/paramAsExplicitInvoke.kt");
|
28f708d59aacda81110f9ed46bba531a5ec884a5
|
apache$maven-surefire
|
Applied patch for http://jira.codehaus.org/browse/SUREFIRE-2 with
modifications.
Added 2 testcases to demonstrate increased flexibility.
git-svn-id: https://svn.apache.org/repos/asf/maven/surefire/trunk/surefire@331345 13f79535-47bb-0310-9956-ffa450edef68
|
p
|
https://github.com/apache/maven-surefire
|
diff --git a/surefire/src/main/org/codehaus/surefire/Surefire.java b/surefire/src/main/org/codehaus/surefire/Surefire.java
index 46b77aa52e..c42d446d34 100644
--- a/surefire/src/main/org/codehaus/surefire/Surefire.java
+++ b/surefire/src/main/org/codehaus/surefire/Surefire.java
@@ -2,6 +2,7 @@
import org.codehaus.surefire.battery.Battery;
import org.codehaus.surefire.battery.JUnitBattery;
+import org.codehaus.surefire.battery.assertion.BatteryTestFailedException;
import org.codehaus.surefire.report.ReportEntry;
import org.codehaus.surefire.report.Reporter;
import org.codehaus.surefire.report.ReporterManager;
@@ -78,11 +79,26 @@ public boolean run()
{
Battery battery = (Battery) i.next();
- if ( battery.getTestCount() > 0 )
+ int testCount = 0;
+ try
+ {
+ testCount = battery.getTestCount();
+ }
+ catch ( BatteryTestFailedException e )
+ {
+ e.printStackTrace();
+ ReportEntry report = new ReportEntry( e,
+ "org.codehaus.surefire.Runner",
+ Surefire.getResources().getString( "bigProblems" ), e );
+
+ reporterManager.batteryAborted( report );
+ }
+
+ if ( testCount > 0 )
{
executeBattery( battery, reporterManager );
- nbTests += battery.getTestCount();
+ nbTests += testCount;
}
List list = new ArrayList();
@@ -100,11 +116,26 @@ public boolean run()
{
Battery b = (Battery) j.next();
- if ( b.getTestCount() > 0 )
+ testCount = 0;
+ try
+ {
+ testCount = b.getTestCount();
+ }
+ catch ( BatteryTestFailedException e )
+ {
+ e.printStackTrace();
+ ReportEntry report = new ReportEntry( e,
+ "org.codehaus.surefire.Runner",
+ Surefire.getResources().getString( "bigProblems" ), e );
+
+ reporterManager.batteryAborted( report );
+ }
+
+ if ( testCount > 0 )
{
executeBattery( b, reporterManager );
- nbTests += b.getTestCount();
+ nbTests += testCount;
}
}
}
@@ -163,6 +194,8 @@ public void executeBattery( Battery battery, ReporterManager reportManager )
}
catch ( RuntimeException e )
{
+ e.printStackTrace();
+
rawString = Surefire.getResources().getString( "executeException" );
report = new ReportEntry( this, battery.getBatteryName(), rawString, e );
diff --git a/surefire/src/main/org/codehaus/surefire/battery/JUnitBattery.java b/surefire/src/main/org/codehaus/surefire/battery/JUnitBattery.java
index fcf7463632..38dd932ab8 100644
--- a/surefire/src/main/org/codehaus/surefire/battery/JUnitBattery.java
+++ b/surefire/src/main/org/codehaus/surefire/battery/JUnitBattery.java
@@ -157,11 +157,33 @@ public JUnitBattery( final Class testClass, ClassLoader loader )
addListenerMethod = testResultClass.getMethod( ADD_LISTENER_METHOD, addListenerParamTypes );
- countTestCasesMethod = testInterface.getMethod( COUNT_TEST_CASES_METHOD, new Class[0] );
+ if ( testInterface.isAssignableFrom( testClass ) )//testObject.getClass() ) )
+ {
+ countTestCasesMethod = testInterface.getMethod( COUNT_TEST_CASES_METHOD, new Class[0] );
- Class[] runParamTypes = {testResultClass};
+ runMethod = testInterface.getMethod( RUN_METHOD, new Class[] { testResultClass } );
- runMethod = testInterface.getMethod( RUN_METHOD, runParamTypes );
+ }
+ else
+ {
+ try
+ {
+ countTestCasesMethod = testClass.getMethod( COUNT_TEST_CASES_METHOD, new Class[0] );
+ }
+ catch (Exception e)
+ {
+ countTestCasesMethod = null; // for clarity
+ }
+
+ try
+ {
+ runMethod = testClass.getMethod( RUN_METHOD, new Class[] { testResultClass } );
+ }
+ catch (Exception e)
+ {
+ runMethod = null; // for clarity
+ }
+ }
}
protected Class getTestClass()
@@ -169,7 +191,25 @@ protected Class getTestClass()
return testClass;
}
- public void execute( ReporterManager reportManager )
+ protected Object getTestClassInstance()
+ {
+ return testObject;
+ }
+
+ public void execute( ReporterManager reportManager )
+ throws Exception
+ {
+ if ( runMethod != null )
+ {
+ executeJUnit( reportManager );
+ }
+ else
+ {
+ super.execute( reportManager );
+ }
+ }
+
+ protected void executeJUnit( ReporterManager reportManager )
{
try
{
@@ -191,19 +231,19 @@ public void execute( ReporterManager reportManager )
}
catch ( IllegalArgumentException e )
{
- throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e );
+ throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e );
}
catch ( InstantiationException e )
{
- throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e );
+ throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e );
}
catch ( IllegalAccessException e )
{
- throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e );
+ throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e );
}
catch ( InvocationTargetException e )
{
- throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e );
+ throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e );
}
}
@@ -211,21 +251,28 @@ public int getTestCount()
{
try
{
- Integer integer = (Integer) countTestCasesMethod.invoke( testObject, new Class[0] );
+ if ( countTestCasesMethod != null)
+ {
+ Integer integer = (Integer) countTestCasesMethod.invoke( testObject, new Class[0] );
- return integer.intValue();
+ return integer.intValue();
+ }
+ else
+ {
+ return super.getTestCount();
+ }
}
catch ( IllegalAccessException e )
{
- throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e );
+ throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e );
}
catch ( IllegalArgumentException e )
{
- throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e );
+ throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e );
}
catch ( InvocationTargetException e )
{
- throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e );
+ throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e );
}
}
diff --git a/surefire/src/main/org/codehaus/surefire/report/ConsoleReporter.java b/surefire/src/main/org/codehaus/surefire/report/ConsoleReporter.java
index 3d5fcfee45..3637060632 100644
--- a/surefire/src/main/org/codehaus/surefire/report/ConsoleReporter.java
+++ b/surefire/src/main/org/codehaus/surefire/report/ConsoleReporter.java
@@ -42,7 +42,7 @@ public void runStarting( int testCount )
public void runAborted( ReportEntry report )
{
- writer.println( "ABORTED" );
+ writer.println( "RUN ABORTED" );
writer.println( report.getSource().getClass().getName() );
writer.println( report.getName() );
writer.println( report.getMessage() );
@@ -51,7 +51,7 @@ public void runAborted( ReportEntry report )
}
public void batteryAborted( ReportEntry report )
{
- writer.println( "ABORTED" );
+ writer.println( "BATTERY ABORTED" );
writer.println( report.getSource().getClass().getName() );
writer.println( report.getName() );
writer.println( report.getMessage() );
diff --git a/surefire/src/main/org/codehaus/surefire/report/ReporterManager.java b/surefire/src/main/org/codehaus/surefire/report/ReporterManager.java
index 294c427647..ea2041668a 100644
--- a/surefire/src/main/org/codehaus/surefire/report/ReporterManager.java
+++ b/surefire/src/main/org/codehaus/surefire/report/ReporterManager.java
@@ -223,7 +223,6 @@ public void batteryCompleted( ReportEntry report )
}
catch ( Exception e )
{
- handleReporterException( "suiteCompleted", e );
}
}
}
@@ -243,6 +242,8 @@ public void batteryAborted( ReportEntry report )
handleReporterException( "suiteAborted", e );
}
}
+
+ ++errors;
}
// ----------------------------------------------------------------------
diff --git a/surefire/src/test/org/codehaus/surefire/POJOTest.java b/surefire/src/test/org/codehaus/surefire/POJOTest.java
new file mode 100644
index 0000000000..5d77187ea6
--- /dev/null
+++ b/surefire/src/test/org/codehaus/surefire/POJOTest.java
@@ -0,0 +1,18 @@
+package org.codehaus.surefire;
+
+/**
+ * Implementation of a POJO with test methods.
+ */
+public class POJOTest
+{
+ public void testFoo()
+ {
+ System.out.println("Foo");
+ }
+
+ public void testBar()
+ {
+ System.out.println("Bar");
+ }
+
+}
diff --git a/surefire/src/test/org/codehaus/surefire/SysUnitTest.java b/surefire/src/test/org/codehaus/surefire/SysUnitTest.java
new file mode 100644
index 0000000000..21ec592333
--- /dev/null
+++ b/surefire/src/test/org/codehaus/surefire/SysUnitTest.java
@@ -0,0 +1,31 @@
+package org.codehaus.surefire;
+
+import junit.framework.TestResult;
+
+/**
+ * This class provides the 'suite' and junit.framework.Test API
+ * without implementing an interface. It (hopefully) mimicks
+ * a sysunit generated testcase.
+ */
+public class SysUnitTest
+{
+ public static Object suite()
+ {
+ return new SysUnitTest();
+ }
+
+ public int countTestCases( TestResult tr )
+ {
+ return 1;
+ }
+
+ public void run()
+ {
+ testFoo();
+ }
+
+ public void testFoo()
+ {
+ System.out.println("No assert available");
+ }
+}
|
69a34741cea3bbca8a92f77e00ed6955c52b428a
|
hunterhacker$jdom
|
Integrated a major path from Rolf Lear (rlearATalgorithmics.com).
Below is his 6/4/2003 email. I tagged the code "before_rolf" so
if we decide to back this out it's easy.
-jh-
I have had a look at the Child/Parent thing.
Personally, I don't think the Idea has been taken far enough, so I
played around with the concept, and "normalised" some of the
redundancies.
Firstly, I converted the Child interface into an Abstract class that
deals with ALL Parent/child relationships for the Child role,
including detaching, cloning, set/getParent (and holds the parent
instance field).
I also implemented getDocument at the Child Class level (all children
have the same mechanism for getting the Document).
Next, I added the method "getDocument" to the Parent Interface... and
parent can getDocument, including the Document class which has "return
this;" in the getDocument().
Finally, I changed the ContentList class substantially. elementData is
now called childData, and is of type Child[] instead of Object[]. The
ContentList owner is now of type Parent instead of Object. I have
added a method canContain to the Parent interface, and thus the actual
Parent object determines what content is allowed in the contentlist,
so instead of add(int,Text), add(int,Element), add(int,CDATA),
add(int,ProcessingInstruction), etc, there is just add(int, Child).
In doing all of the above, I have cut large amounts of
redundant/duplicated code, simplified the relationships, and thrown
away "special cases". The only downside I can see in terms of
"functionality" is that some of the exceptions are thrown with less
specialised messages...
Please have a look, and comment on the concept. Note, that this is
only possible by converting Child to an abstract class instead of
an interface.
Rolf
|
p
|
https://github.com/hunterhacker/jdom
|
diff --git a/core/src/java/org/jdom/Child.java b/core/src/java/org/jdom/Child.java
index ee756a0b6..752619f99 100644
--- a/core/src/java/org/jdom/Child.java
+++ b/core/src/java/org/jdom/Child.java
@@ -1,6 +1,6 @@
/*--
- $Id: Child.java,v 1.3 2003/06/04 17:40:52 jhunter Exp $
+ $Id: Child.java,v 1.4 2004/02/06 03:39:02 jhunter Exp $
Copyright (C) 2000 Brett McLaughlin & Jason Hunter.
All rights reserved.
@@ -72,41 +72,68 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*
* @author Bradley S. Huffman
* @author Jason Hunter
- * @version $Revision: 1.3 $, $Date: 2003/06/04 17:40:52 $
+ * @version $Revision: 1.4 $, $Date: 2004/02/06 03:39:02 $
*/
-public interface Child extends Cloneable, Serializable {
-
+public abstract class Child implements Cloneable, Serializable {
+
+ protected Parent parent = null;
+
+ protected Child() {}
+
/**
* Detaches this child from its parent or does nothing if the child
* has no parent.
*
* @return this child detached
*/
- Child detach();
+ public Child detach() {
+ if (parent != null) {
+ parent.removeContent(this);
+ }
+ return this;
+ }
+
+ /**
+ * Return this child's parent, or null if this child is currently
+ * not attached. The parent can be either an {@link Element}
+ * or a {@link Document}.
+ *
+ * @return this child's parent or null if none
+ */
+ public Parent getParent() {
+ return parent;
+ }
/**
- * Return this child's owning document or null if the branch containing
- * this child is currently not attached to a document.
+ * Sets the parent of this Child. The caller is responsible for removing
+ * any pre-existing parentage.
*
- * @return this child's owning document or null if none
+ * @param parent new parent element
+ * @return the target element
*/
- Document getDocument();
+ protected Child setParent(Parent parent) {
+ this.parent = parent;
+ return this;
+ }
/**
- * Return this child's parent, or null if this child is currently
- * not attached. The parent can be either an {@link Element}
- * or a {@link Document}.
+ * Return this child's owning document or null if the branch containing
+ * this child is currently not attached to a document.
*
- * @return this child's parent or null if none
+ * @return this child's owning document or null if none
*/
- Parent getParent();
+ public Document getDocument() {
+ if (parent == null) return null;
+ return parent.getDocument();
+ }
+
/**
* Returns the XPath 1.0 string value of this child.
*
* @return xpath string value of this child.
*/
- String getValue();
+ public abstract String getValue();
/**
* Returns a deep, unattached copy of this child and its descendants
@@ -114,5 +141,15 @@ public interface Child extends Cloneable, Serializable {
*
* @return a detached deep copy of this child and descendants
*/
- Object clone();
+ public Object clone() {
+ try {
+ Child c = (Child)super.clone();
+ c.parent = null;
+ return c;
+ } catch (CloneNotSupportedException e) {
+ //Can not happen ....
+ //e.printStackTrace();
+ return null;
+ }
+ }
}
diff --git a/core/src/java/org/jdom/Comment.java b/core/src/java/org/jdom/Comment.java
index a2bbe6b66..2287c48f2 100644
--- a/core/src/java/org/jdom/Comment.java
+++ b/core/src/java/org/jdom/Comment.java
@@ -1,6 +1,6 @@
/*--
- $Id: Comment.java,v 1.28 2003/05/20 21:53:59 jhunter Exp $
+ $Id: Comment.java,v 1.29 2004/02/06 03:39:02 jhunter Exp $
Copyright (C) 2000 Jason Hunter & Brett McLaughlin.
All rights reserved.
@@ -60,21 +60,18 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* An XML comment. Methods allow the user to get and set the text of the
* comment.
*
- * @version $Revision: 1.28 $, $Date: 2003/05/20 21:53:59 $
+ * @version $Revision: 1.29 $, $Date: 2004/02/06 03:39:02 $
* @author Brett McLaughlin
* @author Jason Hunter
*/
-public class Comment implements Child {
+public class Comment extends Child {
private static final String CVS_ID =
- "@(#) $RCSfile: Comment.java,v $ $Revision: 1.28 $ $Date: 2003/05/20 21:53:59 $ $Name: $";
+ "@(#) $RCSfile: Comment.java,v $ $Revision: 1.29 $ $Date: 2004/02/06 03:39:02 $ $Name: $";
/** Text of the <code>Comment</code> */
protected String text;
- /** Parent element, document, or null if none */
- protected Parent parent;
-
/**
* Default, no-args constructor for implementations to use if needed.
*/
@@ -89,18 +86,6 @@ public Comment(String text) {
setText(text);
}
- /**
- * This will return the parent of this <code>Comment</code>.
- * If there is no parent, then this returns <code>null</code>.
- *
- * @return parent of this <code>Comment</code>
- */
- public Parent getParent() {
- if (parent instanceof Element) {
- return (Element) parent;
- }
- return null;
- }
/**
* Returns the XPath 1.0 string value of this element, which is the
@@ -112,48 +97,6 @@ public String getValue() {
return text;
}
- /**
- * This will set the parent of this <code>Comment</code>.
- *
- * @param parent <code>Element</code> to be new parent.
- * @return this <code>Comment</code> modified.
- */
- protected Comment setParent(Parent parent) {
- this.parent = parent;
- return this;
- }
-
- /**
- * This detaches the <code>Comment</code> from its parent, or does
- * nothing if the <code>Comment</code> has no parent.
- *
- * @return <code>Comment</code> - this
- * <code>Comment</code> modified.
- */
- public Child detach() {
- if (parent != null) {
- parent.removeContent(this);
- }
- return this;
- }
-
- /**
- * This retrieves the owning <code>{@link Document}</code> for
- * this Comment, or null if not a currently a member of a
- * <code>{@link Document}</code>.
- *
- * @return <code>Document</code> owning this Element, or null.
- */
- public Document getDocument() {
- if (parent instanceof Document) {
- return (Document) parent;
- }
- if (parent instanceof Element) {
- return ((Element)parent).getDocument();
- }
- return null;
- }
-
/**
* This returns the textual data within the <code>Comment</code>.
*
@@ -220,26 +163,4 @@ public final int hashCode() {
return super.hashCode();
}
- /**
- * This will return a clone of this <code>Comment</code>.
- *
- * @return <code>Object</code> - clone of this <code>Comment</code>.
- */
- public Object clone() {
- Comment comment = null;
-
- try {
- comment = (Comment) super.clone();
- } catch (CloneNotSupportedException ce) {
- // Can't happen
- }
-
- // The text is a reference to a immutable String object
- // and is already copied by Object.clone();
-
- // parent reference is copied by Object.clone()
- // and must be set to null
- comment.parent = null;
- return comment;
- }
}
diff --git a/core/src/java/org/jdom/ContentList.java b/core/src/java/org/jdom/ContentList.java
index 423048afe..f76a965e1 100644
--- a/core/src/java/org/jdom/ContentList.java
+++ b/core/src/java/org/jdom/ContentList.java
@@ -1,6 +1,6 @@
/*--
- $Id: ContentList.java,v 1.31 2004/02/05 09:35:56 jhunter Exp $
+ $Id: ContentList.java,v 1.32 2004/02/06 03:39:02 jhunter Exp $
Copyright (C) 2000 Jason Hunter & Brett McLaughlin.
All rights reserved.
@@ -72,15 +72,15 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* @see ProcessingInstruction
* @see Text
*
- * @version $Revision: 1.31 $, $Date: 2004/02/05 09:35:56 $
+ * @version $Revision: 1.32 $, $Date: 2004/02/06 03:39:02 $
* @author Alex Rosen
* @author Philippe Riand
* @author Bradley S. Huffman
*/
-class ContentList extends AbstractList implements java.io.Serializable {
+final class ContentList extends AbstractList implements java.io.Serializable {
private static final String CVS_ID =
- "@(#) $RCSfile: ContentList.java,v $ $Revision: 1.31 $ $Date: 2004/02/05 09:35:56 $ $Name: $";
+ "@(#) $RCSfile: ContentList.java,v $ $Revision: 1.32 $ $Date: 2004/02/06 03:39:02 $ $Name: $";
private static final int INITIAL_ARRAY_SIZE = 5;
@@ -99,28 +99,14 @@ class ContentList extends AbstractList implements java.io.Serializable {
/** Our backing list */
// protected ArrayList list;
- private Object elementData[];
+ private Child elementData[];
private int size;
/** Document or Element this list belongs to */
- private Object parent;
+ private Parent parent;
/** Force either a Document or Element parent */
- private ContentList() { }
-
- /**
- * Create a new instance of the ContentList representing
- * Document content
- */
- ContentList(Document document) {
- this.parent = document;
- }
-
- /**
- * Create a new instance of the ContentList representing
- * Element content
- */
- ContentList(Element parent) {
+ ContentList(Parent parent) {
this.parent = parent;
}
@@ -134,101 +120,16 @@ private ContentList() { }
* throws IndexOutOfBoundsException if index < 0 || index > size()
*/
public void add(int index, Object obj) {
- if (obj instanceof Element) {
- add(index, (Element) obj);
- }
- else if (obj instanceof Text) {
- add(index, (Text) obj);
- }
- else if (obj instanceof Comment) {
- add(index, (Comment) obj);
- }
- else if (obj instanceof ProcessingInstruction) {
- add(index, (ProcessingInstruction) obj);
- }
- else if (obj instanceof EntityRef) {
- add(index, (EntityRef) obj);
- }
- else if (obj instanceof DocType) {
- add(index, (DocType) obj);
- }
- else {
- if (obj == null) {
- throw new IllegalAddException("Cannot add null object");
- }
- else {
- throw new IllegalAddException("Class " +
- obj.getClass().getName() +
- " is of unrecognized type and cannot be added");
- }
- }
- }
-
- /**
- * Check and add the <code>Element</code> to this list at
- * the given index.
- *
- * @param index index where to add <code>Element</code>
- * @param element <code>Element</code> to add
- */
- void add(int index, Element element) {
- if (element == null) {
+ if (obj == null) {
throw new IllegalAddException("Cannot add null object");
}
-
- if (element.getParent() != null) {
- Parent p = element.getParent();
- if (p instanceof Document) {
- throw new IllegalAddException(element,
- "The element is the root element of another document");
- }
- else {
- throw new IllegalAddException(
- "The element already has an existing parent \"" +
- ((Element)p).getQualifiedName() + "\"");
- }
- }
-
- if (element == parent) {
- throw new IllegalAddException(
- "The element cannot be added to itself");
- }
-
- if ((parent instanceof Element) &&
- ((Element) parent).isAncestor(element)) {
- throw new IllegalAddException(
- "The element cannot be added as a descendent of itself");
- }
-
- if (index<0 || index>size) {
- throw new IndexOutOfBoundsException("Index: " + index +
- " Size: " + size());
- }
-
- if (parent instanceof Document) {
- if (indexOfFirstElement() >= 0) {
- throw new IllegalAddException(
- "Cannot add a second root element, only one is allowed");
- }
- if (indexOfDocType() > index) {
- throw new IllegalAddException(
- "A root element cannot be added before the DocType");
- }
- element.setParent((Document) parent);
- }
- else {
- element.setParent((Element) parent);
- }
-
- ensureCapacity(size+1);
- if( index==size ) {
- elementData[size++] = element;
+ if ((obj instanceof Child)) {
+ add(index, (Child) obj);
} else {
- System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = element;
- size++;
+ throw new IllegalAddException("Class " +
+ obj.getClass().getName() +
+ " is of unrecognized type and cannot be added");
}
- modCount++;
}
/**
@@ -236,255 +137,36 @@ void add(int index, Element element) {
* the given index.
*
* @param index index where to add <code>Element</code>
- * @param doctype <code>DocType</code> to add
+ * @param child <code>Element</code> to add
*/
- void add(int index, DocType doctype) {
- if (doctype == null) {
+ void add(int index, Child child) {
+ if (child == null) {
throw new IllegalAddException("Cannot add null object");
}
+ parent.canContain(child, index);
- if (doctype.getParent() != null) {
- throw new IllegalAddException(doctype,
- "The doctype already has an existing document");
- }
-
- if (index < 0 || index > size) {
- throw new IndexOutOfBoundsException("Index: " + index +
- " Size: " + size());
- }
-
- if (parent instanceof Element) {
- throw new IllegalAddException(
- "A DocType is not allowed except at the document level");
- }
-
- int firstElt = indexOfFirstElement();
- if (firstElt != -1 && firstElt < index) {
- throw new IllegalAddException(
- "A DocType cannot be added after the root element");
- }
-
- if (parent instanceof Document) {
- if (indexOfDocType() >= 0) {
- throw new IllegalAddException(
- "Cannot add a second doctype, only one is allowed");
- }
- doctype.setParent((Document) parent);
- }
-
- ensureCapacity(size + 1);
- if (index == size) {
- elementData[size++] = doctype;
- }
- else {
- System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = doctype;
- size++;
- }
- modCount++;
- }
-
- /**
- * Check and add the <code>Comment</code> to this list at
- * the given index.
- *
- * @param index index where to add <code>Comment</code>
- * @param comment <code>Comment</code> to add
- */
- void add(int index, Comment comment) {
- if (comment == null) {
- throw new IllegalAddException("Cannot add null object");
- }
-
- if (comment.getParent() != null) {
- Parent p = comment.getParent();
+ if (child.getParent() != null) {
+ Parent p = child.getParent();
if (p instanceof Document) {
- throw new IllegalAddException(comment,
- "The comment is already attached to a document");
+ throw new IllegalAddException((Element)child,
+ "The Child already has an existing parent document");
}
else {
throw new IllegalAddException(
- "The comment already has an existing parent \"" +
+ "The Child already has an existing parent \"" +
((Element)p).getQualifiedName() + "\"");
}
}
- if (index<0 || index>size) {
- throw new IndexOutOfBoundsException("Index: " + index +
- " Size: " + size());
- }
-
- // XXX We can simplify this
- if (parent instanceof Document) {
- comment.setParent((Document) parent);
- }
- else {
- comment.setParent((Element) parent);
- }
-
- ensureCapacity(size+1);
- if( index==size ) {
- elementData[size++] = comment;
- } else {
- System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = comment;
- size++;
- }
- modCount++;
- }
-
- /**
- * Check and add the <code>ProcessingInstruction</code> to this list at
- * the given index.
- *
- * @param index index where to add <code>ProcessingInstruction</code>
- * @param pi <code>ProcessingInstruction</code> to add
- */
- void add(int index, ProcessingInstruction pi) {
- if (pi == null) {
- throw new IllegalAddException("Cannot add null object");
- }
-
- if (pi.getParent() != null) {
- Parent p = pi.getParent();
- if (p instanceof Document) {
- throw new IllegalAddException(
- "The PI is already attached to a document");
- }
- else {
- throw new IllegalAddException(
- "The PI already has an existing parent \"" +
- ((Element)p).getQualifiedName() + "\"");
- }
- }
-
- if (index<0 || index>size) {
- throw new IndexOutOfBoundsException("Index: " + index +
- " Size: " + size());
- }
-
- // XXX We can simplify this
- if (parent instanceof Document) {
- pi.setParent((Document) parent);
- }
- else {
- pi.setParent((Element) parent);
- }
-
- ensureCapacity(size+1);
- if( index==size ) {
- elementData[size++] = pi;
- } else {
- System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = pi;
- size++;
- }
- modCount++;
- }
-
- /**
- * Check and add the <code>CDATA</code> to this list at
- * the given index.
- *
- * @param index index where to add <code>CDATA</code>
- * @param cdata <code>CDATA</code> to add
- */
- void add(int index, CDATA cdata) {
- if (cdata == null) {
- throw new IllegalAddException("Cannot add null object");
- }
-
- if (parent instanceof Document) {
- throw new IllegalAddException(
- "A CDATA is not allowed at the document root");
- }
-
- if (cdata.getParent() != null) {
- throw new IllegalAddException(
- "The CDATA already has an existing parent \"" +
- ((Element)cdata.getParent()).getQualifiedName() + "\"");
- }
-
- if (index<0 || index>size) {
- throw new IndexOutOfBoundsException("Index: " + index +
- " Size: " + size());
- }
-
- cdata.setParent((Element) parent);
-
- ensureCapacity(size+1);
- if( index==size ) {
- elementData[size++] = cdata;
- } else {
- System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = cdata;
- size++;
- }
- modCount++;
- }
-
- /**
- * Check and add the <code>Text</code> to this list at
- * the given index.
- *
- * @param index index where to add <code>Text</code>
- * @param text <code>Text</code> to add
- */
- void add(int index, Text text) {
- if (text == null) {
- throw new IllegalAddException("Cannot add null object");
- }
-
- if (parent instanceof Document) {
- throw new IllegalAddException(
- "A Text not allowed at the document root");
- }
-
- if (text.getParent() != null) {
- throw new IllegalAddException(
- "The Text already has an existing parent \"" +
- ((Element)text.getParent()).getQualifiedName() + "\"");
- }
-
- if (index<0 || index>size) {
- throw new IndexOutOfBoundsException("Index: " + index +
- " Size: " + size());
- }
-
- text.setParent((Element) parent);
-
- ensureCapacity(size+1);
- if( index==size ) {
- elementData[size++] = text;
- } else {
- System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = text;
- size++;
- }
- modCount++;
- }
-
- /**
- * Check and add the <code>EntityRef</code> to this list at
- * the given index.
- *
- * @param index index where to add <code>Entity</code>
- * @param entity <code>Entity</code> to add
- */
- void add(int index, EntityRef entity) {
- if (entity == null) {
- throw new IllegalAddException("Cannot add null object");
- }
-
- if (parent instanceof Document) {
+ if (child == parent) {
throw new IllegalAddException(
- "An EntityRef is not allowed at the document root");
+ "The Element cannot be added to itself");
}
- if (entity.getParent() != null) {
+ if ((parent instanceof Element && child instanceof Element) &&
+ ((Element) parent).isAncestor((Element)child)) {
throw new IllegalAddException(
- "The EntityRef already has an existing parent \"" +
- ((Element)entity.getParent()).getQualifiedName() + "\"");
+ "The Element cannot be added as a descendent of itself");
}
if (index<0 || index>size) {
@@ -492,14 +174,14 @@ void add(int index, EntityRef entity) {
" Size: " + size());
}
- entity.setParent((Element) parent);
+ child.setParent(parent);
ensureCapacity(size+1);
if( index==size ) {
- elementData[size++] = entity;
+ elementData[size++] = child;
} else {
System.arraycopy(elementData, index, elementData, index + 1, size - index);
- elementData[index] = entity;
+ elementData[index] = child;
size++;
}
modCount++;
@@ -580,7 +262,7 @@ public void clear() {
* @param collection The collection to use.
*/
void clearAndSet(Collection collection) {
- Object[] old = elementData;
+ Child[] old = elementData;
int oldSize = size;
elementData = null;
@@ -615,7 +297,7 @@ void clearAndSet(Collection collection) {
*/
void ensureCapacity(int minCapacity) {
if( elementData==null ) {
- elementData = new Object[Math.max(minCapacity, INITIAL_ARRAY_SIZE)];
+ elementData = new Child[Math.max(minCapacity, INITIAL_ARRAY_SIZE)];
} else {
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
@@ -623,7 +305,7 @@ void ensureCapacity(int minCapacity) {
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
- elementData = new Object[newCapacity];
+ elementData = new Child[newCapacity];
System.arraycopy(oldData, 0, elementData, 0, size);
}
}
diff --git a/core/src/java/org/jdom/DocType.java b/core/src/java/org/jdom/DocType.java
index 3db130adf..12b36bc8a 100644
--- a/core/src/java/org/jdom/DocType.java
+++ b/core/src/java/org/jdom/DocType.java
@@ -1,6 +1,6 @@
/*--
- $Id: DocType.java,v 1.26 2003/05/20 21:53:59 jhunter Exp $
+ $Id: DocType.java,v 1.27 2004/02/06 03:39:03 jhunter Exp $
Copyright (C) 2000 Jason Hunter & Brett McLaughlin.
All rights reserved.
@@ -62,12 +62,12 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*
* @author Brett McLaughlin
* @author Jason Hunter
- * @version $Revision: 1.26 $, $Date: 2003/05/20 21:53:59 $
+ * @version $Revision: 1.27 $, $Date: 2004/02/06 03:39:03 $
*/
-public class DocType implements Child {
+public class DocType extends Child {
private static final String CVS_ID =
- "@(#) $RCSfile: DocType.java,v $ $Revision: 1.26 $ $Date: 2003/05/20 21:53:59 $ $Name: $";
+ "@(#) $RCSfile: DocType.java,v $ $Revision: 1.27 $ $Date: 2004/02/06 03:39:03 $ $Name: $";
/** The element being constrained */
protected String elementName;
@@ -78,9 +78,6 @@ public class DocType implements Child {
/** The system ID of the DOCTYPE */
protected String systemID;
- /** The document having this DOCTYPE */
- protected Document parent;
-
/** The internal subset of the DOCTYPE */
protected String internalSubset;
@@ -236,28 +233,6 @@ public DocType setSystemID(String systemID) {
return this;
}
- public Child detach() {
- if (parent != null) {
- parent.removeContent(this);
- }
- return this;
- }
-
- /**
- * This retrieves the owning <code>{@link Document}</code> for
- * this DocType, or null if not a currently a member of a
- * <code>{@link Document}</code>.
- *
- * @return <code>Document</code> owning this DocType, or null.
- */
- public Document getDocument() {
- return parent;
- }
-
- public Parent getParent() {
- return parent;
- }
-
/**
* Returns the empty string since doctypes don't have an XPath
* 1.0 string value.
@@ -267,17 +242,6 @@ public String getValue() {
return ""; // doctypes don't have an XPath string value
}
- /**
- * This sets the <code>{@link Document}</code> holding this doctype.
- *
- * @param parent parent document holding this doctype
- * @return <code>Document</code> this <code>DocType</code> modified
- */
- protected DocType setParent(Document parent) {
- this.parent = parent;
- return this;
- }
-
/**
* This sets the data for the internal subset.
*
@@ -335,24 +299,4 @@ public final int hashCode() {
return super.hashCode();
}
- /**
- * This will return a clone of this <code>DocType</code>.
- *
- * @return <code>Object</code> - clone of this <code>DocType</code>.
- */
- public Object clone() {
- DocType docType = null;
-
- try {
- docType = (DocType) super.clone();
- } catch (CloneNotSupportedException ce) {
- // Can't happen
- }
-
- docType.parent = null;
-
- // elementName, publicID, and systemID are all immutable
- // (Strings) and references are copied by Object.clone()
- return docType;
- }
}
diff --git a/core/src/java/org/jdom/Document.java b/core/src/java/org/jdom/Document.java
index 71ccfcac4..f952bb082 100644
--- a/core/src/java/org/jdom/Document.java
+++ b/core/src/java/org/jdom/Document.java
@@ -1,6 +1,6 @@
/*--
- $Id: Document.java,v 1.74 2004/02/05 10:45:33 jhunter Exp $
+ $Id: Document.java,v 1.75 2004/02/06 03:39:03 jhunter Exp $
Copyright (C) 2000 Jason Hunter & Brett McLaughlin.
All rights reserved.
@@ -63,7 +63,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* An XML document. Methods allow access to the root element as well as the
* {@link DocType} and other document-level information.
*
- * @version $Revision: 1.74 $, $Date: 2004/02/05 10:45:33 $
+ * @version $Revision: 1.75 $, $Date: 2004/02/06 03:39:03 $
* @author Brett McLaughlin
* @author Jason Hunter
* @author Jools Enticknap
@@ -72,7 +72,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
public class Document implements Parent {
private static final String CVS_ID =
- "@(#) $RCSfile: Document.java,v $ $Revision: 1.74 $ $Date: 2004/02/05 10:45:33 $ $Name: $";
+ "@(#) $RCSfile: Document.java,v $ $Revision: 1.75 $ $Date: 2004/02/06 03:39:03 $ $Name: $";
/**
* This document's content including comments, PIs, a possible
@@ -677,4 +677,49 @@ public Document(List newContent, DocType docType) {
setContent(newContent);
setDocType(docType);
}
+
+ /**
+ * @see org.jdom.Parent#getDocument()
+ */
+ public Document getDocument() {
+ return this;
+ }
+
+ /**
+ * @see org.jdom.ContentList#add(int, org.jdom.Child)
+ */
+ public void canContain(Child child, int index) throws IllegalAddException {
+ if (child instanceof Element) {
+ if (child instanceof Element && content.indexOfFirstElement() >= 0) {
+ throw new IllegalAddException(
+ "Cannot add a second root element, only one is allowed");
+ }
+ if (child instanceof Element && content.indexOfDocType() > index) {
+ throw new IllegalAddException(
+ "A root element cannot be added before the DocType");
+ }
+ }
+ if (child instanceof DocType) {
+ if (content.indexOfDocType() >= 0) {
+ throw new IllegalAddException(
+ "Cannot add a second doctype, only one is allowed");
+ }
+ int firstElt = content.indexOfFirstElement();
+ if (firstElt != -1 && firstElt < index) {
+ throw new IllegalAddException(
+ "A DocType cannot be added after the root element");
+ }
+ }
+ if (child instanceof CDATA) {
+ throw new IllegalAddException("A CDATA is not allowed at the document root");
+ }
+
+ if (child instanceof Text) {
+ throw new IllegalAddException("A Text is not allowed at the document root");
+ }
+
+ if (child instanceof EntityRef) {
+ throw new IllegalAddException("An EntityRef is not allowed at the document root");
+ }
+ }
}
diff --git a/core/src/java/org/jdom/Element.java b/core/src/java/org/jdom/Element.java
index f9a46a9bc..ec4e9c197 100644
--- a/core/src/java/org/jdom/Element.java
+++ b/core/src/java/org/jdom/Element.java
@@ -1,6 +1,6 @@
/*--
- $Id: Element.java,v 1.139 2003/06/18 02:59:44 jhunter Exp $
+ $Id: Element.java,v 1.140 2004/02/06 03:39:03 jhunter Exp $
Copyright (C) 2000 Jason Hunter & Brett McLaughlin.
All rights reserved.
@@ -66,7 +66,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* elements and content, directly access the element's textual content,
* manipulate its attributes, and manage namespaces.
*
- * @version $Revision: 1.139 $, $Date: 2003/06/18 02:59:44 $
+ * @version $Revision: 1.140 $, $Date: 2004/02/06 03:39:03 $
* @author Brett McLaughlin
* @author Jason Hunter
* @author Lucas Gonze
@@ -78,10 +78,10 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* @author Alex Rosen
* @author Bradley S. Huffman
*/
-public class Element implements Parent, Child {
+public class Element extends Child implements Parent {
private static final String CVS_ID =
- "@(#) $RCSfile: Element.java,v $ $Revision: 1.139 $ $Date: 2003/06/18 02:59:44 $ $Name: $";
+ "@(#) $RCSfile: Element.java,v $ $Revision: 1.140 $ $Date: 2004/02/06 03:39:03 $ $Name: $";
private static final int INITIAL_ARRAY_SIZE = 5;
@@ -386,16 +386,6 @@ public List getAdditionalNamespaces() {
return Collections.unmodifiableList(additionalNamespaces);
}
- /**
- * Returns the parent of this element or null if unattached. The parent
- * can be either a Document or Element.
- *
- * @return parent of this element
- */
- public Parent getParent() {
- return parent;
- }
-
/**
* Returns the XPath 1.0 string value of this element, which is the
* complete, ordered content of all text node descendants of this element
@@ -417,34 +407,6 @@ public String getValue() {
return buffer.toString();
}
- /**
- * Sets the parent of this element. The caller is responsible for removing
- * any pre-existing parentage.
- *
- * @param parent new parent element
- * @return the target element
- */
- protected Element setParent(Parent parent) {
- this.parent = parent;
- return this;
- }
-
- /**
- * Detaches the element from its element parent or document, or does nothing
- * if the element has no parent.
- *
- * @return the target element
- */
- public Child detach() {
- if (parent instanceof Element) {
- parent.removeContent(this);
- }
- else if (parent instanceof Document) {
- ((Document) parent).detachRootElement();
- }
- return this;
- }
-
/**
* Returns whether this element is a root element. This can be used in
* tandem with {@link #getParent} to determine if an element has any
@@ -474,23 +436,6 @@ public int indexOf(Child child) {
// return -1;
// }
- /**
- * Returns the owning document for this element, or null if it's not a
- * currently a member of a document.
- *
- * @return the document owning this element, or null if
- * none
- */
- public Document getDocument() {
- if (parent instanceof Document) {
- return (Document) parent;
- }
- if (parent instanceof Element) {
- return ((Element)parent).getDocument();
- }
-
- return null;
- }
/**
* Returns the textual content directly held under this element as a string.
@@ -1436,18 +1381,15 @@ public Object clone() {
Element element = null;
- try {
element = (Element) super.clone();
- } catch (CloneNotSupportedException ce) {
- // Can't happen
- }
// name and namespace are references to immutable objects
// so super.clone() handles them ok
// Reference to parent is copied by super.clone()
// (Object.clone()) so we have to remove it
- element.parent = null;
+ // Actually, super is a Child, which has already detached in the clone().
+ // element.parent = null;
// Reference to content list and attribute lists are copyed by
// super.clone() so we set it new lists if the original had lists
@@ -1770,4 +1712,12 @@ public boolean removeChildren(String name, Namespace ns) {
return deletedSome;
}
+
+ public void canContain(Child child, int index) throws IllegalAddException {
+ if (child instanceof DocType) {
+ throw new IllegalAddException(
+ "A DocType is not allowed except at the document level");
+ }
+ }
+
}
diff --git a/core/src/java/org/jdom/EntityRef.java b/core/src/java/org/jdom/EntityRef.java
index 425ad2776..f76d010e9 100644
--- a/core/src/java/org/jdom/EntityRef.java
+++ b/core/src/java/org/jdom/EntityRef.java
@@ -1,36 +1,36 @@
-/*--
+/*--
- $Id: EntityRef.java,v 1.16 2003/06/04 17:40:52 jhunter Exp $
+ $Id: EntityRef.java,v 1.17 2004/02/06 03:39:03 jhunter Exp $
Copyright (C) 2000 Jason Hunter & Brett McLaughlin.
All rights reserved.
-
+
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
-
+
1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
-
+
2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions, and the disclaimer that follows
- these conditions in the documentation and/or other materials
+ notice, this list of conditions, and the disclaimer that follows
+ these conditions in the documentation and/or other materials
provided with the distribution.
3. The name "JDOM" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact <request_AT_jdom_DOT_org>.
-
+
4. Products derived from this software may not be called "JDOM", nor
may "JDOM" appear in their name, without prior written permission
from the JDOM Project Management <request_AT_jdom_DOT_org>.
-
- In addition, we request (but do not require) that you include in the
- end-user documentation provided with the redistribution and/or in the
+
+ In addition, we request (but do not require) that you include in the
+ end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed by the
JDOM Project (http://www.jdom.org/)."
- Alternatively, the acknowledgment may be graphical using the logos
+ Alternatively, the acknowledgment may be graphical using the logos
available at http://www.jdom.org/images/logos.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
@@ -46,12 +46,12 @@ 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.
- This software consists of voluntary contributions made by many
- individuals on behalf of the JDOM Project and was originally
+ This software consists of voluntary contributions made by many
+ individuals on behalf of the JDOM Project and was originally
created by Jason Hunter <jhunter_AT_jdom_DOT_org> and
Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information
on the JDOM Project, please see <http://www.jdom.org/>.
-
+
*/
package org.jdom;
@@ -59,16 +59,16 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
/**
* An XML entity reference. Methods allow the user to manage its name, public
* id, and system id.
- *
- * @version $Revision: 1.16 $, $Date: 2003/06/04 17:40:52 $
+ *
+ * @version $Revision: 1.17 $, $Date: 2004/02/06 03:39:03 $
* @author Brett McLaughlin
* @author Jason Hunter
* @author Philip Nelson
*/
-public class EntityRef implements Child {
+public class EntityRef extends Child {
- private static final String CVS_ID =
- "@(#) $RCSfile: EntityRef.java,v $ $Revision: 1.16 $ $Date: 2003/06/04 17:40:52 $ $Name: $";
+ private static final String CVS_ID =
+ "@(#) $RCSfile: EntityRef.java,v $ $Revision: 1.17 $ $Date: 2004/02/06 03:39:03 $ $Name: $";
/** The name of the <code>EntityRef</code> */
protected String name;
@@ -79,9 +79,6 @@ public class EntityRef implements Child {
/** The SystemID of the <code>EntityRef</code> */
protected String systemID;
- /** Parent element or null if none */
- protected Element parent;
-
/**
* Default, no-args constructor for implementations to use if needed.
*/
@@ -129,43 +126,6 @@ public EntityRef(String name, String publicID, String systemID) {
setSystemID(systemID);
}
- /**
- * This will return a clone of this <code>EntityRef</code>.
- *
- * @return <code>Object</code> - clone of this <code>EntityRef</code>.
- */
- public Object clone() {
- EntityRef entity = null;
-
- try {
- entity = (EntityRef) super.clone();
- } catch (CloneNotSupportedException ce) {
- // Can't happen
- }
-
- // name is a reference to an immutable (String) object
- // and is copied by Object.clone()
-
- // The parent reference is copied by Object.clone(), so
- // must set to null
- entity.parent = null;
-
- return entity;
- }
-
- /**
- * This detaches the <code>Entity</code> from its parent, or does nothing
- * if the <code>Entity</code> has no parent.
- *
- * @return <code>Entity</code> - this <code>Entity</code> modified.
- */
- public Child detach() {
- if (parent != null) {
- parent.removeContent(this);
- }
- return this;
- }
-
/**
* This tests for equality of this <code>Entity</code> to the supplied
* <code>Object</code>.
@@ -178,21 +138,6 @@ public final boolean equals(Object ob) {
return (ob == this);
}
- /**
- * This retrieves the owning <code>{@link Document}</code> for
- * this Entity, or null if not a currently a member of a
- * <code>{@link Document}</code>.
- *
- * @return <code>Document</code> owning this Entity, or null.
- */
- public Document getDocument() {
- if (parent != null) {
- return parent.getDocument();
- }
-
- return null;
- }
-
/**
* This returns the name of the <code>EntityRef</code>.
*
@@ -202,16 +147,6 @@ public String getName() {
return name;
}
- /**
- * This will return the parent of this <code>EntityRef</code>.
- * If there is no parent, then this returns <code>null</code>.
- *
- * @return parent of this <code>EntityRef</code>
- */
- public Parent getParent() {
- return parent;
- }
-
/**
* Returns the empty string since entity references don't have an XPath
* 1.0 string value.
@@ -250,17 +185,6 @@ public final int hashCode() {
return super.hashCode();
}
- /**
- * This will set the parent of this <code>Entity</code>.
- *
- * @param parent <code>Element</code> to be new parent.
- * @return this <code>Entity</code> modified.
- */
- protected EntityRef setParent(Element parent) {
- this.parent = parent;
- return this;
- }
-
/**
* This will set the name of this <code>EntityRef</code>.
*
diff --git a/core/src/java/org/jdom/Parent.java b/core/src/java/org/jdom/Parent.java
index 69ccac26d..ca735b70c 100644
--- a/core/src/java/org/jdom/Parent.java
+++ b/core/src/java/org/jdom/Parent.java
@@ -1,6 +1,6 @@
/*--
- $Id: Parent.java,v 1.6 2004/02/05 10:45:33 jhunter Exp $
+ $Id: Parent.java,v 1.7 2004/02/06 03:39:03 jhunter Exp $
Copyright (C) 2000 Brett McLaughlin & Jason Hunter.
All rights reserved.
@@ -70,7 +70,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*
* @author Bradley S. Huffman
* @author Jason Hunter
- * @version $Revision: 1.6 $, $Date: 2004/02/05 10:45:33 $
+ * @version $Revision: 1.7 $, $Date: 2004/02/06 03:39:03 $
*/
public interface Parent extends Cloneable, Serializable {
@@ -360,4 +360,23 @@ public interface Parent extends Cloneable, Serializable {
* @return this parent's parent or null if none
*/
Parent getParent();
+
+ /**
+ * Return this parent's owning document or null if the branch containing
+ * this parent is currently not attached to a document.
+ *
+ * @return this child's owning document or null if none
+ */
+ Document getDocument();
+
+ /**
+ * Checks if this parent can contain the given child at the specified
+ * position, throwing a descriptive IllegalAddException if not and
+ * simply returning if it's allowed.
+ *
+ * @param child the potential child to be added to this parent
+ * @param index the location for the potential child
+ * @throws IllegalAddException if the child add isn't allowed
+ */
+ void canContain(Child child, int index) throws IllegalAddException;
}
diff --git a/core/src/java/org/jdom/ProcessingInstruction.java b/core/src/java/org/jdom/ProcessingInstruction.java
index b93051232..94564a3d3 100644
--- a/core/src/java/org/jdom/ProcessingInstruction.java
+++ b/core/src/java/org/jdom/ProcessingInstruction.java
@@ -1,6 +1,6 @@
/*--
- $Id: ProcessingInstruction.java,v 1.40 2003/05/20 21:53:59 jhunter Exp $
+ $Id: ProcessingInstruction.java,v 1.41 2004/02/06 03:39:03 jhunter Exp $
Copyright (C) 2000 Jason Hunter & Brett McLaughlin.
All rights reserved.
@@ -64,16 +64,16 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* if the data appears akin to an attribute list, can be retrieved as name/value
* pairs.
*
- * @version $Revision: 1.40 $, $Date: 2003/05/20 21:53:59 $
+ * @version $Revision: 1.41 $, $Date: 2004/02/06 03:39:03 $
* @author Brett McLaughlin
* @author Jason Hunter
* @author Steven Gould
*/
-public class ProcessingInstruction implements Child {
+public class ProcessingInstruction extends Child {
private static final String CVS_ID =
- "@(#) $RCSfile: ProcessingInstruction.java,v $ $Revision: 1.40 $ $Date: 2003/05/20 21:53:59 $ $Name: $";
+ "@(#) $RCSfile: ProcessingInstruction.java,v $ $Revision: 1.41 $ $Date: 2004/02/06 03:39:03 $ $Name: $";
/** The target of the PI */
protected String target;
@@ -84,9 +84,6 @@ public class ProcessingInstruction implements Child {
/** The data for the PI in name/value pairs */
protected Map mapData;
- /** Parent element, document, or null if none */
- protected Parent parent;
-
/**
* Default, no-args constructor for implementations
* to use if needed.
@@ -139,19 +136,6 @@ public ProcessingInstruction setTarget(String newTarget) {
return this;
}
- /**
- * This will return the parent of this <code>ProcessingInstruction</code>.
- * If there is no parent, then this returns <code>null</code>.
- *
- * @return parent of this <code>ProcessingInstruction</code>
- */
- public Parent getParent() {
- if (parent instanceof Element) {
- return (Element) parent;
- }
- return null;
- }
-
/**
* Returns the XPath 1.0 string value of this element, which is the
* data of this PI.
@@ -162,49 +146,6 @@ public String getValue() {
return rawData;
}
- /**
- * <p>
- * This will set the parent of this <code>ProcessingInstruction</code>.
- * </p>
- *
- * @param parent <code>Element</code> to be new parent.
- * @return this <code>ProcessingInstruction</code> modified.
- */
- protected ProcessingInstruction setParent(Parent parent) {
- this.parent = parent;
- return this;
- }
-
- /**
- * This detaches the PI from its parent, or does nothing if the
- * PI has no parent.
- *
- * @return <code>ProcessingInstruction</code> - this
- * <code>ProcessingInstruction</code> modified.
- */
- public Child detach() {
- if (parent != null) {
- parent.removeContent(this);
- }
- return this;
- }
-
- /**
- * This retrieves the owning <code>{@link Document}</code> for
- * this PI, or null if not a currently a member of a
- * <code>{@link Document}</code>.
- *
- * @return <code>Document</code> owning this PI, or null.
- */
- public Document getDocument() {
- if (parent instanceof Document) {
- return (Document) parent;
- }
- if (parent instanceof Element) {
- return ((Element)parent).getDocument();
- }
- return null;
- }
/**
* This will retrieve the target of the PI.
@@ -593,26 +534,15 @@ public final int hashCode() {
* <code>ProcessingInstruction</code>.
*/
public Object clone() {
- ProcessingInstruction pi = null;
-
- try {
- pi = (ProcessingInstruction) super.clone();
- } catch (CloneNotSupportedException ce) {
- // Can't happen
- }
+ ProcessingInstruction pi = (ProcessingInstruction) super.clone();
// target and rawdata are immutable and references copied by
// Object.clone()
- // parent reference is copied by Object.clone(), so
- // must set to null
- pi.parent = null;
-
// Create a new Map object for the clone (since Map isn't Cloneable)
if (mapData != null) {
pi.mapData = parseData(rawData);
}
-
return pi;
}
}
diff --git a/core/src/java/org/jdom/Text.java b/core/src/java/org/jdom/Text.java
index 521c33e98..627b433f2 100644
--- a/core/src/java/org/jdom/Text.java
+++ b/core/src/java/org/jdom/Text.java
@@ -1,6 +1,6 @@
/*--
- $Id: Text.java,v 1.18 2003/05/29 02:47:40 jhunter Exp $
+ $Id: Text.java,v 1.19 2004/02/06 03:39:03 jhunter Exp $
Copyright (C) 2000 Jason Hunter & Brett McLaughlin.
All rights reserved.
@@ -61,15 +61,15 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* representing text. Text makes no guarantees about the underlying textual
* representation of character data, but does expose that data as a Java String.
*
- * @version $Revision: 1.18 $, $Date: 2003/05/29 02:47:40 $
+ * @version $Revision: 1.19 $, $Date: 2004/02/06 03:39:03 $
* @author Brett McLaughlin
* @author Jason Hunter
* @author Bradley S. Huffman
*/
-public class Text implements Child {
+public class Text extends Child {
private static final String CVS_ID =
- "@(#) $RCSfile: Text.java,v $ $Revision: 1.18 $ $Date: 2003/05/29 02:47:40 $ $Name: $";
+ "@(#) $RCSfile: Text.java,v $ $Revision: 1.19 $ $Date: 2004/02/06 03:39:03 $ $Name: $";
static final String EMPTY_STRING = "";
@@ -80,7 +80,7 @@ public class Text implements Child {
protected String value;
/** This <code>Text</code> node's parent. */
- protected Element parent;
+ protected Parent parent;
/**
* This is the protected, no-args constructor standard in all JDOM
@@ -230,16 +230,6 @@ public void append(Text text) {
value += text.getText();
}
- /**
- * This will return the parent of this <code>Text</code> node, which
- * is always a JDOM <code>{@link Element}</code>.
- *
- * @return <code>Element</code> - this node's parent.
- */
- public Parent getParent() {
- return parent;
- }
-
/**
* Returns the XPath 1.0 string value of this element, which is the
* text itself.
@@ -250,20 +240,6 @@ public String getValue() {
return value;
}
- /**
- * This retrieves the owning <code>{@link Document}</code> for
- * this <code>Text</code>, or null if not a currently a member
- * of a <code>{@link Document}</code>.
- *
- * @return <code>Document</code> owning this <code>Text</code>, or null.
- */
- public Document getDocument() {
- if (parent != null) {
- return parent.getDocument();
- }
- return null;
- }
-
/**
* This will set the parent of the <code>Text</code> node to the supplied
* <code>{@link Element}</code>. This method is intentionally left as
@@ -276,24 +252,11 @@ public Document getDocument() {
*
* @param parent parent for this node.
*/
- protected Text setParent(Element parent) {
+ protected Child setParent(Parent parent) {
this.parent = parent;
return this;
}
- /**
- * Detaches the <code>Text</code> from its parent, or does nothing
- * if the <code>Text</code> has no parent.
- *
- * @return <code>Text</code> - this <code>Text</code> modified.
- */
- public Child detach() {
- if (parent != null) {
- parent.removeContent(this);
- }
- return this;
- }
-
/**
* This returns a <code>String</code> representation of the
* <code>Text</code> node, suitable for debugging. If the XML
@@ -328,17 +291,8 @@ public final int hashCode() {
* @return <code>Text</code> - cloned node.
*/
public Object clone() {
- Text text = null;
-
- try {
- text = (Text)super.clone();
- } catch (CloneNotSupportedException ce) {
- // Can't happen
- }
-
- text.parent = null;
+ Text text = (Text)super.clone();
text.value = value;
-
return text;
}
|
b4bf8bc29803a1355d23331f68cc6b41d9313c79
|
gitools$gitools
|
Advanced filter functionality in the Biomart import module
git-svn-id: https://bg.upf.edu/svn/gitools/trunk@851 1b512f91-3386-4a98-81e7-b8836ddf8916
|
p
|
https://github.com/gitools/gitools
|
diff --git a/gitools-biomart/src/main/java/org/gitools/biomart/restful/model/PushAction.java b/gitools-biomart/src/main/java/org/gitools/biomart/restful/model/PushAction.java
index 8c21acd1..550d772d 100644
--- a/gitools-biomart/src/main/java/org/gitools/biomart/restful/model/PushAction.java
+++ b/gitools-biomart/src/main/java/org/gitools/biomart/restful/model/PushAction.java
@@ -48,7 +48,7 @@ public class PushAction {
@XmlAttribute
private String orderBy;
- @XmlElementWrapper
+ //@XmlElementWrapper
@XmlElement(name = "Option")
private List<Option> options;
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterCheckBoxComponent.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterCheckBoxComponent.java
index e48ab039..1d0858d5 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterCheckBoxComponent.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterCheckBoxComponent.java
@@ -18,6 +18,8 @@
package org.gitools.ui.biomart.filter;
import java.awt.GridLayout;
+import java.util.ArrayList;
+import java.util.List;
import javax.swing.JCheckBox;
import org.gitools.biomart.restful.model.Filter;
import org.gitools.biomart.restful.model.FilterDescription;
@@ -90,7 +92,9 @@ private void buildComponent() {
@Override
// FIXME : Check if get filter from check value/s is correct
- public Filter getFilter() {
+ public List<Filter> getFilters() {
+
+ List<Filter> filters = new ArrayList<Filter>();
Filter f = new Filter();
@@ -102,7 +106,10 @@ public Filter getFilter() {
if (checkBox.isSelected())
f.setValue(checkBox.getText());
- return f;
+
+ filters.add(f);
+
+ return filters;
}
@@ -138,5 +145,10 @@ private String[] getListTextOptions() {
}
return res;
}
+
+ @Override
+ public void setListOptions(List<Option> optionList) {
+ return;
+ }
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterCollectionPanel.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterCollectionPanel.java
index a95ba7d3..5a7c747a 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterCollectionPanel.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterCollectionPanel.java
@@ -79,6 +79,10 @@ private void buildDescriptions(FilterCollection fc) {
validate();
}
+ public JPanel getDescriptionsPanel() {
+ return descriptionsPanel;
+ }
+
/**
* Render Label descriptions when more than 1 descriptions per collection
* @param fc
@@ -111,7 +115,35 @@ public Integer getCurrentHeigh() {
return currentHeight + DEFAULT_COLLECTION_PANEL_HEIGHT;
}
+ public List<Filter> getFilters(){
+
+
+ List<Filter> filters = new ArrayList<Filter>();
+ List<Filter> filtersAux = null;
+
+ if (collectionCheckBox.isSelected())
+ {
+ // Obtain the filters involved for this event
+ for (Component compo : descriptionsPanel.getComponents()) {
+
+ filtersAux = ((FilterDescriptionPanel) compo).getFilters();
+
+ for (Filter f : filtersAux)
+
+ if ((f.getName() != null)&& (f.getValue() != null) && (!f.getValue().equals("")))
+
+ filters.add(f);
+ }
+ }
+ return filters;
+ }
+
+ public BiomartFilterConfigurationPage getFilterConfigurationPage() {
+ return filterConfigurationPage;
+ }
+
+
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
@@ -176,28 +208,5 @@ private void stateChangedAction(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:
// End of variables declaration//GEN-END:variables
- public List<Filter> getFilters(){
-
-
- Filter f = null;
- List<Filter> filters = new ArrayList<Filter>();
-
- if (collectionCheckBox.isSelected())
- {
- // Obtain the filters involved for this event
- for (Component compo : descriptionsPanel.getComponents()) {
-
- f = ((FilterDescriptionPanel) compo).getFilter();
- if ((f.getName() != null)&& (f.getValue() != null) && (!f.getValue().equals("")))
- filters.add(f);
-
- }
- }
- return filters;
- }
-
- public BiomartFilterConfigurationPage getFilterConfigurationPage() {
- return filterConfigurationPage;
- }
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterComponent.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterComponent.java
index 593c1cc9..5c4d9862 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterComponent.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterComponent.java
@@ -16,6 +16,7 @@
*/
package org.gitools.ui.biomart.filter;
+import java.util.List;
import javax.swing.JPanel;
import org.gitools.biomart.restful.model.FilterDescription;
import org.gitools.biomart.restful.model.Option;
@@ -23,11 +24,16 @@
public abstract class FilterComponent extends JPanel implements IFilterComponent {
protected FilterComponent childComponent;
- protected FilterDescriptionPanel parentPanel;
- protected FilterDescription filterDescription;
+
+ protected FilterDescriptionPanel parentPanel;
+
+ protected FilterDescription filterDescription;
+
protected Option filterOptions;
+
protected Integer currentHeight;
+
FilterComponent(FilterDescription d, FilterDescriptionPanel parent) {
filterDescription = d;
parentPanel = parent;
@@ -66,4 +72,15 @@ public FilterDescriptionPanel getDescriptionPanel() {
public Integer getCurrentHeight() {
return currentHeight;
}
+
+ public FilterDescription getFilterDescription() {
+ return filterDescription;
+ }
+
+ /**
+ * Set options model of a comboBox component.
+ * This operation is used for implement the PushAction
+ * mechanism
+ */
+ public abstract void setListOptions(List<Option> optionList);
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterDescriptionPanel.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterDescriptionPanel.java
index d95c1c12..c8b4ece9 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterDescriptionPanel.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterDescriptionPanel.java
@@ -22,8 +22,8 @@
*/
package org.gitools.ui.biomart.filter;
+import java.util.List;
import javax.swing.BoxLayout;
-import org.gitools.biomart.BiomartServiceException;
import org.gitools.biomart.restful.model.DatasetConfig;
import org.gitools.biomart.restful.model.DatasetInfo;
import org.gitools.biomart.restful.model.Filter;
@@ -34,9 +34,6 @@
import org.gitools.biomart.restful.model.Option;
import org.gitools.ui.platform.AppFrame;
import org.gitools.ui.platform.dialog.ExceptionDialog;
-import org.gitools.ui.platform.AppFrame;
-import org.gitools.ui.platform.dialog.ExceptionDialog;
-import org.gitools.ui.platform.dialog.MessageStatus;
public class FilterDescriptionPanel extends javax.swing.JPanel {
@@ -54,80 +51,108 @@ public FilterDescriptionPanel(FilterDescription description, FilterCollectionPan
this.currentHeight = 0;
this.renderLabel = labelRendered;
-
if (filterDescription.getDisplayType() != null) {
+
this.renderPanel = true;
+
buildComponent();
+
}
else if (filterDescription.getPointerDataset() != null) {
- //FIXME: MAKE it in thread
- //getParentCollection().getFilterConfigurationPage().setMessage(MessageStatus.PROGRESS, "Retrieving available filters ...");
- //new Thread(new Runnable() {
- // @Override public void run() {
-
try {
-
DatasetInfo d = new DatasetInfo();
+
d.setName(filterDescription.getPointerDataset());
+
d.setInterface(filterDescription.getPointerInterface());
- DatasetConfig configuration = null;
- configuration = getParentCollection().getFilterConfigurationPage().getBiomartService().getConfiguration(d);
- buildPointerFilterComponents(configuration);
- getParentCollection().getFilterConfigurationPage().setMessage(MessageStatus.INFO, "");
+
+ DatasetConfig configuration = getParentCollection().getFilterConfigurationPage().getBiomartService().getConfiguration(d);
+
+ buildPointerFilterComponents(configuration);
+
renderPanel = true;
}
catch (final Exception ex) {
- ExceptionDialog dlg = new ExceptionDialog(AppFrame.instance(), ex);
- dlg.setVisible(true);
+
+ System.out.println("Pointer dataset :" +filterDescription.getPointerDataset()+ " has not been found");
+
renderPanel = false;
+
return;
}
- //}
- //}).start();
- } else {
- this.renderPanel = false;
- }
+ } else this.renderPanel = false;
+
}
- /** This method is called from within the constructor to
- * initialize the form.
- * WARNING: Do NOT modify this code. The content of this method is
- * always regenerated by the Form Editor.
+/**
+ * BuildPointer elements with default options if it is the case
+ * @param configuration
+ * @param DefaultOptions
*/
- @SuppressWarnings("unchecked")
- // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
- private void initComponents() {
+ private void buildPointerFilterComponents(DatasetConfig configuration) {
- javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
- this.setLayout(layout);
- layout.setHorizontalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGap(0, 396, Short.MAX_VALUE)
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGap(0, 298, Short.MAX_VALUE)
- );
- }// </editor-fold>//GEN-END:initComponents
+ for (FilterPage page : configuration.getFilterPages())
- // Variables declaration - do not modify//GEN-BEGIN:variables
- // End of variables declaration//GEN-END:variables
+ if (page.getHideDisplay() == null || !page.getHideDisplay().equals("true"))
+
+ for (FilterGroup group : page.getFilterGroups())
+
+ if (group.getHideDisplay() == null || !group.getHideDisplay().equals("true"))
+
+ for (FilterCollection collection : group.getFilterCollections())
+
+ for (FilterDescription desc : collection.getFilterDescriptions())
+
+ if ((desc.getInternalName().equals(filterDescription.getPointerFilter()))
+ && (desc.getHideDisplay() == null || !desc.getHideDisplay().equals("true"))) {
+
+ this.renderPanel = true;
+
+ // WARN: This code is for solving bugs in xml config avoiding build combos
+ // where it is not the case
+ // SOLUTION is check if component receives pushactions then it is a
+ // combo component!
+
+ if (parentCollection.getFilterConfigurationPage().
+ getDefaultSelecComposData().get(filterDescription.getPointerFilter()) != null){
+
+ desc.setStyle("menu");
+
+ desc.setDisplayType("list");
+
+ }
+
+ filterDescription = desc;
+
+ buildComponent();
+
+ }
+ }
+
+ /**
+ * Builds components for the filterDescription
+ */
private void buildComponent() {
String displayType = filterDescription.getDisplayType();
+
String multipleValues = filterDescription.getMultipleValues();
+
String style = filterDescription.getStyle();
+
String graph = filterDescription.getGraph();
+
FilterComponent child = null;
if (displayType.equals("container")) {
String displayStyleOption = filterDescription.getOptions().get(0).getDisplayType();
+
String multipleValuesOption = filterDescription.getOptions().get(0).getMultipleValues();
FilterComponent componentParent = new FilterSelecComponent(filterDescription, this);
@@ -136,29 +161,47 @@ private void buildComponent() {
if (displayStyleOption.equals("list")) {
+
if (multipleValuesOption != null && multipleValuesOption.equals("1")) {
+
child = new FilterCheckBoxComponent(filterOptions);
+
} else {
+
child = new FilterRadioComponent(filterOptions);
}
} else if (displayStyleOption.equals("text")) {
+
child = new FilterTextComponent(filterOptions);
}
componentParent.addChildComponent(child);
+
filterComponent = componentParent;
} else {
if (displayType.equals("list")) {
if (style.equals("menu") && (graph == null || !graph.equals("1"))) {
- filterComponent = new FilterSelecComponent(filterDescription, this);
+
+ FilterSelecComponent selecComponent = new FilterSelecComponent(filterDescription, this);
+
+ //Retrieve PushAction Data from default option
+ parentCollection.getFilterConfigurationPage().storeSelecComponentsDefaultData(selecComponent.getPushActionData_defaultOption());
+
+ filterComponent =selecComponent;
+
} else if (style.equals("menu") && graph != null && graph.equals("1")) {
+
filterComponent = new FilterTextComponent(filterDescription, this);
+
} else if (multipleValues != null && multipleValues.equals("1")) {
+
filterComponent = new FilterCheckBoxComponent(filterDescription, this);
+
} else {
+
filterComponent = new FilterRadioComponent(filterDescription, this);
}
@@ -166,6 +209,11 @@ private void buildComponent() {
filterComponent = new FilterTextComponent(filterDescription, this);
}
+ else
+ {
+ System.out.println("Component "+ filterDescription.getInternalName() +"has not been builded");
+ return;
+ }
}
@@ -188,6 +236,31 @@ private void buildComponent() {
validate();
}
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGap(0, 396, Short.MAX_VALUE)
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGap(0, 298, Short.MAX_VALUE)
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ // End of variables declaration//GEN-END:variables
+
public FilterDescription getFilterDescription() {
return filterDescription;
}
@@ -196,8 +269,8 @@ public FilterCollectionPanel getParentCollection() {
return parentCollection;
}
- public Filter getFilter() {
- return filterComponent.getFilter();
+ public List<Filter> getFilters() {
+ return filterComponent.getFilters();
}
public void setFilterComponents(FilterComponent components) {
@@ -228,24 +301,7 @@ public void setRenderLabel(Boolean renderLabel) {
this.renderLabel = renderLabel;
}
- private void buildPointerFilterComponents(DatasetConfig configuration) {
- for (FilterPage page : configuration.getFilterPages()) {
- if (page.getHideDisplay() == null || !page.getHideDisplay().equals("true")) {
- for (FilterGroup group : page.getFilterGroups()) {
- if (group.getHideDisplay() == null || !group.getHideDisplay().equals("true")) {
- for (FilterCollection collection : group.getFilterCollections()) {
- for (FilterDescription desc : collection.getFilterDescriptions()) {
- if ((desc.getInternalName().equals(filterDescription.getPointerFilter())) && (desc.getHideDisplay() == null || !desc.getHideDisplay().equals("true"))) {
- this.renderPanel = true;
- filterDescription = desc;
- buildComponent();
+
+
- }
- }
- }
- }
- }
- }
- }
- }
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterRadioComponent.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterRadioComponent.java
index 0c25865a..c351fd24 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterRadioComponent.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterRadioComponent.java
@@ -18,7 +18,9 @@
package org.gitools.ui.biomart.filter;
import java.awt.GridLayout;
+import java.util.ArrayList;
import java.util.Enumeration;
+import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JRadioButton;
import org.gitools.biomart.restful.model.Filter;
@@ -100,9 +102,12 @@ private void buildComponent() {
@Override
// FIXME : Check if get filter from radio value/s is correct
- public Filter getFilter() {
+ public List<Filter> getFilters() {
+
+ List<Filter> filters = new ArrayList<Filter>();
Filter f = new Filter();
+
JRadioButton r = null;
// Could happen filterDescription null, if this component is a child (belongs to a container component)
@@ -129,7 +134,9 @@ public Filter getFilter() {
}
}
- return f;
+ filters.add(f);
+
+ return filters;
}
@@ -165,5 +172,10 @@ private String[] getListTextOptions() {
}
return res;
}
+
+ @Override
+ public void setListOptions(List<Option> optionList) {
+ return;
+ }
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterSelecComponent.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterSelecComponent.java
index bf01ed9c..56bda9a8 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterSelecComponent.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterSelecComponent.java
@@ -23,13 +23,21 @@
package org.gitools.ui.biomart.filter;
+import java.awt.Component;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import org.gitools.biomart.restful.model.Filter;
import org.gitools.biomart.restful.model.FilterDescription;
+import org.gitools.biomart.restful.model.FilterGroup;
+import org.gitools.biomart.restful.model.FilterPage;
import org.gitools.biomart.restful.model.Option;
+import org.gitools.biomart.restful.model.PushAction;
+import org.gitools.ui.biomart.wizard.BiomartFilterConfigurationPage.CollectionsPanelsCache;
public class FilterSelecComponent extends FilterComponent {
@@ -60,17 +68,37 @@ public String toString() {
//Members of class
private String component;
+
private final Integer COMBO_HEIGHT = 45;
+
private final Integer LIST_HEIGHT = 190;
+ private HashMap <Option,HashMap<String,List<Option>>> pushActions; // N options, each one with its list of components and options to show
+
- /** Creates new form FilterSelecComponent1 */
public FilterSelecComponent(FilterDescription d,FilterDescriptionPanel collectionParent) {
super(d,collectionParent);
+
initComponents();
+ pushActions = new HashMap <Option,HashMap<String,List<Option>>>();
+
buildComponent();
+
+ if (component.equals("ComboBox") && pushActions.size()>0)
+ {
+ comboComponent.addItemListener(new ItemListener() {
+ @Override public void itemStateChanged(ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.SELECTED){
+
+ setPushOptionsComponent(((OptionListWrapper) comboComponent.getSelectedItem()).getOption());
+
+ }
+
+ }
+ });
+ }
}
/** This method is called from within the constructor to
@@ -121,22 +149,33 @@ private void initComponents() {
private void buildComponent() {
List<OptionListWrapper> options = InitListOptions();
+
if (filterDescription.getMultipleValues() == null || !filterDescription.getMultipleValues().equals("1")) {
component = "ComboBox";
comboComponent.setVisible(true);
+
comboComponent.setAlignmentY(TOP_ALIGNMENT);
jScrollPane1.setVisible(false);
+
listComponent.setVisible(false);
+
listComponent.setAlignmentY(BOTTOM_ALIGNMENT);
DefaultComboBoxModel m = new DefaultComboBoxModel();
+
for (OptionListWrapper o : options) m.addElement(o);
+
comboComponent.setModel(m);
+
currentHeight = COMBO_HEIGHT;
+ //process pushActions
+ if (filterDescription != null) loadPushActions();
+
+
} else {
component = "List";
@@ -158,7 +197,58 @@ private void buildComponent() {
}
+ private void setPushOptionsComponent(Option optionSelected)
+ {
+
+ //search and set component options
+
+ HashMap<FilterPage, CollectionsPanelsCache> collectionsCache = getDescriptionPanel().getParentCollection().getFilterConfigurationPage().getCollectionsCache();
+
+ FilterDescriptionPanel descriptionPanel = null;
+
+ FilterComponent filterCompo = null;
+
+ //System.out.println("Actions: "+pushActions.keySet());
+
+
+ for (FilterPage page :collectionsCache.keySet())
+
+ for(FilterGroup group : collectionsCache.get(page).collections.keySet())
+ {
+ //System.out.println("Group: "+group.getInternalName());
+
+ for (FilterCollectionPanel panel : collectionsCache.get(page).collections.get(group))
+
+ for ( Component componentPanel : panel.getDescriptionsPanel().getComponents())
+ {
+
+ descriptionPanel = ((FilterDescriptionPanel) componentPanel);
+
+ for (Component compo : descriptionPanel.getComponents())
+ {
+
+ filterCompo = (FilterComponent) compo;
+
+ if (filterCompo.getFilterDescription() != null && filterCompo.getFilterDescription().getInternalName() != null)
+ {
+ //System.out.println ("Component: "+filterCompo.getFilterDescription().getInternalName());
+
+ if (pushActions.get(optionSelected).get(filterCompo.getFilterDescription().getInternalName()) != null)
+ {
+ //System.out.println ("options; "+ pushActions.get(optionSelected).get(filterCompo.getFilterDescription().getInternalName()));
+
+ filterCompo.setListOptions(pushActions.get(optionSelected).get(filterCompo.getFilterDescription().getInternalName()));
+
+ }
+ }
+ }
+ }
+ }
+ }
+
+
private List<OptionListWrapper> InitListOptions() {
+
List<OptionListWrapper> res = new ArrayList<OptionListWrapper>();
for (Option o : filterDescription.getOptions())
@@ -166,33 +256,102 @@ private List<OptionListWrapper> InitListOptions() {
OptionListWrapper wrapper = new OptionListWrapper(o);
res.add(wrapper);
}
+
+ // Load default options from some component with push action
+ if (parentPanel != null && parentPanel.getParentCollection().getFilterConfigurationPage().getDefaultSelecComposData().size()>0)
+ {
+ if (parentPanel.getParentCollection().getFilterConfigurationPage().
+ getDefaultSelecComposData().get(filterDescription.getInternalName()) != null)
+
+ for (Option o : parentPanel.getParentCollection().getFilterConfigurationPage().
+ getDefaultSelecComposData().get(filterDescription.getInternalName()))
+ {
+
+ OptionListWrapper wrapper = new OptionListWrapper(o);
+
+ res.add(wrapper);
+ }
+ }
return res;
}
+ /**
+ * Load PushActions of component
+ */
+ private void loadPushActions() {
+
+ for (Option o : filterDescription.getOptions())
+ {
+ if (o.getPushactions() != null)
+ {
+ HashMap<String,List<Option>> actions = new HashMap<String,List<Option>>();
+
+ for (PushAction action : o.getPushactions()){
+
+ actions.put(action.getRef(), action.getOptions());
+ }
+ pushActions.put(o,actions);
+ }
+
+ }
+
+ }
+
@Override
// FIXME : get Filter for selected value/s in list
- public Filter getFilter() {
+ public List<Filter> getFilters() {
+
+ List<Filter> filters = new ArrayList<Filter>();
- Filter f = new Filter();
+ Filter f = null;
if (hasChild()) {
- f.setName(((OptionListWrapper) comboComponent.getSelectedItem()).getOption().getInternalName());
- f.setValue(getChildComponent().getFilter().getValue());
- f.setRadio(getChildComponent().getFilter().getRadio());
+ if (component.equals("ComboBox"))
+ {
+ f = new Filter();
+
+ f.setName(((OptionListWrapper) comboComponent.getSelectedItem()).getOption().getInternalName());
+
+ f.setValue(getChildComponent().getFilters().get(0).getValue());
+
+ f.setRadio(getChildComponent().getFilters().get(0).getRadio());
+
+ filters.add(f);
+ }
+ else
+ {
+ for (Object optionWrapper : listComponent.getSelectedValues())
+ {
+ f = new Filter();
+
+ f.setName(((OptionListWrapper) optionWrapper).getOption().getInternalName());
+
+ f.setValue(getChildComponent().getFilters().get(0).getValue());
+
+ f.setRadio(getChildComponent().getFilters().get(0).getRadio());
+
+ filters.add(f);
+ }
+ }
+
}
else {
+ f = new Filter();
+
f.setName(filterDescription.getInternalName());
if (component.equals("ComboBox"))
{
if (comboComponent.getSelectedItem() != null)
+
f.setValue(comboComponent.getSelectedItem().toString());
}
else {
String selStr = "";
+
if (listComponent.getSelectedValues() !=null && listComponent.getSelectedValues().length>0)
{
String res = null;
@@ -210,8 +369,9 @@ public Filter getFilter() {
}
}
+ filters.add(f);
}
- return f;
+ return filters;
}
@Override
@@ -221,5 +381,50 @@ public Boolean hasChanged() {
}
+ @Override
+ public void setListOptions(List<Option> optionList) {
+
+ if (this.component.equals("ComboBox")) {
+
+ DefaultComboBoxModel m = new DefaultComboBoxModel();
+
+ for (Option o : optionList) m.addElement(new OptionListWrapper(o));
+
+ comboComponent.setModel(m);
+
+ }
+ else
+ {
+
+ DefaultListModel m = new DefaultListModel();
+
+ for (Option o : optionList) m.addElement(new OptionListWrapper(o));
+
+ listComponent.setModel(m);
+
+ }
+ }
+
+ public HashMap<Option, HashMap<String, List<Option>>> getPushActions() {
+
+ return pushActions;
+ }
+
+ public HashMap<String, List<Option>> getPushActionData_defaultOption() {
+
+ if (pushActions.size()>0)
+
+ if (component.equals("ComboBox"))
+
+ return pushActions.get(((OptionListWrapper) comboComponent.getSelectedItem()).getOption());
+
+ else
+
+ return pushActions.get(((OptionListWrapper) listComponent.getSelectedValue()).getOption());
+
+ else
+
+ return new HashMap<String, List<Option>>();
+ }
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterTextComponent.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterTextComponent.java
index 7ca98299..33bf5772 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterTextComponent.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/FilterTextComponent.java
@@ -21,6 +21,8 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import org.gitools.ui.utils.FileChooserUtils;
import org.gitools.biomart.restful.model.Filter;
@@ -48,8 +50,8 @@ public class FilterTextComponent extends FilterComponent {
FilterTextComponent(Option o) {
super(o);
- initComponents();
+ initComponents();
buildComponent();
@@ -142,8 +144,21 @@ private void selectFileAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event
"Select file", folder.getText(), FileChooserUtils.MODE_OPEN);
if (selPath != null) {
+
folder.setText(selPath.getAbsolutePath());
+
+ try {
+
+ txtArea.setText(readFileAsString(folder.getText()));
+
+ } catch (IOException ex) {
+ ExceptionDialog dlg = new ExceptionDialog(AppFrame.instance(), ex);
+ dlg.setVisible(true);
+ }
+
+
}
+
}//GEN-LAST:event_selectFileAction
// Variables declaration - do not modify//GEN-BEGIN:variables
@@ -166,12 +181,13 @@ private void buildComponent() {
if (parentPanel != null && parentPanel.getRenderLabel())
nameDescription.setVisible(true);
- else
+ else
nameDescription.setVisible(false);
if (filterDescription != null)
{
txt = filterDescription.getDefaultValue() != null ? filterDescription.getDefaultValue() : "";
+
if (filterDescription.getMultipleValues() == null || !filterDescription.getMultipleValues().equals("1"))
component = "Field";
else
@@ -182,6 +198,7 @@ private void buildComponent() {
if (filterOptions != null)
{
txt = filterOptions.getDefaultValue() != null ? filterOptions.getDefaultValue() : "";
+
if (filterOptions.getMultipleValues() == null || !filterOptions.getMultipleValues().equals("1"))
component = "Field";
else
@@ -193,13 +210,16 @@ private void buildComponent() {
if (component.equals("Field"))
{
txtField.setAlignmentY(TOP_ALIGNMENT);
+
txtField.setText(txt);
+
txtField.setVisible(true);
jScrollPane1.setVisible(false);
+
txtArea.setVisible(false);
- browsePanel.setVisible(false);
+ browsePanel.setVisible(false);
currentHeight = FIELD_HEIGHT;
}
@@ -208,25 +228,34 @@ private void buildComponent() {
component = "TextArea";
jScrollPane1.setAlignmentY(TOP_ALIGNMENT);
+
jScrollPane1.setVisible(true);
+
txtArea.setAlignmentY(TOP_ALIGNMENT);
+
txtArea.setVisible(true);
+
txtArea.setText("");
+
browsePanel.setVisible(true);
txtField.setVisible(false);
+
txtField.setAlignmentY(BOTTOM_ALIGNMENT);
currentHeight = TEXTAREA_HEIGHT;
}
if (filterDescription!= null && filterDescription.getDisplayName() != null)
+
nameDescription.setText(filterDescription.getDisplayName());
}
@Override
- public Filter getFilter() {
+ public List<Filter> getFilters() {
+
+ List<Filter> filters = new ArrayList<Filter>();
Filter f = new Filter();
@@ -235,28 +264,23 @@ public Filter getFilter() {
if (filterDescription != null && filterDescription.getInternalName() != null)
f.setName(filterDescription.getInternalName());
- if (component.equals("Field")) {
+ if (component.equals("Field"))
f.setValue(txtField.getText());
- } else {
- if (folder.getText() == null || folder.getText().equals(""))
- f.setValue(txtArea.getText().replace("\n", ","));
- else
- {
- try {
-
- f.setValue(readFileAsString(folder.getText()).replace("\n", ","));
- f.setValue(f.getValue().replace("\\", "\\\\"));
- f.setValue(f.getValue().replace("\"", "\\\""));
- while (f.getValue().startsWith(",")) f.setValue(f.getValue().substring(1));
-
- } catch (IOException ex) {
- ExceptionDialog dlg = new ExceptionDialog(AppFrame.instance(), ex);
- dlg.setVisible(true);
- }
- }
- }
-
- return f;
+
+ else
+ f.setValue(txtArea.getText().replace("\n", ","));
+
+ f.setValue(f.getValue().replace("\\", "\\\\"));
+
+ f.setValue(f.getValue().replace("\"", "\\\""));
+
+ while (f.getValue().startsWith(",")) f.setValue(f.getValue().substring(1));
+ while (f.getValue().endsWith(","))
+ f.setValue(f.getValue().substring(0,f.getValue().length()-1));
+
+ filters.add(f);
+
+ return filters;
}
@Override
@@ -286,4 +310,8 @@ private static String readFileAsString(String filePath) throws java.io.IOExcepti
return new String(buffer);
}
+ @Override
+ public void setListOptions(List<Option> optionList) {
+ return;
+ }
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/IFilterComponent.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/IFilterComponent.java
index 937b8792..099d64d7 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/IFilterComponent.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/filter/IFilterComponent.java
@@ -17,11 +17,12 @@
package org.gitools.ui.biomart.filter;
+import java.util.List;
import org.gitools.biomart.restful.model.Filter;
interface IFilterComponent {
- public Filter getFilter();
+ public List<Filter> getFilters();
public Boolean hasChanged();
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/panel/BiomartAttributeListPanel.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/panel/BiomartAttributeListPanel.java
index 33bb532c..51cb8e16 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/panel/BiomartAttributeListPanel.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/panel/BiomartAttributeListPanel.java
@@ -272,6 +272,16 @@ private void removeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIR
model.removeElement(o);
}//GEN-LAST:event_removeBtnActionPerformed
+ public void removeAllListAttributes(){
+
+ if (attrList.getModel() == null) return;
+
+ DefaultListModel model = (DefaultListModel) attrList.getModel();
+
+ if (model != null) model.removeAllElements();
+
+
+ }
private void upBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_upBtnActionPerformed
DefaultListModel model = (DefaultListModel) attrList.getModel();
int[] indices = attrList.getSelectedIndices();
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartAttributeListPage.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartAttributeListPage.java
index ddba4260..520cb15c 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartAttributeListPage.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartAttributeListPage.java
@@ -25,6 +25,7 @@
import org.gitools.biomart.restful.model.DatasetInfo;
import org.gitools.biomart.restful.BiomartRestfulService;
import org.gitools.biomart.restful.model.AttributeDescription;
+import org.gitools.biomart.restful.model.DatasetConfig;
import org.gitools.biomart.restful.model.MartLocation;
import org.gitools.ui.biomart.panel.BiomartAttributeListPanel;
@@ -44,6 +45,10 @@ public class BiomartAttributeListPage extends AbstractWizardPage {
private BiomartAttributeListPanel panel;
private BiomartRestfulService biomartService;
+
+ private DatasetConfig biomartConfig;
+
+ private Boolean reloadData; //determine whether update panel data
public BiomartAttributeListPage() {
}
@@ -63,24 +68,34 @@ public JComponent createControls() {
@Override
public void updateControls() {
//panel.setAddBtnEnabled(false);
- panel.setAttributePages(null);
- setStatus(MessageStatus.PROGRESS);
- setMessage("Retrieving available attributes ...");
+ if (panel != null && reloadData)
+ panel.removeAllListAttributes();
+
+ panel.setAttributePages(null);
if (panel.getAttributePages() == null) {
new Thread(new Runnable() {
@Override public void run() {
+
updateControlsThread();
+ reloadData = false; //To avoid reload data when back button
+
}
}).start();
}
+
+
}
private void updateControlsThread() {
try {
- if (attrPages == null)
- attrPages = biomartService.getAttributes(mart, dataset);
+ if (attrPages == null || reloadData){
+ setStatus(MessageStatus.PROGRESS);
+ setMessage("Retrieving available attributes ...");
+ biomartConfig = biomartService.getConfiguration(dataset);
+ attrPages = biomartConfig.getAttributePages();
+ }
SwingUtilities.invokeAndWait(new Runnable() {
@Override public void run() {
@@ -108,13 +123,23 @@ private void updateControlsThread() {
panel.setAttributePages(attrPages);
}*/
- public void setSource(BiomartRestfulService biomartService, MartLocation mart, DatasetInfo dataset) {
+ public void setSource(BiomartRestfulService biomartService, MartLocation mart, DatasetInfo ds) {
+
+ if (this.dataset != null && this.dataset.getName().equals(ds.getName()))
+ reloadData = false;
+ else
+ reloadData = true;
+
this.biomartService = biomartService;
this.mart = mart;
- this.dataset = dataset;
+ this.dataset = ds;
}
public List<AttributeDescription> getAttributeList() {
return panel.getAttributeList();
}
+
+ public DatasetConfig getBiomartConfig() {
+ return biomartConfig;
+ }
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartAttributePage.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartAttributePage.java
index 8809e34b..ddb208bb 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartAttributePage.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartAttributePage.java
@@ -16,6 +16,7 @@
import org.gitools.biomart.restful.model.DatasetInfo;
import org.gitools.biomart.restful.model.MartLocation;
import org.gitools.biomart.restful.BiomartRestfulService;
+import org.gitools.biomart.restful.model.DatasetConfig;
import org.gitools.ui.biomart.panel.AttributesTreeModel;
import org.gitools.ui.biomart.panel.AttributesTreeModel.AttributeWrapper;
@@ -35,9 +36,11 @@ public class BiomartAttributePage extends FilteredTreePage {
private AttributeDescription attribute;
- private boolean updated;
-
private BiomartRestfulService biomartService;
+
+ private DatasetConfig biomartConfig;
+
+ private Boolean reloadData; //determine whether update panel data
public BiomartAttributePage() {
super();
@@ -45,8 +48,7 @@ public BiomartAttributePage() {
this.mart = null;
this.dataset = null;
this.attrPages = null;
-
- updated = false;
+
}
@Override
@@ -66,11 +68,6 @@ public JComponent createControls() {
@Override
public void updateControls() {
- if (updated)
- return;
-
- setStatus(MessageStatus.PROGRESS);
- setMessage("Retrieving available attributes ...");
setComplete(false);
@@ -79,10 +76,13 @@ public void updateControls() {
new Thread(new Runnable() {
@Override public void run() {
try {
- if (attrPages == null) {
- attrPages = biomartService.getAttributes(mart, dataset);
+ if (attrPages == null || reloadData) {
+ setStatus(MessageStatus.PROGRESS);
+ setMessage("Retrieving available attributes ...");
- setAttributePages(attrPages);
+ biomartConfig = biomartService.getConfiguration(dataset);
+ attrPages = biomartConfig.getAttributePages();
+
}
final AttributesTreeModel model = new AttributesTreeModel(attrPages);
@@ -96,7 +96,6 @@ public void updateControls() {
}
});
- updated = true;
}
catch (final Throwable cause) {
SwingUtilities.invokeLater(new Runnable() {
@@ -129,15 +128,20 @@ private void selectionChanged() {
}
public void setSource(BiomartRestfulService biomartService, MartLocation mart, DatasetInfo dataset) {
+
+ if (this.dataset != null && this.dataset.getName().equals(dataset.getName()))
+ reloadData = false;
+ else
+ reloadData = true;
+
this.biomartService = biomartService;
this.mart = mart;
this.dataset = dataset;
-
}
public synchronized void setAttributePages(List<AttributePage> attrPages) {
this.attrPages = attrPages;
- updated = false;
+ reloadData = false;
}
public synchronized List<AttributePage> getAttributePages() {
@@ -152,4 +156,8 @@ public AttributeDescription getAttribute() {
protected TreeModel createModel(String filterText) {
return new AttributesTreeModel(attrPages, filterText);
}
+
+ public DatasetConfig getBiomartConfig() {
+ return biomartConfig;
+ }
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartFilterConfigurationPage.form b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartFilterConfigurationPage.form
index 818f857e..eec17c3f 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartFilterConfigurationPage.form
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartFilterConfigurationPage.form
@@ -23,18 +23,14 @@
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
- <Group type="102" alignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
<EmptySpace max="-2" attributes="0"/>
- <Group type="103" groupAlignment="0" attributes="0">
- <Group type="102" alignment="0" attributes="0">
- <Component id="filterGroupList" min="-2" pref="195" max="-2" attributes="0"/>
- <EmptySpace max="-2" attributes="0"/>
- <Component id="scrollPanel" pref="333" max="32767" attributes="0"/>
- </Group>
- <Group type="102" alignment="0" attributes="0">
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="jSplitPane1" alignment="0" pref="558" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
- <Component id="filterPageCombo" pref="494" max="32767" attributes="0"/>
+ <Component id="filterPageCombo" pref="518" max="32767" attributes="0"/>
</Group>
</Group>
<EmptySpace max="-2" attributes="0"/>
@@ -49,11 +45,8 @@
<Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="filterPageCombo" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
- <EmptySpace type="separate" max="-2" attributes="0"/>
- <Group type="103" groupAlignment="0" attributes="0">
- <Component id="scrollPanel" pref="362" max="32767" attributes="0"/>
- <Component id="filterGroupList" alignment="0" pref="362" max="32767" attributes="0"/>
- </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jSplitPane1" pref="386" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
@@ -61,56 +54,124 @@
</Layout>
<SubComponents>
<Component class="javax.swing.JComboBox" name="filterPageCombo">
- <Events>
- <EventHandler event="propertyChange" listener="java.beans.PropertyChangeListener" parameters="java.beans.PropertyChangeEvent" handler="filterPageComboPropertyChange"/>
- </Events>
</Component>
<Component class="javax.swing.JLabel" name="jLabel1">
<Properties>
<Property name="text" type="java.lang.String" value="Page"/>
</Properties>
</Component>
- <Component class="javax.swing.JList" name="filterGroupList">
+ <Container class="javax.swing.JSplitPane" name="jSplitPane1">
<Properties>
- <Property name="selectionMode" type="int" value="0"/>
- </Properties>
- <Events>
- <EventHandler event="valueChanged" listener="javax.swing.event.ListSelectionListener" parameters="javax.swing.event.ListSelectionEvent" handler="filterGroupListValueChanged"/>
- </Events>
- </Component>
- <Container class="javax.swing.JScrollPane" name="scrollPanel">
- <Properties>
- <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
- <Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo">
- <EmptyBorder bottom="0" left="0" right="0" top="0"/>
- </Border>
- </Property>
- <Property name="viewportBorder" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
- <Border info="null"/>
- </Property>
+ <Property name="dividerLocation" type="int" value="198"/>
+ <Property name="continuousLayout" type="boolean" value="true"/>
</Properties>
- <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout"/>
<SubComponents>
- <Container class="javax.swing.JPanel" name="collectionsPanel">
- <Properties>
- <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
- <Border info="null"/>
- </Property>
- </Properties>
+ <Container class="javax.swing.JPanel" name="jPanel1">
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
+ <JSplitPaneConstraints position="left"/>
+ </Constraint>
+ </Constraints>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
- <EmptySpace min="0" pref="333" max="32767" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="filterGroupList" pref="186" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
- <EmptySpace min="0" pref="362" max="32767" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="filterGroupList" pref="362" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
</Group>
</DimensionLayout>
</Layout>
+ <SubComponents>
+ <Component class="javax.swing.JList" name="filterGroupList">
+ <Properties>
+ <Property name="selectionMode" type="int" value="0"/>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Container class="javax.swing.JPanel" name="jPanel2">
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JSplitPaneSupportLayout$JSplitPaneConstraintsDescription">
+ <JSplitPaneConstraints position="right"/>
+ </Constraint>
+ </Constraints>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <EmptySpace min="0" pref="354" max="32767" attributes="0"/>
+ <Group type="103" rootIndex="1" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="scrollPanel" pref="342" max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <EmptySpace min="0" pref="386" max="32767" attributes="0"/>
+ <Group type="103" rootIndex="1" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="scrollPanel" pref="362" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JScrollPane" name="scrollPanel">
+ <Properties>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo">
+ <EmptyBorder bottom="0" left="0" right="0" top="0"/>
+ </Border>
+ </Property>
+ <Property name="viewportBorder" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="null"/>
+ </Property>
+ </Properties>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Container class="javax.swing.JPanel" name="collectionsPanel">
+ <Properties>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="null"/>
+ </Property>
+ </Properties>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <EmptySpace min="0" pref="342" max="32767" attributes="0"/>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <EmptySpace min="0" pref="362" max="32767" attributes="0"/>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ </Container>
+ </SubComponents>
+ </Container>
+ </SubComponents>
</Container>
</SubComponents>
</Container>
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartFilterConfigurationPage.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartFilterConfigurationPage.java
index c2f1c931..e50e8b04 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartFilterConfigurationPage.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartFilterConfigurationPage.java
@@ -18,6 +18,8 @@
package org.gitools.ui.biomart.wizard;
import java.awt.Dimension;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@@ -27,6 +29,8 @@
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
import org.gitools.biomart.restful.BiomartRestfulService;
import org.gitools.biomart.restful.model.DatasetConfig;
import org.gitools.biomart.restful.model.FilterGroup;
@@ -34,6 +38,7 @@
import org.gitools.biomart.restful.model.DatasetInfo;
import org.gitools.biomart.restful.model.Filter;
import org.gitools.biomart.restful.model.FilterCollection;
+import org.gitools.biomart.restful.model.Option;
import org.gitools.ui.biomart.filter.FilterCollectionPanel;
import org.gitools.ui.platform.AppFrame;
import org.gitools.ui.platform.dialog.ExceptionDialog;
@@ -91,17 +96,28 @@ public String toString() {
return res;
}
}
+
private final Integer FILTER_PANEL_WEIGHT = 333;
+
private final Integer FILTER_PANEL_HEIGHT = 330;
private DatasetInfo dataset;
- private DatasetConfig dsConfiguration;
+
+ private DatasetConfig biomartConfig;
+
private BiomartRestfulService biomartService;
+
private FilterGroup lastGroupSelected;
+
+ private FilterPage lastPageSelected;
+
private HashMap<String,Filter> filters;
- private HashMap<FilterPage,CollectionsPanelsCache> collectionsCache; // Attribute to retain user panel selections
- private Boolean updateFilterData; //When to update panel data
+ private HashMap<FilterPage,CollectionsPanelsCache> collectionsCache; // Stores component panel selections
+
+ private Boolean reloadData; //determine whether update panel data
+
+ private HashMap<String, List<Option>> defaultSelecComposData; //Stores default selection component data
public static class CollectionsPanelsCache{
@@ -118,63 +134,48 @@ public BiomartFilterConfigurationPage() {
initComponents();
- collectionsCache = null;
lastGroupSelected = null;
- updateFilterData = true;
+
+ lastPageSelected = null;
+
+ reloadData = true;
filters = new HashMap<String,Filter>();
+
collectionsCache = new HashMap<FilterPage, CollectionsPanelsCache>();
setComplete(true); //Next button always is true, input filters is not mandatory
- }
+ filterPageCombo.addItemListener(new ItemListener() {
+ @Override public void itemStateChanged(ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.SELECTED){
+ if (filterPageCombo.getSelectedItem() != null) {
- @Override
- public JComponent createControls() {
- return this;
- }
+ updateGroupFilterList(((PageListWrapper) filterPageCombo.getSelectedItem()).getFilterPage());
- /**
- * Method called each time this class is shown in the application
- * All components from collections panel are cleaned, to avoid wrong
- * component visualisations
- *
- */
- @Override
- public void updateControls() {
+ lastPageSelected = ((PageListWrapper) filterPageCombo.getSelectedItem()).getFilterPage();
+ }
+ }
+ }
+ });
- //Clean main collections panel
- collectionsPanel.removeAll();
- collectionsPanel.setPreferredSize(new Dimension(FILTER_PANEL_WEIGHT,FILTER_PANEL_HEIGHT));
- lastGroupSelected = null;
-
- if (updateFilterData) {
- setMessage(MessageStatus.PROGRESS, "Retrieving available filters ...");
- new Thread(new Runnable() {
- @Override public void run() {
- try {
- dsConfiguration = biomartService.getConfiguration(dataset);
- setMessage(MessageStatus.INFO, "");
- updatePageFilterList();
- initCollectionsCache();
- }
- catch (final Exception ex) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override public void run() {
- setStatus(MessageStatus.ERROR);
- setMessage(ex.getMessage());
- }
- });
- ExceptionDialog dlg = new ExceptionDialog(AppFrame.instance(), ex);
- dlg.setVisible(true);
- }
+ filterGroupList.addListSelectionListener(new ListSelectionListener() {
+ @Override public void valueChanged(ListSelectionEvent e) {
+ if (filterPageCombo.getModel().getSelectedItem() != null && filterGroupList.getSelectedValue() != null)
+ {
+ updateCollectionControls(((PageListWrapper) filterPageCombo.getModel().getSelectedItem()).getFilterPage(),
+ ((GroupListWrapper) filterGroupList.getSelectedValue()).getFilterGroup());
+
+ lastGroupSelected = ((GroupListWrapper) filterGroupList.getSelectedValue()).getFilterGroup();
}
+ }
+ });
- }).start();
- }
}
+
+
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
@@ -186,26 +187,39 @@ private void initComponents() {
filterPageCombo = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
+ jSplitPane1 = new javax.swing.JSplitPane();
+ jPanel1 = new javax.swing.JPanel();
filterGroupList = new javax.swing.JList();
+ jPanel2 = new javax.swing.JPanel();
scrollPanel = new javax.swing.JScrollPane();
collectionsPanel = new javax.swing.JPanel();
setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
- filterPageCombo.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
- public void propertyChange(java.beans.PropertyChangeEvent evt) {
- filterPageComboPropertyChange(evt);
- }
- });
-
jLabel1.setText("Page");
+ jSplitPane1.setDividerLocation(198);
+ jSplitPane1.setContinuousLayout(true);
+
filterGroupList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
- filterGroupList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
- public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
- filterGroupListValueChanged(evt);
- }
- });
+
+ javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
+ jPanel1.setLayout(jPanel1Layout);
+ jPanel1Layout.setHorizontalGroup(
+ jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel1Layout.createSequentialGroup()
+ .addComponent(filterGroupList, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ jPanel1Layout.setVerticalGroup(
+ jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel1Layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(filterGroupList, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+
+ jSplitPane1.setLeftComponent(jPanel1);
scrollPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
scrollPanel.setViewportBorder(null);
@@ -216,7 +230,7 @@ public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
collectionsPanel.setLayout(collectionsPanelLayout);
collectionsPanelLayout.setHorizontalGroup(
collectionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGap(0, 333, Short.MAX_VALUE)
+ .addGap(0, 342, Short.MAX_VALUE)
);
collectionsPanelLayout.setVerticalGroup(
collectionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
@@ -225,21 +239,40 @@ public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
scrollPanel.setViewportView(collectionsPanel);
+ javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
+ jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(
+ jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGap(0, 354, Short.MAX_VALUE)
+ .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel2Layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(scrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)))
+ );
+ jPanel2Layout.setVerticalGroup(
+ jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGap(0, 386, Short.MAX_VALUE)
+ .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanel2Layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(scrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
+ .addContainerGap()))
+ );
+
+ jSplitPane1.setRightComponent(jPanel2);
+
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addComponent(filterGroupList, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(scrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE))
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
+ .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 558, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(filterPageCombo, 0, 494, Short.MAX_VALUE)))
+ .addComponent(filterPageCombo, 0, 518, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
@@ -249,159 +282,215 @@ public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(filterPageCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGap(18, 18, 18)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(scrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
- .addComponent(filterGroupList, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
- private void filterGroupListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_filterGroupListValueChanged
-
- updateCollectionControls();
-
- }//GEN-LAST:event_filterGroupListValueChanged
-
- private void filterPageComboPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_filterPageComboPropertyChange
-
- updateGroupFilterList();
-
- }//GEN-LAST:event_filterPageComboPropertyChange
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel collectionsPanel;
private javax.swing.JList filterGroupList;
private javax.swing.JComboBox filterPageCombo;
private javax.swing.JLabel jLabel1;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JPanel jPanel2;
+ private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JScrollPane scrollPanel;
// End of variables declaration//GEN-END:variables
+ @Override
+ public JComponent createControls() {
+ return this;
+ }
+
+ /**
+ * Method called each time this class is shown in the application
+ * All components from collections panel are cleaned, to avoid wrong
+ * component visualisations
+ *
+ */
+ @Override
+ public void updateControls() {
+
+ //Clean main collections panel
+ collectionsPanel.removeAll();
+
+ collectionsPanel.setPreferredSize(new Dimension(FILTER_PANEL_WEIGHT,FILTER_PANEL_HEIGHT));
+
+ filterGroupList.clearSelection();
+
+ lastGroupSelected = null;
+
+ lastPageSelected = null;
+
+ if (reloadData) {
+
+ setMessage(MessageStatus.PROGRESS, "Retrieving available filters ...");
+
+ new Thread(new Runnable() {
+ @Override public void run() {
+ try {
+
+ defaultSelecComposData = new HashMap<String, List<Option>>();
+
+ initCollectionsCache();
+
+ updatePageFilterList();
+
+ lastPageSelected = ((PageListWrapper) filterPageCombo.getSelectedItem()).getFilterPage();
+
+ setMessage(MessageStatus.INFO, "");
+
+ reloadData = false;
+
+ }
+ catch (final Exception ex) {
+ SwingUtilities.invokeLater(new Runnable() {
+ @Override public void run() {
+ setStatus(MessageStatus.ERROR);
+ setMessage(ex.getMessage());
+ }
+ });
+ ExceptionDialog dlg = new ExceptionDialog(AppFrame.instance(), ex);
+ dlg.setVisible(true);
+ System.out.println(ex);
+ }
+ }
+
+ }).start();
+ }
+ }
+
public void updatePageFilterList() {
+
DefaultComboBoxModel model = new DefaultComboBoxModel();
- for (FilterPage p : dsConfiguration.getFilterPages()) {
+ for (FilterPage p : biomartConfig.getFilterPages()) {
if (p.getHideDisplay() == null || !p.getHideDisplay().equals("true")) {
+
model.addElement(new PageListWrapper(p));
+ updateGroupFilterList(p);
+
}
}
this.filterPageCombo.setModel(model);
- updateGroupFilterList();
-
}
- private void updateGroupFilterList() {
+ private void updateGroupFilterList(FilterPage page) {
+
+ // Avoid update process when null value or unaltered filter group selection
+ if (lastPageSelected != null
+ && lastPageSelected.getInternalName().equals(page.getInternalName())) {
+
+ return;
+ }
//Clean main collections panel
collectionsPanel.removeAll();
+
collectionsPanel.setPreferredSize(new Dimension(FILTER_PANEL_WEIGHT,FILTER_PANEL_HEIGHT));
+
lastGroupSelected = null;
DefaultListModel model = new DefaultListModel();
- if (this.filterPageCombo.getSelectedItem() != null) {
- FilterPage indexPage = ((PageListWrapper) this.filterPageCombo.getSelectedItem()).getFilterPage();
+ for (FilterGroup group : page.getFilterGroups()) {
+ if (group.getHideDisplay() == null || !group.getHideDisplay().equals("true")) {
- for (FilterGroup g : indexPage.getFilterGroups()) {
- if (g.getHideDisplay() == null || !g.getHideDisplay().equals("true")) {
- model.addElement(new GroupListWrapper(g));
- }
- }
+ model.addElement(new GroupListWrapper(group));
- this.filterGroupList.setModel(model);
+ updateCollectionsCache(page,group);
+ }
}
+ this.filterGroupList.setModel(model);
+
}
/**
- * Initialisation of user collections panels shown
+ * Stores in a field (memory) all Panels (collectionsPanels, descriptionPanels, components,...)
+ * but do not show them on the screen
+ * @param page
+ * @param group
*/
- private void initCollectionsCache() {
+ private void updateCollectionsCache(FilterPage page,FilterGroup group){
- if (collectionsCache == null) collectionsCache = new HashMap<FilterPage, CollectionsPanelsCache>();
- else
- collectionsCache.clear();
+ FilterCollectionPanel collectionPanel = null;
- for (int i = 0; i< this.filterPageCombo.getModel().getSize(); i ++){
+ List<FilterCollectionPanel> listCollections = new ArrayList<FilterCollectionPanel>();
- FilterPage page = ((PageListWrapper) filterPageCombo.getModel().getElementAt(i)).getFilterPage();
-
- collectionsCache.put(page, null);
+ for (FilterCollection collection : group.getFilterCollections()) {
- CollectionsPanelsCache panels = new CollectionsPanelsCache();
+ collectionPanel = new FilterCollectionPanel(collection, this);
- for (int j = 0; j< this.filterGroupList.getModel().getSize();j++)
- panels.collections.put(((GroupListWrapper) filterGroupList.getModel().getElementAt(j)).
- getFilterGroup(), new ArrayList(0));
+ if (collectionPanel.isPanelRendered()) {
+ //add collectionPanel in list
+ listCollections.add(collectionPanel);
+
+ }
- collectionsCache.put(page, panels);
}
- }
- private void updateCollectionControls() {
+ //add collectionPanel list in cache
+ collectionsCache.get(page).collections.put(group, listCollections);
+
+ }
+ /**
+ * Shows in the screen all collections panels which belongs to the group selected
+ * @param page
+ * @param group
+ */
+ private void updateCollectionControls(FilterPage page,FilterGroup group) {
// Avoid update process when null value or unaltered filter group selection
- if (filterGroupList.getSelectedValue() == null ||
- (lastGroupSelected != null &&
- lastGroupSelected.getInternalName().equals(((GroupListWrapper) filterGroupList.getSelectedValue()).getFilterGroup().getInternalName()))
- )
- return;
+ if (filterGroupList.getSelectedValue() == null
+ || (lastGroupSelected != null
+ && lastGroupSelected.getInternalName().equals(group.getInternalName()))) {
- lastGroupSelected = ((GroupListWrapper) filterGroupList.getSelectedValue()).getFilterGroup();
+ return;
+ }
Integer collectionPanelHeight = 0;
- FilterCollectionPanel collectionPanel = null;
collectionsPanel.removeAll();
+
collectionsPanel.repaint();
+
collectionsPanel.setLayout(new BoxLayout(collectionsPanel, BoxLayout.Y_AXIS));
- //Check if collections have been showed previously (cache)
- if (collectionsCache.get(((PageListWrapper) filterPageCombo.getModel().getSelectedItem()).getFilterPage()).
- collections.get(lastGroupSelected).size()>0 )
- {
- for (FilterCollectionPanel col : collectionsCache.get(((PageListWrapper) filterPageCombo.getModel().getSelectedItem()).getFilterPage()).
- collections.get(lastGroupSelected))
- {
- collectionsPanel.add(col);
- collectionPanelHeight += col.getCurrentHeigh();
- }
- }
- else //first time collections are shown
- {
- List<FilterCollectionPanel> listCollections = new ArrayList<FilterCollectionPanel>();
- for (FilterCollection collection : lastGroupSelected.getFilterCollections()) {
+ //Check if collections have not been load previously (cache)
+ if (collectionsCache.get(page).collections.get(group).size() == 0)
+ updateCollectionsCache(page,group);
- collectionPanel = new FilterCollectionPanel(collection,this);
- if (collectionPanel.isPanelRendered())
- {
- collectionsPanel.add(collectionPanel);
- collectionPanelHeight += collectionPanel.getCurrentHeigh();
- //add collectionPanel in list
- listCollections.add(collectionPanel);
- }
+ for (FilterCollectionPanel col : collectionsCache.get(page).collections.get(group)) {
- }
- //add collectionPanel list in cache
- collectionsCache.get(((PageListWrapper) filterPageCombo.getModel().getSelectedItem()).
- getFilterPage()).collections.put(lastGroupSelected, listCollections);
+ collectionsPanel.add(col);
+
+ collectionPanelHeight += col.getCurrentHeigh();
}
+
+
+ Dimension d = new Dimension(collectionsPanel.getWidth(), collectionPanelHeight);
- Dimension d = new Dimension(collectionsPanel.getWidth(),collectionPanelHeight);
collectionsPanel.setPreferredSize(d);
collectionsPanel.repaint();
+
scrollPanel.validate();
validate();
}
+
+
/**
* Loop through all groups and their collections.
* If checkBox collection checked the filter is annotated
@@ -412,54 +501,136 @@ public Collection<Filter> getFilters() {
List<Filter> listFilters = new ArrayList<Filter>();
for (FilterPage page :collectionsCache.keySet())
+
for(FilterGroup group : collectionsCache.get(page).collections.keySet())
+
for (FilterCollectionPanel panel : collectionsCache.get(page).collections.get(group))
+
listFilters.addAll(panel.getFilters());
return listFilters;
}
+ /**
+ * Load global attributes and guess if reload data
+ * @param service
+ * @param dataset
+ */
+ public void setSource(BiomartRestfulService service, DatasetConfig config) {
+
+ if (this.biomartConfig != null && this.biomartConfig.getDataset().equals(config.getDataset()))
+
+ reloadData = false;
+
+ else
+ {
+ reloadData = true;
+
+ filterPageCombo.setModel(new DefaultComboBoxModel());
+
+ filterGroupList.setModel(new DefaultListModel());
+
+ collectionsPanel.removeAll();
+
+ collectionsPanel.repaint();
+
+ scrollPanel.validate();
+
+ validate();
+ }
+
+ this.biomartService = service;
+
+ this.biomartConfig = config;
+
+ }
+
+ /**
+ * Initialisation of the field which will contain all filter panels
+ */
+ private void initCollectionsCache() {
+
+ if (collectionsCache == null) collectionsCache = new HashMap<FilterPage, CollectionsPanelsCache>();
+
+ else collectionsCache.clear();
+
+ for (FilterPage page : biomartConfig.getFilterPages())
+ {
+
+ if (page.getHideDisplay() == null || !page.getHideDisplay().equals("true"))
+ {
+
+ collectionsCache.put(page, null);
+
+ CollectionsPanelsCache panels = new CollectionsPanelsCache();
+
+ for (FilterGroup group : page.getFilterGroups())
+
+ panels.collections.put(group, new ArrayList(0));
+
+ collectionsCache.put(page, panels);
+ }
+ }
+
+ }
+
public void setFilter(String name, Filter f) {
+
filters.put(name,f);
}
public void setFilters(HashMap<String,Filter> filters) {
+
filters.putAll(filters);
}
public void deleteFilter(String name) {
+
filters.remove(name);
}
public void deleteFilters(HashMap<String,Filter> delFilters) {
for (String name : delFilters.keySet())
- filters.remove(name);
-
- }
- public void setSource(BiomartRestfulService service, DatasetInfo dataset) {
- if (this.dataset != null && this.dataset.getName().equals(dataset.getName()))
- updateFilterData = false;
- else
- updateFilterData = true;
+ filters.remove(name);
- this.dataset = dataset;
- this.biomartService = service;
-
}
-
+
public BiomartRestfulService getBiomartService(){
+
return this.biomartService;
}
+ public DatasetConfig getDatasetConfig(){
+
+ return this.biomartConfig;
+ }
+
public HashMap<FilterPage, CollectionsPanelsCache> getCollectionsCache() {
+
return collectionsCache;
}
public void setCollectionsCache(HashMap<FilterPage, CollectionsPanelsCache> collectionsCache) {
+
this.collectionsCache = collectionsCache;
}
+
+ public HashMap<String, List<Option>> getDefaultSelecComposData() {
+ return defaultSelecComposData;
+ }
+
+
+ public void storeSelecComponentsDefaultData(HashMap<String, List<Option>> data) {
+
+ if (data.size()>0)
+ {
+ for (String key : data.keySet())
+ this.defaultSelecComposData.put(key, data.get(key));
+ }
+
+ }
/*
public void resetCollectionCache() {
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartModulesWizard.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartModulesWizard.java
index 71417b04..83c57c2d 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartModulesWizard.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartModulesWizard.java
@@ -7,6 +7,7 @@
import org.gitools.biomart.restful.model.Dataset;
import org.gitools.biomart.restful.model.Query;
import org.gitools.biomart.restful.BiomartRestfulService;
+import org.gitools.biomart.restful.model.DatasetConfig;
import org.gitools.biomart.restful.model.DatasetInfo;
import org.gitools.biomart.restful.model.Filter;
import org.gitools.biomart.restful.model.MartLocation;
@@ -31,6 +32,8 @@ public class BiomartModulesWizard extends AbstractWizard {
private BiomartRestfulService biomartService;
+ private DatasetConfig biomartConfig;
+
private BiomartFilterConfigurationPage filterListPage;
private BiomartSourcePage sourcePage;
@@ -99,7 +102,7 @@ public IWizardPage getNextPage(IWizardPage page) {
if (page == sourcePage) {
- biomartService = sourcePage.getService();
+ biomartService = sourcePage.getBiomartService();
Database = sourcePage.getDataBase();
Dataset = sourcePage.getDataset();
@@ -114,8 +117,11 @@ public IWizardPage getNextPage(IWizardPage page) {
modulesAttributePage.getAttributePages());
}
- else if (page == dataAttributePage)
- filterListPage.setSource(biomartService, Dataset);
+ else if (page == dataAttributePage){
+ //filterListPage.setSource(biomartService, Dataset);
+ biomartConfig = modulesAttributePage.getBiomartConfig();
+ filterListPage.setSource(biomartService,biomartConfig);
+ }
return super.getNextPage(page);
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartSourcePage.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartSourcePage.java
index 4fdf0955..21f228d0 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartSourcePage.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartSourcePage.java
@@ -109,7 +109,7 @@ public String toString() {
}
- private BiomartRestfulService service;
+ private BiomartRestfulService biomartService;
private boolean updated;
private FilteredListPanel datasetPanel;
@@ -320,8 +320,8 @@ public void updateDatabase() {
return;
try {
- service = null;
- service = BiomartServiceFactory.createRestfulService(bs);
+ biomartService = null;
+ biomartService = BiomartServiceFactory.createRestfulService(bs);
} catch (BiomartServiceException ex) {
ExceptionDialog dlg = new ExceptionDialog(AppFrame.instance(), ex);
dlg.setVisible(true);
@@ -330,13 +330,13 @@ public void updateDatabase() {
// TODO close the wizard or throw up the exception (RuntimeException)
}
- if (service == null)
+ if (biomartService == null)
return;
new Thread(new Runnable() {
@Override public void run() {
try {
- List<MartLocation> registry = service.getRegistry();
+ List<MartLocation> registry = biomartService.getRegistry();
DefaultListModel model = new DefaultListModel();
for (MartLocation mart : registry)
if (mart.getVisible() != 0)
@@ -379,7 +379,7 @@ private void updateDatasets() {
try {
lastMartSelected = getDataBase();
- List<DatasetInfo> datasets = service.getDatasets(lastMartSelected);
+ List<DatasetInfo> datasets = biomartService.getDatasets(lastMartSelected);
List<Object> model = new ArrayList();
@@ -427,7 +427,7 @@ public DatasetInfo getDataset() {
: null;
}
- public BiomartRestfulService getService() {
- return service;
+ public BiomartRestfulService getBiomartService() {
+ return biomartService;
}
}
diff --git a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartTableWizard.java b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartTableWizard.java
index 8330ac95..88fd8b5e 100644
--- a/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartTableWizard.java
+++ b/gitools-ui/src/main/java/org/gitools/ui/biomart/wizard/BiomartTableWizard.java
@@ -25,6 +25,7 @@
import org.gitools.biomart.restful.BiomartRestfulService;
import org.gitools.biomart.restful.model.AttributeDescription;
+import org.gitools.biomart.restful.model.DatasetConfig;
import org.gitools.biomart.restful.model.DatasetInfo;
import org.gitools.biomart.restful.model.Filter;
import org.gitools.biomart.restful.model.MartLocation;
@@ -43,6 +44,8 @@ public class BiomartTableWizard extends AbstractWizard {
private BiomartRestfulService biomartService;
+ private DatasetConfig biomartConfig;
+
private BiomartAttributeListPage attrListPage;
private BiomartTableFilteringPage filteringPage;
@@ -103,7 +106,7 @@ public IWizardPage getNextPage(IWizardPage page) {
IWizardPage nextPage = super.getNextPage(page);
if (nextPage == attrListPage) {
- biomartService = sourcePage.getService();
+ biomartService = sourcePage.getBiomartService();
Database = sourcePage.getDataBase();
Dataset = sourcePage.getDataset();
@@ -111,13 +114,10 @@ public IWizardPage getNextPage(IWizardPage page) {
biomartService,
Database,
Dataset);
- }
-
-
+ }
else if (nextPage == filterListPage) {
- filterListPage.setSource(
- biomartService,
- Dataset);
+ biomartConfig = attrListPage.getBiomartConfig();
+ filterListPage.setSource(biomartService,biomartConfig);
}
return nextPage;
|
c12028b5b932403ea2ce77a45ad699a013b8d488
|
hbase
|
HBASE-2057 Cluster won't stop--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@894111 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/src/java/org/apache/hadoop/hbase/master/ZKMasterAddressWatcher.java b/src/java/org/apache/hadoop/hbase/master/ZKMasterAddressWatcher.java
index 49f783dfc87b..fccf46d93896 100644
--- a/src/java/org/apache/hadoop/hbase/master/ZKMasterAddressWatcher.java
+++ b/src/java/org/apache/hadoop/hbase/master/ZKMasterAddressWatcher.java
@@ -110,6 +110,7 @@ boolean writeAddressToZooKeeper(
}
if(this.zookeeper.writeMasterAddress(address)) {
this.zookeeper.setClusterState(true);
+ this.zookeeper.setClusterStateWatch(this);
// Watch our own node
this.zookeeper.readMasterAddress(this);
return true;
|
35c5faa642a497729746e958d1c3d84e4234270c
|
belaban$jgroups
|
NIO Reads writes are completed in the caller thered;
100% compatible with old interface and functionality.
Each connection has an instance of this object to
receive data for a message in multiple OP_READ events.
|
p
|
https://github.com/belaban/jgroups
|
diff --git a/src/org/jgroups/blocks/ConnectionTable1_4.java b/src/org/jgroups/blocks/ConnectionTable1_4.java
index 3b01c9a727e..3a681a673a0 100644
--- a/src/org/jgroups/blocks/ConnectionTable1_4.java
+++ b/src/org/jgroups/blocks/ConnectionTable1_4.java
@@ -1,26 +1,17 @@
-// $Id: ConnectionTable1_4.java,v 1.1 2003/09/09 01:24:08 belaban Exp $
+// $Id: ConnectionTable1_4.java,v 1.2 2003/12/21 03:47:56 akbollu Exp $
package org.jgroups.blocks;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
-import java.net.BindException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.net.SocketException;
+import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.Vector;
+import java.util.*;
import org.jgroups.Address;
import org.jgroups.Message;
@@ -28,8 +19,9 @@
import org.jgroups.log.Trace;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.Util;
+import org.jgroups.util.Util1_4;
+
-/* ---------------------------- TODO WORK IN PROGRESS --------------------------------------------------*/
/**
* Manages incoming and outgoing TCP connections. For each outgoing message to destination P, if there
* is not yet a connection for P, one will be created. Subsequent outgoing messages will use this
@@ -40,334 +32,291 @@
* message listener.
* @author Bela Ban
*/
-public class ConnectionTable1_4 implements Runnable
-{
- Hashtable conns = new Hashtable();
- // keys: Addresses (peer address), values: Connection
- Receiver receiver = null;
- ServerSocketChannel srv_sock = null;
- InetAddress bind_addr = null;
- Address local_addr = null; // bind_addr + port of srv_sock
- int srv_port = 7800;
- Thread acceptor = null; // continuously calls srv_sock.accept()
- final int backlog = 20;
- // 20 conn requests are queued by ServerSocket (addtl will be discarded)
- Vector conn_listeners = new Vector();
- // listeners to be notified when a conn is established/torn down
- Object recv_mutex = new Object();
- // to serialize simultaneous access to receive() from multiple Connections
- Reaper reaper = null;
- // closes conns that have been idle for more than n secs
- long reaper_interval = 60000; // reap unused conns once a minute
- long conn_expire_time = 300000;
- // connections can be idle for 5 minutes before they are reaped
- boolean use_reaper = false; // by default we don't reap idle conns
- ThreadGroup thread_group = null;
- final byte[] cookie = { 'b', 'e', 'l', 'a' };
- private Selector connectSelector;
-
- /** Used for message reception */
- public interface Receiver
- {
- void receive(Message msg);
- }
-
- /** Used to be notified about connection establishment and teardown */
- public interface ConnectionListener
- {
- void connectionOpened(Address peer_addr);
- void connectionClosed(Address peer_addr);
- }
-
- private ConnectionTable1_4()
- { // cannot be used, other ctor has to be used
-
- }
-
- /**
- * Regular ConnectionTable without expiration of idle connections
- * @param srv_port The port on which the server will listen. If this port is reserved, the next
- * free port will be taken (incrementing srv_port).
- */
- public ConnectionTable1_4(int srv_port) throws Exception
- {
- this.srv_port = srv_port;
- start();
- }
-
- /**
- * ConnectionTable including a connection reaper. Connections that have been idle for more than conn_expire_time
- * milliseconds will be closed and removed from the connection table. On next access they will be re-created.
- * @param srv_port The port on which the server will listen
- * @param reaper_interval Number of milliseconds to wait for reaper between attepts to reap idle connections
- * @param conn_expire_time Number of milliseconds a connection can be idle (no traffic sent or received until
- * it will be reaped
- */
- public ConnectionTable1_4(
- int srv_port,
- long reaper_interval,
- long conn_expire_time)
- throws Exception
- {
- this.srv_port = srv_port;
- this.reaper_interval = reaper_interval;
- this.conn_expire_time = conn_expire_time;
- use_reaper = true;
- start();
- }
-
- /**
- * Create a ConnectionTable
- * @param r A reference to a receiver of all messages received by this class. Method <code>receive()</code>
- * will be called.
- * @param bind_addr The host name or IP address of the interface to which the server socket will bind.
- * This is interesting only in multi-homed systems. If bind_addr is null, the
- * server socket will bind to the first available interface (e.g. /dev/hme0 on
- * Solaris or /dev/eth0 on Linux systems).
- * @param srv_port The port to which the server socket will bind to. If this port is reserved, the next
- * free port will be taken (incrementing srv_port).
- */
- public ConnectionTable1_4(Receiver r, InetAddress bind_addr, int srv_port)
- throws Exception
- {
- setReceiver(r);
- this.bind_addr = bind_addr;
- this.srv_port = srv_port;
- start();
- }
-
- /**
- * ConnectionTable including a connection reaper. Connections that have been idle for more than conn_expire_time
- * milliseconds will be closed and removed from the connection table. On next access they will be re-created.
- *
- * @param srv_port The port on which the server will listen.If this port is reserved, the next
- * free port will be taken (incrementing srv_port).
- * @param bind_addr The host name or IP address of the interface to which the server socket will bind.
- * This is interesting only in multi-homed systems. If bind_addr is null, the
- * server socket will bind to the first available interface (e.g. /dev/hme0 on
- * Solaris or /dev/eth0 on Linux systems).
- * @param srv_port The port to which the server socket will bind to. If this port is reserved, the next
- * free port will be taken (incrementing srv_port).
- * @param reaper_interval Number of milliseconds to wait for reaper between attepts to reap idle connections
- * @param conn_expire_time Number of milliseconds a connection can be idle (no traffic sent or received until
- * it will be reaped
- */
- public ConnectionTable1_4(
- Receiver r,
- InetAddress bind_addr,
- int srv_port,
- long reaper_interval,
- long conn_expire_time)
- throws Exception
- {
- setReceiver(r);
- this.bind_addr = bind_addr;
- this.srv_port = srv_port;
- this.reaper_interval = reaper_interval;
- this.conn_expire_time = conn_expire_time;
- use_reaper = true;
- start();
- }
-
- public void setReceiver(Receiver r)
- {
- receiver = r;
- }
-
- public void addConnectionListener(ConnectionListener l)
- {
- if (l != null && !conn_listeners.contains(l))
- conn_listeners.addElement(l);
- }
-
- public void removeConnectionListener(ConnectionListener l)
- {
- if (l != null)
- conn_listeners.removeElement(l);
- }
-
- public Address getLocalAddress()
- {
- if (local_addr == null)
- local_addr =
- bind_addr != null ? new IpAddress(bind_addr, srv_port) : null;
- return local_addr;
- }
-
- /** Sends a message to a unicast destination. The destination has to be set */
- public void send(Message msg)
- {
- Address dest = msg != null ? msg.getDest() : null;
- Connection conn;
-
- if (dest == null)
- {
- Trace.error(
- "ConnectionTable.send()",
- "msg is null or message's destination is null");
- return;
- }
-
- // 1. Try to obtain correct Connection (or create one if not yet existent)
- try
- {
- conn = getConnection(dest);
- if (conn == null)
- return;
- }
- catch (Throwable ex)
- {
- Trace.info(
- "ConnectionTable.send()",
- "connection to " + dest + " could not be established: " + ex);
- return;
- }
-
- // 2. Send the message using that connection
- try
- {
- conn.send(msg);
- }
- catch (Throwable ex)
- {
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.send()",
- "sending message to "
- + dest
- + " failed (ex="
- + ex.getClass().getName()
- + "); removing from connection table");
- remove(dest);
- }
- }
-
- /** Try to obtain correct Connection (or create one if not yet existent) */
- Connection getConnection(Address dest) throws Exception
- {
- Connection conn = null;
- Socket sock;
-
- synchronized (conns)
- {
- conn = (Connection) conns.get(dest);
- if (conn == null)
- {
- sock =
- new Socket(
+public class ConnectionTable1_4 implements Runnable {
+ Hashtable conns=new Hashtable(); // keys: Addresses (peer address), values: Connection
+ Receiver receiver=null;
+ ServerSocketChannel srv_sock_ch=null;
+ ServerSocket srv_sock=null;
+ InetAddress bind_addr=null;
+ Address local_addr=null; // bind_addr + port of srv_sock
+ int srv_port=7800;
+ Thread acceptor=null; // continuously calls srv_sock.accept()
+ final int backlog=20; // 20 conn requests are queued by ServerSocket (addtl will be discarded)
+ Vector conn_listeners=new Vector(); // listeners to be notified when a conn is established/torn down
+ Object recv_mutex=new Object(); // to serialize simultaneous access to receive() from multiple Connections
+ Reaper reaper=null; // closes conns that have been idle for more than n secs
+ long reaper_interval=60000; // reap unused conns once a minute
+ long conn_expire_time=300000; // connections can be idle for 5 minutes before they are reaped
+ boolean use_reaper=false; // by default we don't reap idle conns
+ ThreadGroup thread_group=null;
+ final byte[] cookie={'b', 'e', 'l', 'a'};
+ private Selector selector = null;
+ private ArrayList pendingSocksList=null;
+ /** Used for message reception */
+ public interface Receiver {
+ void receive(Message msg);
+ }
+
+
+ /** Used to be notified about connection establishment and teardown */
+ public interface ConnectionListener {
+ void connectionOpened(Address peer_addr);
+ void connectionClosed(Address peer_addr);
+ }
+
+
+ private ConnectionTable1_4() { // cannot be used, other ctor has to be used
+
+ }
+
+ /**
+ * Regular ConnectionTable1_4 without expiration of idle connections
+ * @param srv_port The port on which the server will listen. If this port is reserved, the next
+ * free port will be taken (incrementing srv_port).
+ */
+ public ConnectionTable1_4(int srv_port) throws Exception {
+ this.srv_port=srv_port;
+ start();
+ }
+
+
+ /**
+ * ConnectionTable including a connection reaper. Connections that have been idle for more than conn_expire_time
+ * milliseconds will be closed and removed from the connection table. On next access they will be re-created.
+ * @param srv_port The port on which the server will listen
+ * @param reaper_interval Number of milliseconds to wait for reaper between attepts to reap idle connections
+ * @param conn_expire_time Number of milliseconds a connection can be idle (no traffic sent or received until
+ * it will be reaped
+ */
+ public ConnectionTable1_4(int srv_port, long reaper_interval, long conn_expire_time) throws Exception {
+ this.srv_port=srv_port;
+ this.reaper_interval=reaper_interval;
+ this.conn_expire_time=conn_expire_time;
+ use_reaper=true;
+ start();
+ }
+
+
+ /**
+ * Create a ConnectionTable
+ * @param r A reference to a receiver of all messages received by this class. Method <code>receive()</code>
+ * will be called.
+ * @param bind_addr The host name or IP address of the interface to which the server socket will bind.
+ * This is interesting only in multi-homed systems. If bind_addr is null, the
+ * server socket will bind to the first available interface (e.g. /dev/hme0 on
+ * Solaris or /dev/eth0 on Linux systems).
+ * @param srv_port The port to which the server socket will bind to. If this port is reserved, the next
+ * free port will be taken (incrementing srv_port).
+ */
+ public ConnectionTable1_4(Receiver r, InetAddress bind_addr, int srv_port) throws Exception {
+ setReceiver(r);
+ this.bind_addr=bind_addr;
+ this.srv_port=srv_port;
+ start();
+ }
+
+
+ /**
+ * ConnectionTable including a connection reaper. Connections that have been idle for more than conn_expire_time
+ * milliseconds will be closed and removed from the connection table. On next access they will be re-created.
+ *
+ * @param srv_port The port on which the server will listen.If this port is reserved, the next
+ * free port will be taken (incrementing srv_port).
+ * @param bind_addr The host name or IP address of the interface to which the server socket will bind.
+ * This is interesting only in multi-homed systems. If bind_addr is null, the
+ * server socket will bind to the first available interface (e.g. /dev/hme0 on
+ * Solaris or /dev/eth0 on Linux systems).
+ * @param srv_port The port to which the server socket will bind to. If this port is reserved, the next
+ * free port will be taken (incrementing srv_port).
+ * @param reaper_interval Number of milliseconds to wait for reaper between attepts to reap idle connections
+ * @param conn_expire_time Number of milliseconds a connection can be idle (no traffic sent or received until
+ * it will be reaped
+ */
+ public ConnectionTable1_4(Receiver r, InetAddress bind_addr, int srv_port,
+ long reaper_interval, long conn_expire_time) throws Exception {
+ setReceiver(r);
+ this.bind_addr=bind_addr;
+ this.srv_port=srv_port;
+ this.reaper_interval=reaper_interval;
+ this.conn_expire_time=conn_expire_time;
+ use_reaper=true;
+ start();
+ }
+
+
+ public void setReceiver(Receiver r) {
+ receiver=r;
+ }
+
+
+ public void addConnectionListener(ConnectionListener l) {
+ if(l != null && !conn_listeners.contains(l))
+ conn_listeners.addElement(l);
+ }
+
+
+ public void removeConnectionListener(ConnectionListener l) {
+ if(l != null) conn_listeners.removeElement(l);
+ }
+
+
+ public Address getLocalAddress() {
+ if(local_addr == null)
+ local_addr=bind_addr != null ? new IpAddress(bind_addr, srv_port) : null;
+ return local_addr;
+ }
+
+
+ /** Sends a message to a unicast destination. The destination has to be set */
+ public void send(Message msg) {
+ Address dest=msg != null ? msg.getDest() : null;
+ Connection conn;
+
+ if(dest == null) {
+ Trace.error("ConnectionTable1_4.send()", "msg is null or message's destination is null");
+ return;
+ }
+
+ // 1. Try to obtain correct Connection (or create one if not yet existent)
+ try {
+ conn=getConnection(dest);
+ if(conn == null) return;
+ }
+ catch(Throwable ex) {
+ Trace.info("ConnectionTable1_4.send()", "connection to " + dest + " could not be established: " + ex);
+ return;
+ }
+
+ // 2. Send the message using that connection
+ try {
+ conn.send(msg);
+ }
+ catch(Throwable ex) {
+ if(Trace.trace)
+ Trace.info("ConnectionTable1_4.send()", "sending message to " + dest + " failed (ex=" +
+ ex.getClass().getName() + "); removing from connection table");
+ remove(dest);
+ }
+ }
+
+
+ /** Try to obtain correct Connection (or create one if not yet existent) */
+ Connection getConnection(Address dest) throws Exception {
+ Connection conn=null;
+ SocketChannel sock_ch;
+
+ synchronized(conns) {
+ conn=(Connection)conns.get(dest);
+ if(conn == null) {
+ InetSocketAddress destAddress =
+ new InetSocketAddress(
((IpAddress) dest).getIpAddress(),
((IpAddress) dest).getPort());
- conn = new Connection(sock, dest);
- conn.sendLocalAddress(local_addr);
- notifyConnectionOpened(dest);
- // conns.put(dest, conn);
- addConnection(dest, conn);
- conn.init();
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.getConnection()",
- "created socket to " + dest);
- }
- return conn;
- }
- }
-
- public void start() throws Exception
- {
- srv_sock = createServerSocket(srv_port);
-
- if (bind_addr != null)
- local_addr =
- new IpAddress(bind_addr, srv_sock.socket().getLocalPort());
- else
- local_addr = new IpAddress(srv_sock.socket().getLocalPort());
-
- if (Trace.trace)
- {
- Trace.info(
- "ConnectionTable.start()",
- "server socket created " + "on " + local_addr);
- }
- acceptor = new Thread(this, "ConnectionTable.AcceptorThread");
- acceptor.setDaemon(true);
- acceptor.start();
-
- // start the connection reaper - will periodically remove unused connections
- if (use_reaper && reaper == null)
- {
- reaper = new Reaper();
- reaper.start();
- }
- }
-
- /** Closes all open sockets, the server socket and all threads waiting for incoming messages */
- public void stop()
- {
- Iterator it = null;
- Connection conn;
- ServerSocketChannel tmp;
-
- // 1. close the server socket (this also stops the acceptor thread)
- if (srv_sock != null)
- {
- try
- {
- tmp = srv_sock;
- srv_sock = null;
- tmp.close();
- }
- catch (Exception e)
- {
- }
- }
-
- // 2. then close the connections
- synchronized (conns)
- {
- it = conns.values().iterator();
- while (it.hasNext())
- {
- conn = (Connection) it.next();
- conn.destroy();
- }
- conns.clear();
- }
- local_addr = null;
- }
-
- /**
- Remove <code>addr</code>from connection table. This is typically triggered when a member is suspected.
- */
- public void remove(Address addr)
- {
- Connection conn;
-
- synchronized (conns)
- {
- conn = (Connection) conns.get(addr);
-
- if (conn != null)
- {
- try
- {
- conn.destroy(); // won't do anything if already destroyed
- }
- catch (Exception e)
- {
- }
- conns.remove(addr);
- }
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.remove()",
- "addr=" + addr + ", connections are " + toString());
- }
- }
-
- /**
- * Acceptor thread. Continuously accept new connections. Create a new thread for each new
- * connection and put it in conns. When the thread should stop, it is
- * interrupted by the thread creator.
+ sock_ch = SocketChannel.open(destAddress);
+ conn=new Connection(sock_ch, dest);
+ conn.sendLocalAddress(local_addr);
+ // conns.put(dest, conn);
+ addConnection(dest, conn);
+ pendingSocksList.add(conn);
+ selector.wakeup();
+ notifyConnectionOpened(dest);
+ if(Trace.trace) Trace.info("ConnectionTable1_4.getConnection()", "created socket to " + dest);
+ }
+ return conn;
+ }
+ }
+
+
+ public void start() throws Exception {
+ this.selector = Selector.open();
+ srv_sock=createServerSocket(srv_port);
+
+ if(bind_addr != null)
+ local_addr=new IpAddress(bind_addr, srv_sock.getLocalPort());
+ else
+ local_addr=new IpAddress(srv_sock.getLocalPort());
+
+ if(Trace.trace) {
+ Trace.info("ConnectionTable1_4.start()", "server socket created " +
+ "on " + local_addr);
+ }
+
+ //Roland Kurmann 4/7/2003, build new thread group
+ thread_group = new ThreadGroup(Thread.currentThread().getThreadGroup(), "ConnectionTableGroup");
+ //Roland Kurmann 4/7/2003, put in thread_group
+ acceptor=new Thread(thread_group, this, "ConnectionTable1_4.AcceptorThread");
+ acceptor.setDaemon(true);
+ acceptor.start();
+
+ // start the connection reaper - will periodically remove unused connections
+ if(use_reaper && reaper == null) {
+ reaper=new Reaper();
+ reaper.start();
+ }
+ pendingSocksList = new ArrayList();
+ }
+
+
+ /** Closes all open sockets, the server socket and all threads waiting for incoming messages */
+ public void stop() {
+ Iterator it=null;
+ Connection conn;
+ ServerSocket tmp;
+
+ // 1. close the server socket (this also stops the acceptor thread)
+ if(srv_sock != null) {
+ try {
+ tmp=srv_sock;
+ srv_sock=null;
+ tmp.close();
+ }
+ catch(Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ // 2. then close the connections
+ synchronized(conns) {
+ it=conns.values().iterator();
+ while(it.hasNext()) {
+ conn=(Connection)it.next();
+ conn.destroy();
+ }
+ conns.clear();
+ }
+ local_addr=null;
+ }
+
+
+ /**
+ Remove <code>addr</code>from connection table. This is typically triggered when a member is suspected.
+ */
+ public void remove(Address addr) {
+ Connection conn;
+
+ synchronized(conns) {
+ conn=(Connection)conns.get(addr);
+
+ if(conn != null) {
+ try {
+ conn.destroy(); // won't do anything if already destroyed
+ }
+ catch(Exception e) {
+ e.printStackTrace();
+ }
+ conns.remove(addr);
+ }
+ if(Trace.trace)
+ Trace.info("ConnectionTable1_4.remove()", "addr=" + addr + ", connections are " + toString());
+ }
+ }
+
+
+ /**
+ * Acceptor thread. Continuously accept new connections. Create a new
+ * thread for each new connection and put it in conns. When the thread
+ * should stop, it is interrupted by the thread creator.
*/
public void run()
{
@@ -375,63 +324,96 @@ public void run()
Connection conn = null;
Address peer_addr;
- while (srv_sock != null)
+ while (srv_sock_ch != null)
{
try
{
- connectSelector.select();
- Set readyKeys = connectSelector.selectedKeys();
-
- for (Iterator i = readyKeys.iterator(); i.hasNext();)
+ if (selector.select() > 0)
{
- SelectionKey key = (SelectionKey) i.next();
- i.remove();
-
- ServerSocketChannel readyChannel =
- (ServerSocketChannel) key.channel();
-
- SocketChannel incomingChannel = readyChannel.accept();
- incomingChannel.configureBlocking(false);
- client_sock = incomingChannel.socket();
-
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.run()",
- "accepted connection, client_sock=" + client_sock);
-
- // create new thread and add to conn table
- conn = new Connection(client_sock, null);
- // will call receive(msg)
- // get peer's address
- peer_addr = conn.readPeerAddress(client_sock);
-
- // client_addr=new IpAddress(client_sock.getInetAddress(), client_port);
- conn.setPeerAddress(peer_addr);
-
- synchronized (conns)
+ Set readyKeys = selector.selectedKeys();
+ for (Iterator i = readyKeys.iterator(); i.hasNext();)
{
- if (conns.contains(peer_addr))
+ SelectionKey key = (SelectionKey) i.next();
+ i.remove();
+ if ((key.readyOps() & SelectionKey.OP_ACCEPT)
+ == SelectionKey.OP_ACCEPT)
{
+ ServerSocketChannel readyChannel =
+ (ServerSocketChannel) key.channel();
+
+ SocketChannel client_sock_ch=
+ readyChannel.accept();
+ client_sock = client_sock_ch.socket();
if (Trace.trace)
- Trace.warn(
- "ConnectionTable.run()",
- peer_addr
- + " is already there, will terminate connection");
- conn.destroy();
- return;
+ Trace.info(
+ "ConnectionTable1_4.run()",
+ "accepted connection, client_sock="
+ + client_sock);
+
+ conn = new Connection(client_sock_ch, null);
+ // will call receive(msg)
+ // get peer's address
+ peer_addr = conn.readPeerAddress(client_sock);
+
+ conn.setPeerAddress(peer_addr);
+
+ synchronized (conns)
+ {
+ if (conns.contains(peer_addr))
+ {
+ if (Trace.trace)
+ Trace.warn(
+ "ConnectionTable1_4.run()",
+ peer_addr
+ + " is already there, will terminate connection");
+ conn.destroy();
+ return;
+ }
+ addConnection(peer_addr, conn);
+ }
+ conn.init();
+ notifyConnectionOpened(peer_addr);
+ }
+ else if (
+ (key.readyOps() & SelectionKey.OP_READ)
+ == SelectionKey.OP_READ)
+ {
+ SocketChannel incomingChannel =
+ (SocketChannel) key.channel();
+ conn = (Connection) key.attachment();
+ ByteBuffer buff = conn.getNIOMsgReader().readCompleteMsgBuffer();
+ if(buff != null)
+ {
+ receive((Message)Util.objectFromByteBuffer(buff.array()));
+ conn.getNIOMsgReader().reset();
+ }
}
- // conns.put(peer_addr, conn);
- addConnection(peer_addr, conn);
}
- notifyConnectionOpened(peer_addr);
- conn.init(); // starts handler thread on this socket
+ }
+ else
+ {
+ /*In addition to the accepted Sockets, we must registe
+ * sockets opend by this for OP_READ, because peer may
+ * use the same socket to sends data using the same socket,
+ * instead of opening a new connection. We can not register
+ * with this selectior from a different thread. set pending
+ * and wakeup this selector.
+ */
+ synchronized (conns)
+ {
+ Connection pendingConnection;
+ while( (pendingSocksList.size()>0) && (null != (pendingConnection = (Connection)pendingSocksList.remove(0))) )
+ {
+ pendingConnection.init();
+ }
+ }
}
}
catch (SocketException sock_ex)
{
if (Trace.trace)
Trace.info(
- "ConnectionTable.run()",
+ "ConnectionTable1_4.run()",
"exception is " + sock_ex);
if (conn != null)
conn.destroy();
@@ -441,637 +423,447 @@ public void run()
catch (Throwable ex)
{
if (Trace.trace)
- Trace.warn("ConnectionTable.run()", "exception is " + ex);
- }
- }
- }
-
- /**
- * Calls the receiver callback. We serialize access to this method because it may be called concurrently
- * by several Connection handler threads. Therefore the receiver doesn't need to synchronize.
- */
- public void receive(Message msg)
- {
- if (receiver != null)
- {
- synchronized (recv_mutex)
- {
- receiver.receive(msg);
- }
- }
- else
- Trace.error(
- "ConnectionTable.receive()",
- "receiver is null (not set) !");
- }
-
- public String toString()
- {
- StringBuffer ret = new StringBuffer();
- Address key;
- Connection val;
-
- synchronized (conns)
- {
- ret.append("connections (" + conns.size() + "):\n");
- for (Enumeration e = conns.keys(); e.hasMoreElements();)
- {
- key = (Address) e.nextElement();
- val = (Connection) conns.get(key);
- ret.append(
- "key: " + key.toString() + ": " + val.toString() + "\n");
- }
- }
- ret.append("\n");
- return ret.toString();
- }
-
- /** Finds first available port starting at start_port and returns server socket. Sets srv_port */
- ServerSocketChannel createServerSocket(int start_port) throws Exception
- {
- ServerSocketChannel ret = ServerSocketChannel.open();
- ret.configureBlocking(false);
-
- while (true)
- {
- try
- {
- if (bind_addr == null)
- ret.socket().bind(new InetSocketAddress(start_port));
- else
- ret.socket().bind(
- new InetSocketAddress(bind_addr, start_port),
- backlog);
- }
- catch (BindException bind_ex)
- {
- start_port++;
- continue;
- }
- catch (IOException io_ex)
- {
- Trace.error(
- "ConnectionTable.createServerSocket()",
- "exception is " + io_ex);
- }
- srv_port = start_port;
- break;
- }
- ret.register(this.connectSelector, SelectionKey.OP_ACCEPT);
- return ret;
- }
-
- void notifyConnectionOpened(Address peer)
- {
- if (peer == null)
- return;
- for (int i = 0; i < conn_listeners.size(); i++)
- (
- (ConnectionListener) conn_listeners.elementAt(
- i)).connectionOpened(
- peer);
- }
-
- void notifyConnectionClosed(Address peer)
- {
- if (peer == null)
- return;
- for (int i = 0; i < conn_listeners.size(); i++)
- (
- (ConnectionListener) conn_listeners.elementAt(
- i)).connectionClosed(
- peer);
- }
-
- void addConnection(Address peer, Connection c)
- {
- conns.put(peer, c);
- if (reaper != null && !reaper.isRunning())
- reaper.start();
- }
-
- /* ----Receiver thread gets OP_READ events and reads from the channel ---*/
- /**
- * need to have multiple receiver threads for every 63 of channels(sockets)
- */
-
- class ReceiverThread extends Thread
- {
- private Selector selector = null;
- private static final int READ_BUFFER_SIZE = 256;
- private ByteBuffer readBuffer = null;
- public ReceiverThread(Selector selector)
- {
- this.selector = selector;
- readBuffer = ByteBuffer.allocateDirect(READ_BUFFER_SIZE);
- }
-
- public void run()
- {
- Message msg;
- while (true)
- {
- try
- {
- int keysReady = selector.select();
-
- if (keysReady > 0)
- {
- Set readyKeys = selector.selectedKeys();
-
- for (Iterator i = readyKeys.iterator(); i.hasNext();)
- {
- SelectionKey key = (SelectionKey) i.next();
- i.remove();
- SocketChannel incomingChannel =
- (SocketChannel) key.channel();
- Socket incomingSocket = incomingChannel.socket();
- int bytesRead = incomingChannel.read(readBuffer);
- readBuffer.flip();
- byte[] recvBytes = readBuffer.array();
- msg =
- (Message) Util.objectFromByteBuffer(recvBytes);
- receive(msg);
- readBuffer.clear();
-
- }
- }
- }
- catch (Exception ex)
- {
- ex.printStackTrace();
- }
- }
- }
- }
-
- class Connection
- {
- Socket sock = null;
- // socket to/from peer (result of srv_sock.accept() or new Socket())
- DataOutputStream out = null; // for sending messages
- DataInputStream in = null; // for receiving messages
- Address peer_addr = null;
- // address of the 'other end' of the connection
- Object send_mutex = new Object(); // serialize sends
- long last_access = System.currentTimeMillis();
- // last time a message was sent or received
- // final byte[] cookie={(byte)'b', (byte)'e', (byte)'l', (byte)'a'};
-
- Connection(Socket s, Address peer_addr)
- {
- sock = s;
- this.peer_addr = peer_addr;
- try
- {
- out = new DataOutputStream(sock.getOutputStream());
- in = new DataInputStream(sock.getInputStream());
- }
- catch (Exception ex)
- {
- Trace.error(
- "ConnectionTable.Connection()",
- "exception is " + ex);
- }
- }
-
- void setPeerAddress(Address peer_addr)
- {
- this.peer_addr = peer_addr;
- }
-
- void updateLastAccessed()
- {
- //if(Trace.trace)
- ///Trace.info("ConnectionTable.Connection.updateLastAccessed()", "connections are " + conns);
- last_access = System.currentTimeMillis();
- }
-
- void init()
- {
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.Connection.init()",
- "connection was created to " + peer_addr);
- // TODO register channel with selector or creater should.
- }
-
- void destroy()
- {
- closeSocket(); // should terminate handler as well
- }
-
- void send(Message msg)
- {
- synchronized (send_mutex)
- {
- try
- {
- doSend(msg);
- updateLastAccessed();
- }
- catch (IOException io_ex)
- {
- if (Trace.trace)
- Trace.warn(
- "ConnectionTable.Connection.send()",
- "peer closed connection, "
- + "trying to re-establish connection and re-send msg.");
- try
- {
- doSend(msg);
- updateLastAccessed();
- }
- catch (IOException io_ex2)
- {
- if (Trace.trace)
- Trace.error(
- "ConnectionTable.Connection.send()",
- "2nd attempt to send data failed too");
- }
- catch (Exception ex2)
- {
- if (Trace.trace)
- Trace.error(
- "ConnectionTable.Connection.send()",
- "exception is " + ex2);
- }
- }
- catch (Exception ex)
- {
- if (Trace.trace)
- Trace.error(
- "ConnectionTable.Connection.send()",
- "exception is " + ex);
- }
- }
- }
-
- void doSend(Message msg) throws Exception
- {
- IpAddress dst_addr = (IpAddress) msg.getDest();
- byte[] buffie = null;
-
- if (dst_addr == null || dst_addr.getIpAddress() == null)
- {
- Trace.error(
- "ConnectionTable.Connection.doSend()",
- "the destination address is null; aborting send");
- return;
- }
-
- try
- {
- // set the source address if not yet set
- if (msg.getSrc() == null)
- msg.setSrc(local_addr);
-
- buffie = Util.objectToByteBuffer(msg);
- if (buffie.length <= 0)
- {
- Trace.error(
- "ConnectionTable.Connection.doSend()",
- "buffer.length is 0. Will not send message");
- return;
- }
-
- // we're using 'double-writes', sending the buffer to the destination twice. this would
- // ensure that, if the peer closed the connection while we were idle, we would get an exception.
- // this won't happen if we use a single write (see Stevens, ch. 5.13).
- if (out != null)
- {
- out.writeInt(buffie.length);
- // write the length of the data buffer first
- Util.doubleWrite(buffie, out);
- out.flush(); // may not be very efficient (but safe)
- }
- }
- catch (Exception ex)
- {
- if (Trace.trace)
- Trace.error(
- "ConnectionTable.Connection.doSend()",
- "to "
- + dst_addr
- + ", exception is "
- + ex
- + ", stack trace:\n"
- + Util.printStackTrace(ex));
- remove(dst_addr);
- throw ex;
- }
- }
-
- /**
- * Reads the peer's address. First a cookie has to be sent which has to match my own cookie, otherwise
- * the connection will be refused
- */
- Address readPeerAddress(Socket client_sock) throws Exception
- {
- Address peer_addr = null;
- byte[] version, buf, input_cookie = new byte[cookie.length];
- int len = 0,
- client_port = client_sock != null ? client_sock.getPort() : 0;
- InetAddress client_addr =
- client_sock != null ? client_sock.getInetAddress() : null;
-
- if (in != null)
- {
- initCookie(input_cookie);
-
- // read the cookie first
- in.read(input_cookie, 0, input_cookie.length);
- if (!matchCookie(input_cookie))
- throw new SocketException(
- "ConnectionTable.Connection.readPeerAddress(): cookie sent by "
- + peer_addr
- + " does not match own cookie; terminating connection");
- // then read the version
- version = new byte[Version.version_id.length];
- in.read(version, 0, version.length);
-
- if (Version.compareTo(version) == false)
- {
Trace.warn(
- "ConnectionTable.readPeerAddress()",
- "packet from "
- + client_addr
- + ":"
- + client_port
- + " has different version ("
- + Version.printVersionId(
- version,
- Version.version_id.length)
- + ") from ours ("
- + Version.printVersionId(Version.version_id)
- + "). This may cause problems");
- }
-
- // read the length of the address
- len = in.readInt();
-
- // finally read the address itself
- buf = new byte[len];
- in.readFully(buf, 0, len);
- peer_addr = (Address) Util.objectFromByteBuffer(buf);
- updateLastAccessed();
- }
- return peer_addr;
- }
-
- /**
- * Send the cookie first, then the our port number. If the cookie doesn't match the receiver's cookie,
- * the receiver will reject the connection and close it.
- */
- void sendLocalAddress(Address local_addr)
- {
- byte[] buf;
-
- if (local_addr == null)
- {
- Trace.warn(
- "ConnectionTable.Connection.sendLocalAddress()",
- "local_addr is null");
- return;
- }
- if (out != null)
- {
- try
- {
- buf = Util.objectToByteBuffer(local_addr);
-
- // write the cookie
- out.write(cookie, 0, cookie.length);
-
- // write the version
- out.write(Version.version_id, 0, Version.version_id.length);
-
- // write the length of the buffer
- out.writeInt(buf.length);
-
- // and finally write the buffer itself
- out.write(buf, 0, buf.length);
- out.flush(); // needed ?
- updateLastAccessed();
- }
- catch (Throwable t)
- {
- Trace.error(
- "ConnectionTable.Connection.sendLocalAddress()",
- "exception is " + t);
- }
- }
- }
-
- void initCookie(byte[] c)
- {
- if (c != null)
- for (int i = 0; i < c.length; i++)
- c[i] = 0;
- }
-
- boolean matchCookie(byte[] input)
- {
- if (input == null || input.length < cookie.length)
- return false;
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.Connection.matchCookie()",
- "input_cookie is " + printCookie(input));
- for (int i = 0; i < cookie.length; i++)
- if (cookie[i] != input[i])
- return false;
- return true;
- }
-
- String printCookie(byte[] c)
- {
- if (c == null)
- return "";
- return new String(c);
- }
-
- public String toString()
- {
- StringBuffer ret = new StringBuffer();
- InetAddress local = null, remote = null;
- String local_str, remote_str;
-
- if (sock == null)
- ret.append("<null socket>");
- else
- {
- //since the sock variable gets set to null we want to make
- //make sure we make it through here without a nullpointer exception
- Socket tmp_sock = sock;
- local = tmp_sock.getLocalAddress();
- remote = tmp_sock.getInetAddress();
- local_str =
- local != null
- ? Util.shortName(local.getHostName())
- : "<null>";
- remote_str =
- remote != null
- ? Util.shortName(local.getHostName())
- : "<null>";
- ret.append(
- "<"
- + local_str
- + ":"
- + tmp_sock.getLocalPort()
- + " --> "
- + remote_str
- + ":"
- + tmp_sock.getPort()
- + "> ("
- + ((System.currentTimeMillis() - last_access) / 1000)
- + " secs old)");
- tmp_sock = null;
- }
-
- return ret.toString();
- }
-
- void closeSocket()
- {
- if (sock != null)
- {
- try
- {
- sock.close();
- // should actually close in/out (so we don't need to close them explicitly)
- }
- catch (Exception e)
- {
- }
- sock = null;
- }
- if (out != null)
- {
- try
- {
- out.close(); // flushes data
- }
- catch (Exception e)
- {
- }
- // removed 4/22/2003 (request by Roland Kurmann)
- // out=null;
- }
- if (in != null)
- {
- try
- {
- in.close();
- }
- catch (Exception ex)
- {
- }
- in = null;
+ "ConnectionTable1_4.run()",
+ "exception is " + ex);
}
}
}
- class Reaper implements Runnable
- {
- Thread t = null;
- Reaper()
- {
- ;
- }
-
- public void start()
- {
- if (conns.size() == 0)
- return;
- if (t != null && !t.isAlive())
- t = null;
- if (t == null)
+ /**
+ * Calls the receiver callback. We serialize access to this method because it may be called concurrently
+ * by several Connection handler threads. Therefore the receiver doesn't need to synchronize.
+ */
+ public void receive(Message msg) {
+ if(receiver != null) {
+ synchronized(recv_mutex) {
+ receiver.receive(msg);
+ }
+ }
+ else
+ Trace.error("ConnectionTable1_4.receive()", "receiver is null (not set) !");
+ }
+
+
+ public String toString() {
+ StringBuffer ret=new StringBuffer();
+ Address key;
+ Connection val;
+
+ synchronized(conns) {
+ ret.append("connections (" + conns.size() + "):\n");
+ for(Enumeration e=conns.keys(); e.hasMoreElements();) {
+ key=(Address)e.nextElement();
+ val=(Connection)conns.get(key);
+ ret.append("key: " + key.toString() + ": " + val.toString() + "\n");
+ }
+ }
+ ret.append("\n");
+ return ret.toString();
+ }
+
+
+ /** Finds first available port starting at start_port and returns server socket. Sets srv_port */
+ ServerSocket createServerSocket(int start_port) throws Exception {
+ srv_sock_ch = ServerSocketChannel.open();
+ srv_sock_ch.configureBlocking(false);
+ while(true) {
+ try {
+ if(bind_addr == null)
+ srv_sock_ch.socket().bind(new InetSocketAddress(start_port));
+ else
+ srv_sock_ch.socket().bind(new InetSocketAddress( bind_addr,start_port), backlog);
+ }
+ catch(BindException bind_ex) {
+ start_port++;
+ continue;
+ }
+ catch(IOException io_ex) {
+ Trace.error("ConnectionTable1_4.createServerSocket()", "exception is " + io_ex);
+ }
+ srv_port=start_port;
+ break;
+ }
+ srv_sock_ch.register(this.selector, SelectionKey.OP_ACCEPT);
+ return srv_sock_ch.socket();
+ }
+
+
+ void notifyConnectionOpened(Address peer) {
+ if(peer == null) return;
+ for(int i=0; i < conn_listeners.size(); i++)
+ ((ConnectionListener)conn_listeners.elementAt(i)).connectionOpened(peer);
+ }
+
+ void notifyConnectionClosed(Address peer) {
+ if(peer == null) return;
+ for(int i=0; i < conn_listeners.size(); i++)
+ ((ConnectionListener)conn_listeners.elementAt(i)).connectionClosed(peer);
+ }
+
+
+ void addConnection(Address peer, Connection c) {
+ conns.put(peer, c);
+ if(reaper != null && !reaper.isRunning())
+ reaper.start();
+ }
+
+
+ class Connection {
+ Socket sock=null; // socket to/from peer (result of srv_sock.accept() or new Socket())
+ SocketChannel sock_ch = null;
+ DataOutputStream out=null; // for sending messages
+ DataInputStream in=null; // for receiving messages
+ Address peer_addr=null; // address of the 'other end' of the connection
+ Object send_mutex=new Object(); // serialize sends
+ long last_access=System.currentTimeMillis(); // last time a message was sent or received
+ private static final int HEADER_SIZE = 4;
+ private static final int DEFAULT_BUFF_SIZE = 256;
+ ByteBuffer headerBuffer = ByteBuffer.allocate(HEADER_SIZE);
+ NBMessageForm1_4 nioMsgReader = null;
+
+ Connection(SocketChannel s, Address peer_addr) {
+ sock_ch=s;
+ sock = sock_ch.socket();
+ this.peer_addr=peer_addr;
+ try {
+ out=new DataOutputStream(sock.getOutputStream());
+ in=new DataInputStream(sock.getInputStream());
+ }
+ catch(Exception ex) {
+ Trace.error("ConnectionTable1_4.Connection()", "exception is " + ex);
+ }
+ }
+
+ void setPeerAddress(Address peer_addr) {
+ this.peer_addr=peer_addr;
+ }
+
+ void updateLastAccessed() {
+ //if(Trace.trace)
+ ///Trace.info("ConnectionTable1_4.Connection.updateLastAccessed()", "connections are " + conns);
+ last_access=System.currentTimeMillis();
+ }
+
+ void init() {
+ try
+ {
+ in = null;
+ out = null;
+ }
+ catch(Exception ex)
+ {
+ ex.printStackTrace();
+ }
+
+ try
{
- //RKU 7.4.2003, put in threadgroup
- t =
- new Thread(
- thread_group,
- this,
- "ConnectionTable.ReaperThread");
- t.setDaemon(true);
- // will allow us to terminate if all remaining threads are daemons
- t.start();
+ sock_ch.configureBlocking(false);
+ nioMsgReader = new NBMessageForm1_4(DEFAULT_BUFF_SIZE,sock_ch);
+ sock_ch.register(selector, SelectionKey.OP_READ, this);
}
- }
-
- public void stop()
- {
- if (t != null)
- t = null;
- }
-
- public boolean isRunning()
- {
- return t != null;
- }
-
- public void run()
- {
- Connection value;
- Map.Entry entry;
- long curr_time;
-
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.Reaper.run()",
- "connection reaper thread was started. Number of connections="
- + conns.size()
- + ", reaper_interval="
- + reaper_interval
- + ", conn_expire_time="
- + conn_expire_time);
-
- while (conns.size() > 0 && t != null)
+ catch (IOException e)
{
- // first sleep
- Util.sleep(reaper_interval);
- synchronized (conns)
- {
- curr_time = System.currentTimeMillis();
- for (Iterator it = conns.entrySet().iterator();
- it.hasNext();
- )
- {
- entry = (Map.Entry) it.next();
- value = (Connection) entry.getValue();
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.Reaper.run()",
- "connection is "
- + ((curr_time - value.last_access) / 1000)
- + " seconds old (curr-time="
- + curr_time
- + ", last_access="
- + value.last_access
- + ")");
- if (value.last_access + conn_expire_time < curr_time)
- {
- if (Trace.trace)
- Trace.info(
- "ConnectionTable.Reaper.run()",
- "connection "
- + value
- + " has been idle for too long (conn_expire_time="
- + conn_expire_time
- + "), will be removed");
-
- value.destroy();
- it.remove();
- }
- }
- }
+ e.printStackTrace();
}
- if (Trace.trace)
- Trace.info("ConnectionTable.Reaper.run()", "reaper terminated");
- t = null;
- }
- }
-
-}
+ if(Trace.trace)
+ Trace.info("ConnectionTable1_4.Connection.init()", "connection was created to " + peer_addr);
+
+ }
+
+
+ void destroy() {
+ closeSocket();
+ nioMsgReader = null;
+ }
+
+ void send(Message msg) {
+ synchronized(send_mutex) {
+ try {
+ doSend(msg);
+ updateLastAccessed();
+ }
+ catch(IOException io_ex) {
+ if(Trace.trace)
+ Trace.warn("ConnectionTable1_4.Connection.send()", "peer closed connection, " +
+ "trying to re-establish connection and re-send msg.");
+ try {
+ doSend(msg);
+ updateLastAccessed();
+ }
+ catch(IOException io_ex2) {
+ if(Trace.trace) Trace.error("ConnectionTable1_4.Connection.send()", "2nd attempt to send data failed too");
+ io_ex2.printStackTrace();
+ }
+ catch(Exception ex2) {
+ if(Trace.trace) Trace.error("ConnectionTable1_4.Connection.send()", "exception is " + ex2);
+ ex2.printStackTrace();
+ }
+ }
+ catch(Exception ex) {
+ if(Trace.trace) Trace.error("ConnectionTable1_4.Connection.send()", "exception is " + ex);
+ ex.printStackTrace();
+ }
+ }
+ }
+
+
+ void doSend(Message msg) throws Exception {
+ IpAddress dst_addr=(IpAddress)msg.getDest();
+ byte[] buffie=null;
+
+ if(dst_addr == null || dst_addr.getIpAddress() == null) {
+ Trace.error("ConnectionTable1_4.Connection.doSend()", "the destination address is null; aborting send");
+ return;
+ }
+
+ try {
+ // set the source address if not yet set
+ if(msg.getSrc() == null)
+ msg.setSrc(local_addr);
+
+ buffie=Util.objectToByteBuffer(msg);
+ if(buffie.length <= 0) {
+ Trace.error("ConnectionTable1_4.Connection.doSend()", "buffer.length is 0. Will not send message");
+ return;
+ }
+
+
+ // we're using 'double-writes', sending the buffer to the destination twice. this would
+ // ensure that, if the peer closed the connection while we were idle, we would get an exception.
+ // this won't happen if we use a single write (see Stevens, ch. 5.13).
+ headerBuffer.clear();
+ headerBuffer.putInt(buffie.length);
+ headerBuffer.flip();
+ Util1_4.writeFully(headerBuffer,sock_ch);
+ ByteBuffer sendBuffer = ByteBuffer.wrap(buffie);
+ Util1_4.writeFully(sendBuffer, sock_ch);
+ }
+ catch(Exception ex) {
+ if(Trace.trace)
+ Trace.error("ConnectionTable1_4.Connection.doSend()",
+ "to " + dst_addr + ", exception is " + ex + ", stack trace:\n" +
+ Util.printStackTrace(ex));
+ ex.printStackTrace();
+ remove(dst_addr);
+ throw ex;
+ }
+ }
+
+
+ /**
+ * Reads the peer's address. First a cookie has to be sent which has to match my own cookie, otherwise
+ * the connection will be refused
+ */
+ Address readPeerAddress(Socket client_sock) throws Exception {
+ Address peer_addr=null;
+ byte[] version, buf, input_cookie=new byte[cookie.length];
+ int len=0, client_port=client_sock != null? client_sock.getPort() : 0;
+ InetAddress client_addr=client_sock != null? client_sock.getInetAddress() : null;
+
+ if(in != null) {
+ initCookie(input_cookie);
+
+ // read the cookie first
+ in.read(input_cookie, 0, input_cookie.length);
+ if(!matchCookie(input_cookie))
+ throw new SocketException("ConnectionTable1_4.Connection.readPeerAddress(): cookie sent by " +
+ peer_addr + " does not match own cookie; terminating connection");
+ // then read the version
+ version=new byte[Version.version_id.length];
+ in.read(version, 0, version.length);
+
+ if(Version.compareTo(version) == false) {
+ Trace.warn("ConnectionTable1_4.readPeerAddress()",
+ "packet from " + client_addr + ":" + client_port +
+ " has different version (" +
+ Version.printVersionId(version, Version.version_id.length) +
+ ") from ours (" + Version.printVersionId(Version.version_id) +
+ "). This may cause problems");
+ }
+
+ // read the length of the address
+ len=in.readInt();
+
+ // finally read the address itself
+ buf=new byte[len];
+ in.readFully(buf, 0, len);
+ peer_addr=(Address)Util.objectFromByteBuffer(buf);
+ updateLastAccessed();
+ }
+ return peer_addr;
+ }
+
+
+ /**
+ * Send the cookie first, then the our port number. If the cookie doesn't match the receiver's cookie,
+ * the receiver will reject the connection and close it.
+ */
+ void sendLocalAddress(Address local_addr) {
+ byte[] buf;
+
+ if(local_addr == null) {
+ Trace.warn("ConnectionTable1_4.Connection.sendLocalAddress()", "local_addr is null");
+ return;
+ }
+ if(out != null) {
+ try {
+ buf=Util.objectToByteBuffer(local_addr);
+
+ // write the cookie
+ out.write(cookie, 0, cookie.length);
+
+ // write the version
+ out.write(Version.version_id, 0, Version.version_id.length);
+
+ // write the length of the buffer
+ out.writeInt(buf.length);
+
+ // and finally write the buffer itself
+ out.write(buf, 0, buf.length);
+ out.flush(); // needed ?
+ updateLastAccessed();
+ }
+ catch(Throwable t) {
+ Trace.error("ConnectionTable1_4.Connection.sendLocalAddress()", "exception is " + t);
+ }
+ }
+ }
+
+
+ void initCookie(byte[] c) {
+ if(c != null)
+ for(int i=0; i < c.length; i++)
+ c[i]=0;
+ }
+
+ boolean matchCookie(byte[] input) {
+ if(input == null || input.length < cookie.length) return false;
+ if(Trace.trace)
+ Trace.info("ConnectionTable1_4.Connection.matchCookie()", "input_cookie is " + printCookie(input));
+ for(int i=0; i < cookie.length; i++)
+ if(cookie[i] != input[i]) return false;
+ return true;
+ }
+
+
+ String printCookie(byte[] c) {
+ if(c == null) return "";
+ return new String(c);
+ }
+
+ public String toString() {
+ StringBuffer ret=new StringBuffer();
+ InetAddress local=null, remote=null;
+ String local_str, remote_str;
+
+ if(sock == null)
+ ret.append("<null socket>");
+ else {
+ //since the sock variable gets set to null we want to make
+ //make sure we make it through here without a nullpointer exception
+ Socket tmp_sock=sock;
+ local=tmp_sock.getLocalAddress();
+ remote=tmp_sock.getInetAddress();
+ local_str=local != null ? Util.shortName(local.getHostName()) : "<null>";
+ remote_str=remote != null ? Util.shortName(local.getHostName()) : "<null>";
+ ret.append("<" + local_str + ":" + tmp_sock.getLocalPort() +
+ " --> " + remote_str + ":" + tmp_sock.getPort() + "> (" +
+ ((System.currentTimeMillis() - last_access) / 1000) + " secs old)");
+ tmp_sock=null;
+ }
+
+ return ret.toString();
+ }
+
+
+ void closeSocket() {
+ if(sock != null) {
+ try {
+ sock_ch.close();
+ }
+ catch(Exception e) {
+ e.printStackTrace();
+ }
+ sock=null;
+ }
+ }
+
+ NBMessageForm1_4 getNIOMsgReader()
+ {
+ return nioMsgReader;
+ }
+ }
+
+
+ class Reaper implements Runnable {
+ Thread t=null;
+
+ Reaper() {
+ ;
+ }
+
+ public void start() {
+ if(conns.size() == 0)
+ return;
+ if(t != null && !t.isAlive())
+ t=null;
+ if(t == null) {
+ //RKU 7.4.2003, put in threadgroup
+ t=new Thread(thread_group, this, "ConnectionTable1_4.ReaperThread");
+ t.setDaemon(true); // will allow us to terminate if all remaining threads are daemons
+ t.start();
+ }
+ }
+
+ public void stop() {
+ if(t != null)
+ t=null;
+ }
+
+
+ public boolean isRunning() {
+ return t != null;
+ }
+
+ public void run() {
+ Connection value;
+ Map.Entry entry;
+ long curr_time;
+
+ if(Trace.trace)
+ Trace.info("ConnectionTable1_4.Reaper.run()", "connection reaper thread was started. Number of connections=" +
+ conns.size() + ", reaper_interval=" + reaper_interval + ", conn_expire_time=" +
+ conn_expire_time);
+
+ while(conns.size() > 0 && t != null) {
+ // first sleep
+ Util.sleep(reaper_interval);
+ synchronized(conns) {
+ curr_time=System.currentTimeMillis();
+ for(Iterator it=conns.entrySet().iterator(); it.hasNext();) {
+ entry=(Map.Entry)it.next();
+ value=(Connection)entry.getValue();
+ if(Trace.trace)
+ Trace.info("ConnectionTable1_4.Reaper.run()", "connection is " +
+ ((curr_time - value.last_access) / 1000) + " seconds old (curr-time=" +
+ curr_time + ", last_access=" + value.last_access + ")");
+ if(value.last_access + conn_expire_time < curr_time) {
+ if(Trace.trace)
+ Trace.info("ConnectionTable1_4.Reaper.run()", "connection " + value +
+ " has been idle for too long (conn_expire_time=" + conn_expire_time +
+ "), will be removed");
+
+ value.destroy();
+ it.remove();
+ }
+ }
+ }
+ }
+ if(Trace.trace)
+ Trace.info("ConnectionTable1_4.Reaper.run()", "reaper terminated");
+ t=null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/org/jgroups/blocks/NBMessageForm1_4.java b/src/org/jgroups/blocks/NBMessageForm1_4.java
new file mode 100644
index 00000000000..73559358a4c
--- /dev/null
+++ b/src/org/jgroups/blocks/NBMessageForm1_4.java
@@ -0,0 +1,76 @@
+// $Id: NBMessageForm1_4.java,v 1.1 2003/12/21 03:47:56 akbollu Exp $
+
+package org.jgroups.blocks;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
+
+/**
+ * NBMessageForm - Message form for non-blocking message reads.
+ * @author akbollu
+ */
+public class NBMessageForm1_4
+{
+ ByteBuffer headerBuffer = null;
+ ByteBuffer dataBuffer = null;
+ static final int HEADER_SIZE = 4;
+ boolean isComplete = false;
+ int messageSize = 0;
+ boolean w_in_p = false;
+ SocketChannel channel = null;
+
+ public NBMessageForm1_4(int dataBuffSize, SocketChannel ch)
+ {
+ headerBuffer = ByteBuffer.allocate(HEADER_SIZE);
+ dataBuffer = ByteBuffer.allocate(dataBuffSize);
+ channel = ch;
+ }
+
+ public ByteBuffer readCompleteMsgBuffer() throws IOException
+ {
+ if (!w_in_p)
+ {
+ int rt = channel.read(headerBuffer);
+ if ( (rt == 0) || (rt == -1) )
+ {
+ channel.close();
+ return null;
+ }
+ if (rt == HEADER_SIZE)
+ {
+ headerBuffer.flip();
+ messageSize = headerBuffer.getInt();
+ if(dataBuffer.capacity() < messageSize)
+ {
+ dataBuffer = ByteBuffer.allocate(messageSize);
+ }
+ w_in_p = true;
+ }
+ }
+ else
+ {
+ //rt == 0 need not be checked twice in the same event
+ channel.read(dataBuffer);
+ if(isComplete())
+ {
+ dataBuffer.flip();
+ return dataBuffer;
+ }
+ }
+ return null;
+ }
+
+ public void reset()
+ {
+ dataBuffer.clear();
+ headerBuffer.clear();
+ messageSize = 0;
+ w_in_p = false;
+ }
+
+ private boolean isComplete()
+ {
+ return ( dataBuffer.position() == messageSize );
+ }
+}
|
72385b4f18bd2646ee7aa3b627a40f1326eb9c1f
|
isa-tools$isacreator
|
Added remote folder field in the AppManager, added functionality to save to same remote folder, fixed method to get file metadata in GSDataManager
|
p
|
https://github.com/isa-tools/isacreator
|
diff --git a/src/main/java/org/isatools/isacreator/gs/GSDataManager.java b/src/main/java/org/isatools/isacreator/gs/GSDataManager.java
index c844b3a5..7ae6f124 100644
--- a/src/main/java/org/isatools/isacreator/gs/GSDataManager.java
+++ b/src/main/java/org/isatools/isacreator/gs/GSDataManager.java
@@ -101,9 +101,14 @@ public void lsHome(String username){
}
- public GSFileMetadata getFileMetadata(String filePath){
+ public GSFileMetadata getFileMetadata(String url){
+ //System.out.println("at getFileMetadata -> url="+url);
+ //System.out.println("is logged in?="+gsSession.isLoggedIn());
+ String filePath = transformURLtoFilePath(url) ;
+ //System.out.println("filePath="+filePath);
DataManagerClient dmClient = gsSession.getDataManagerClient();
GSFileMetadata fileMetadata = dmClient.getMetadata(filePath);
+ //System.out.println("fileMetadata="+fileMetadata);
return fileMetadata;
}
diff --git a/src/main/java/org/isatools/isacreator/gs/GSLocalFilesManager.java b/src/main/java/org/isatools/isacreator/gs/GSLocalFilesManager.java
index 948a47a1..829da015 100644
--- a/src/main/java/org/isatools/isacreator/gs/GSLocalFilesManager.java
+++ b/src/main/java/org/isatools/isacreator/gs/GSLocalFilesManager.java
@@ -44,6 +44,7 @@ public static List<ErrorMessage> downloadFiles(Authentication gsAuthentication)
if (!errors.isEmpty()){
return errors;
}
+ ApplicationManager.setCurrentRemoteISATABFolder(ISAcreatorCLArgs.isatabDir());
}//isatabDir not null
@@ -56,7 +57,8 @@ public static List<ErrorMessage> downloadFiles(Authentication gsAuthentication)
}//if
ISAcreatorCLArgs.isatabDir(localTmpDirectory);
- ApplicationManager.setCurrentISATABFolder(localTmpDirectory);
+ ApplicationManager.setCurrentLocalISATABFolder(localTmpDirectory);
+
}// if
return errors;
diff --git a/src/main/java/org/isatools/isacreator/gs/GSSaveAction.java b/src/main/java/org/isatools/isacreator/gs/GSSaveAction.java
index f1c56602..dda5caf2 100644
--- a/src/main/java/org/isatools/isacreator/gs/GSSaveAction.java
+++ b/src/main/java/org/isatools/isacreator/gs/GSSaveAction.java
@@ -70,8 +70,12 @@ public void actionPerformed(ActionEvent actionEvent) {
File folder = new File(localISATABFolder);
File[] files = folder.listFiles();
+
+ String folderPath = ApplicationManager.getCurrentRemoteISAtabFolder();
+ GSFileMetadata folderMetadata = gsDataManager.getFileMetadata(folderPath);
+
for(File file: files){
- // gsDataManager.saveFile(file, fileMetadata);
+ gsDataManager.saveFile(file, folderMetadata);
}
diff --git a/src/main/java/org/isatools/isacreator/gs/gui/GSImportFilesMenu.java b/src/main/java/org/isatools/isacreator/gs/gui/GSImportFilesMenu.java
index 8f57feda..4fc867e0 100644
--- a/src/main/java/org/isatools/isacreator/gs/gui/GSImportFilesMenu.java
+++ b/src/main/java/org/isatools/isacreator/gs/gui/GSImportFilesMenu.java
@@ -329,7 +329,7 @@ public void propertyChange(PropertyChangeEvent event) {
gsDataManager.downloadAllFilesFromDirectory(fileMetadata.getPath(),localTmpDirectory, pattern);
System.out.println("Importing file...");
- ApplicationManager.setCurrentISATABFolder(localTmpDirectory);
+ ApplicationManager.setCurrentLocalISATABFolder(localTmpDirectory);
loadFile(localTmpDirectory);
diff --git a/src/main/java/org/isatools/isacreator/managers/ApplicationManager.java b/src/main/java/org/isatools/isacreator/managers/ApplicationManager.java
index ac42cd6f..3b5ce296 100644
--- a/src/main/java/org/isatools/isacreator/managers/ApplicationManager.java
+++ b/src/main/java/org/isatools/isacreator/managers/ApplicationManager.java
@@ -32,15 +32,24 @@ public class ApplicationManager {
private static String currentlySelectedFieldName;
private static String currentLocalISAtabFolder;
+ private static String currentRemoteISAtabFolder;
public static String getCurrentLocalISAtabFolder(){
return currentLocalISAtabFolder;
}
- public static void setCurrentISATABFolder(String folder){
+ public static void setCurrentLocalISATABFolder(String folder){
currentLocalISAtabFolder = folder;
}
+ public static String getCurrentRemoteISAtabFolder(){
+ return currentRemoteISAtabFolder;
+ }
+
+ public static void setCurrentRemoteISATABFolder(String folder){
+ currentRemoteISAtabFolder = folder;
+ }
+
public static void setCurrentApplicationInstance(ISAcreator isacreatorEnvironment) {
ApplicationManager.currentApplicationInstance = isacreatorEnvironment;
|
02668af08bebc5266b321ab1df2f45dfe656c813
|
duracloud$duracloud
|
First part of https://jira.duraspace.org/browse/DURACLOUD-525: Creates the DuraBoss application by breaking out DuraReport into the webapp (which is now DuraBoss) and a new Reporter project. There are no functionality changes in this commit, just re-naming and re-organization. Note that your init.properties will need to change, "durareport" should be replaced with "duraboss".
git-svn-id: https://svn.duraspace.org/duracloud/trunk@833 1005ed41-97cd-4a8f-848c-be5b5fe45bcb
|
p
|
https://github.com/duracloud/duracloud
|
diff --git a/app-config/src/main/java/org/duracloud/appconfig/ApplicationInitializer.java b/app-config/src/main/java/org/duracloud/appconfig/ApplicationInitializer.java
index 695a706e6..69ccf19d6 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/ApplicationInitializer.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/ApplicationInitializer.java
@@ -11,7 +11,7 @@
import org.duracloud.appconfig.domain.Application;
import org.duracloud.appconfig.domain.BaseConfig;
import org.duracloud.appconfig.domain.DuradminConfig;
-import org.duracloud.appconfig.domain.DurareportConfig;
+import org.duracloud.appconfig.domain.DurabossConfig;
import org.duracloud.appconfig.domain.DuraserviceConfig;
import org.duracloud.appconfig.domain.DurastoreConfig;
import org.duracloud.appconfig.domain.SecurityConfig;
@@ -46,7 +46,7 @@ public class ApplicationInitializer extends BaseConfig {
private static final String duradminKey = "duradmin";
private static final String duraserviceKey = "duraservice";
private static final String durastoreKey = "durastore";
- private static final String durareportKey = "durareport";
+ private static final String durabossKey = "duraboss";
protected static final String hostKey = "host";
protected static final String portKey = "port";
@@ -62,9 +62,9 @@ public class ApplicationInitializer extends BaseConfig {
private String durastoreHost;
private String durastorePort;
private String durastoreContext;
- private String durareportHost;
- private String durareportPort;
- private String durareportContext;
+ private String durabossHost;
+ private String durabossPort;
+ private String durabossContext;
private SecurityConfig securityConfig = new SecurityConfig();
private Map<String, ApplicationWithConfig> appsWithConfigs =
@@ -88,7 +88,7 @@ public ApplicationInitializer(File propsFile) throws IOException {
/**
* This method sets the configuration of duradmin, durastore, duraservice,
- * durareport, and application security from the provided props.
+ * duraboss, and application security from the provided props.
* Note: this method is called by the constructor, so generally is should
* not be needed publicly.
*
@@ -145,17 +145,17 @@ private void createApplications() {
log.warn("durastore endpoint !loaded");
}
- if (durareportEndpointLoad()) {
- app = new Application(durareportHost,
- durareportPort,
- durareportContext);
+ if (durabossEndpointLoad()) {
+ app = new Application(durabossHost,
+ durabossPort,
+ durabossContext);
- appWithConfig = new ApplicationWithConfig(durareportKey);
+ appWithConfig = new ApplicationWithConfig(durabossKey);
appWithConfig.setApplication(app);
- appWithConfig.setConfig(new DurareportConfig());
+ appWithConfig.setConfig(new DurabossConfig());
appsWithConfigs.put(appWithConfig.getName(), appWithConfig);
} else {
- log.warn("durareport endpoint not !loaded");
+ log.warn("duraboss endpoint not !loaded");
}
}
@@ -174,9 +174,9 @@ private boolean durastoreEndpointLoad() {
null != durastoreContext;
}
- private boolean durareportEndpointLoad() {
- return null != durareportHost && null != durareportPort &&
- null != durareportContext;
+ private boolean durabossEndpointLoad() {
+ return null != durabossHost && null != durabossPort &&
+ null != durabossContext;
}
protected String getQualifier() {
@@ -196,14 +196,14 @@ protected void loadProperty(String key, String value) {
} else if (prefix.equalsIgnoreCase(DuraserviceConfig.QUALIFIER)) {
loadDuraservice(suffix, value);
- } else if (prefix.equalsIgnoreCase(DurareportConfig.QUALIFIER)) {
- loadDurareport(suffix, value);
+ } else if (prefix.equalsIgnoreCase(DurabossConfig.QUALIFIER)) {
+ loadDuraboss(suffix, value);
} else if (prefix.equalsIgnoreCase(wildcardKey)) {
loadDuradmin(suffix, value);
loadDurastore(suffix, value);
loadDuraservice(suffix, value);
- loadDurareport(suffix, value);
+ loadDuraboss(suffix, value);
} else {
String msg = "unknown key: " + key + " (" + value + ")";
@@ -266,16 +266,16 @@ private void loadDuraservice(String key, String value) {
}
}
- private void loadDurareport(String key, String value) {
+ private void loadDuraboss(String key, String value) {
String prefix = getPrefix(key);
if (prefix.equalsIgnoreCase(hostKey)) {
- this.durareportHost = value;
+ this.durabossHost = value;
} else if (prefix.equalsIgnoreCase(portKey)) {
- this.durareportPort = value;
+ this.durabossPort = value;
} else if (prefix.equalsIgnoreCase(contextKey)) {
- this.durareportContext = value;
+ this.durabossContext = value;
} else {
String msg = "unknown key: " + key + " (" + value + ")";
@@ -296,8 +296,8 @@ public RestHttpHelper.HttpResponse initialize() {
response = initApp(appsWithConfigs.get(durastoreKey));
response = initApp(appsWithConfigs.get(duraserviceKey));
response = initApp(appsWithConfigs.get(duradminKey));
- if (durareportEndpointLoad()) {
- response = initApp(appsWithConfigs.get(durareportKey));
+ if (durabossEndpointLoad()) {
+ response = initApp(appsWithConfigs.get(durabossKey));
}
return response;
@@ -389,7 +389,7 @@ public Application getDuraservice() {
return appsWithConfigs.get(duraserviceKey).getApplication();
}
- public Application getDurareport() {
- return appsWithConfigs.get(durareportKey).getApplication();
+ public Application getDuraboss() {
+ return appsWithConfigs.get(durabossKey).getApplication();
}
}
diff --git a/app-config/src/main/java/org/duracloud/appconfig/domain/BaseConfig.java b/app-config/src/main/java/org/duracloud/appconfig/domain/BaseConfig.java
index 3e5c77730..58016abf5 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/domain/BaseConfig.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/domain/BaseConfig.java
@@ -16,7 +16,7 @@
/**
* This class collects the common functionality needed by durastore,
- * duraservice, duradmin, durareport, and security configurations.
+ * duraservice, duradmin, duraboss, and security configurations.
*
* @author Andrew Woods
* Date: Apr 20, 2010
diff --git a/app-config/src/main/java/org/duracloud/appconfig/domain/DurareportConfig.java b/app-config/src/main/java/org/duracloud/appconfig/domain/DurabossConfig.java
similarity index 92%
rename from app-config/src/main/java/org/duracloud/appconfig/domain/DurareportConfig.java
rename to app-config/src/main/java/org/duracloud/appconfig/domain/DurabossConfig.java
index 8d952f946..9675d65e1 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/domain/DurareportConfig.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/domain/DurabossConfig.java
@@ -7,7 +7,7 @@
*/
package org.duracloud.appconfig.domain;
-import org.duracloud.appconfig.xml.DurareportInitDocumentBinding;
+import org.duracloud.appconfig.xml.DurabossInitDocumentBinding;
import java.util.Collection;
import java.util.HashMap;
@@ -17,9 +17,9 @@
* @author: Bill Branan
* Date: 5/12/11
*/
-public class DurareportConfig extends DuradminConfig {
+public class DurabossConfig extends DuradminConfig {
- public static final String QUALIFIER = "durareport";
+ public static final String QUALIFIER = "duraboss";
public static final String notificationKey = "notification";
public static final String notificationTypeKey = "type";
public static final String notificationUsernameKey = "username";
@@ -82,7 +82,7 @@ protected boolean isSupported(String key) {
@Override
public String asXml() {
- return DurareportInitDocumentBinding.createDocumentFrom(this);
+ return DurabossInitDocumentBinding.createDocumentFrom(this);
}
/**
diff --git a/app-config/src/main/java/org/duracloud/appconfig/domain/DuradminConfig.java b/app-config/src/main/java/org/duracloud/appconfig/domain/DuradminConfig.java
index 7124e760b..f49a1901b 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/domain/DuradminConfig.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/domain/DuradminConfig.java
@@ -28,7 +28,7 @@ public class DuradminConfig extends BaseConfig implements AppConfig {
public static final String duraServiceHostKey = "duraservice-host";
public static final String duraServicePortKey = "duraservice-port";
public static final String duraServiceContextKey = "duraservice-context";
- public static final String duraReportContextKey = "durareport-context";
+ public static final String duraBossContextKey = "duraboss-context";
public static final String amaUrlKey = "ama-url";
@@ -38,7 +38,7 @@ public class DuradminConfig extends BaseConfig implements AppConfig {
private String duraserviceHost;
private String duraservicePort;
private String duraserviceContext;
- private String durareportContext;
+ private String durabossContext;
private String amaUrl;
@@ -74,8 +74,8 @@ protected void loadProperty(String key, String value) {
} else if (key.equalsIgnoreCase(duraServiceContextKey)) {
this.duraserviceContext = value;
- } else if (key.equalsIgnoreCase(duraReportContextKey)) {
- this.durareportContext = value;
+ } else if (key.equalsIgnoreCase(duraBossContextKey)) {
+ this.durabossContext = value;
} else if (key.equalsIgnoreCase(amaUrlKey)) {
this.amaUrl = value;
@@ -149,11 +149,11 @@ public void setAmaUrl(String amaUrl) {
this.amaUrl = amaUrl;
}
- public String getDurareportContext() {
- return durareportContext;
+ public String getDurabossContext() {
+ return durabossContext;
}
- public void setDurareportContext(String durareportContext) {
- this.durareportContext = durareportContext;
+ public void setDurabossContext(String durabossContext) {
+ this.durabossContext = durabossContext;
}
}
diff --git a/app-config/src/main/java/org/duracloud/appconfig/xml/DurareportInitDocumentBinding.java b/app-config/src/main/java/org/duracloud/appconfig/xml/DurabossInitDocumentBinding.java
similarity index 80%
rename from app-config/src/main/java/org/duracloud/appconfig/xml/DurareportInitDocumentBinding.java
rename to app-config/src/main/java/org/duracloud/appconfig/xml/DurabossInitDocumentBinding.java
index 39c053910..24a1af67a 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/xml/DurareportInitDocumentBinding.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/xml/DurabossInitDocumentBinding.java
@@ -7,7 +7,7 @@
*/
package org.duracloud.appconfig.xml;
-import org.duracloud.appconfig.domain.DurareportConfig;
+import org.duracloud.appconfig.domain.DurabossConfig;
import org.duracloud.appconfig.domain.NotificationConfig;
import org.duracloud.common.error.DuraCloudRuntimeException;
import org.duracloud.common.util.EncryptionUtil;
@@ -27,10 +27,10 @@
* @author: Bill Branan
* Date: 5/12/11
*/
-public class DurareportInitDocumentBinding {
+public class DurabossInitDocumentBinding {
private static final Logger log = LoggerFactory
- .getLogger(DurareportInitDocumentBinding.class);
+ .getLogger(DurabossInitDocumentBinding.class);
private static EncryptionUtil encryptionUtil;
@@ -44,13 +44,13 @@ public class DurareportInitDocumentBinding {
/**
- * This method deserializes the provided xml into a durareport config object.
+ * This method deserializes the provided xml into a duraboss config object.
*
* @param xml
* @return
*/
- public static DurareportConfig createDurareportConfigFrom(InputStream xml) {
- DurareportConfig config = new DurareportConfig();
+ public static DurabossConfig createDurabossConfigFrom(InputStream xml) {
+ DurabossConfig config = new DurabossConfig();
try {
SAXBuilder builder = new SAXBuilder();
@@ -84,7 +84,7 @@ public static DurareportConfig createDurareportConfigFrom(InputStream xml) {
}
} catch (Exception e) {
String error = "Error encountered attempting to parse " +
- "Durareport configuration xml: " + e.getMessage();
+ "Duraboss configuration xml: " + e.getMessage();
log.error(error);
throw new DuraCloudRuntimeException(error, e);
}
@@ -93,23 +93,23 @@ public static DurareportConfig createDurareportConfigFrom(InputStream xml) {
}
/**
- * This method serializes the provide durareport configuration into xml.
+ * This method serializes the provide duraboss configuration into xml.
*
- * @param durareportConfig
+ * @param durabossConfig
* @return
*/
- public static String createDocumentFrom(DurareportConfig durareportConfig) {
+ public static String createDocumentFrom(DurabossConfig durabossConfig) {
StringBuilder xml = new StringBuilder();
- if (null != durareportConfig) {
- String durastoreHost = durareportConfig.getDurastoreHost();
- String durastorePort = durareportConfig.getDurastorePort();
- String durastoreContext = durareportConfig.getDurastoreContext();
- String duraserviceHost = durareportConfig.getDuraserviceHost();
- String duraservicePort = durareportConfig.getDuraservicePort();
- String duraserviceContext = durareportConfig.getDuraserviceContext();
+ if (null != durabossConfig) {
+ String durastoreHost = durabossConfig.getDurastoreHost();
+ String durastorePort = durabossConfig.getDurastorePort();
+ String durastoreContext = durabossConfig.getDurastoreContext();
+ String duraserviceHost = durabossConfig.getDuraserviceHost();
+ String duraservicePort = durabossConfig.getDuraservicePort();
+ String duraserviceContext = durabossConfig.getDuraserviceContext();
- xml.append("<durareportConfig>");
+ xml.append("<durabossConfig>");
xml.append(" <durastoreHost>" + durastoreHost);
xml.append("</durastoreHost>");
xml.append(" <durastorePort>" + durastorePort);
@@ -124,7 +124,7 @@ public static String createDocumentFrom(DurareportConfig durareportConfig) {
xml.append("</duraserviceContext>");
Collection<NotificationConfig> notificationConfigs =
- durareportConfig.getNotificationConfigs();
+ durabossConfig.getNotificationConfigs();
if(null != notificationConfigs) {
for(NotificationConfig config : notificationConfigs) {
String encUsername = encrypt(config.getUsername());
@@ -142,7 +142,7 @@ public static String createDocumentFrom(DurareportConfig durareportConfig) {
}
}
- xml.append("</durareportConfig>");
+ xml.append("</durabossConfig>");
}
return xml.toString();
}
diff --git a/app-config/src/main/java/org/duracloud/appconfig/xml/DuradminInitDocumentBinding.java b/app-config/src/main/java/org/duracloud/appconfig/xml/DuradminInitDocumentBinding.java
index 800a7e4c4..27e7d2f46 100644
--- a/app-config/src/main/java/org/duracloud/appconfig/xml/DuradminInitDocumentBinding.java
+++ b/app-config/src/main/java/org/duracloud/appconfig/xml/DuradminInitDocumentBinding.java
@@ -47,7 +47,7 @@ public static DuradminConfig createDuradminConfigFrom(InputStream xml) {
config.setDuraserviceHost(root.getChildText("duraserviceHost"));
config.setDuraservicePort(root.getChildText("duraservicePort"));
config.setDuraserviceContext(root.getChildText("duraserviceContext"));
- config.setDurareportContext(root.getChildText("durareportContext"));
+ config.setDurabossContext(root.getChildText("durabossContext"));
config.setAmaUrl(root.getChildText("amaUrl"));
} catch (Exception e) {
diff --git a/app-config/src/main/resources/init.properties b/app-config/src/main/resources/init.properties
index 8cea7fdba..faa77c231 100644
--- a/app-config/src/main/resources/init.properties
+++ b/app-config/src/main/resources/init.properties
@@ -6,7 +6,7 @@ app.*.port=8080
app.durastore.context=durastore
app.duraservice.context=duraservice
app.duradmin.context=duradmin
-app.durareport.context=durareport
+app.duraboss.context=duraboss
###
# defines durastore accts
@@ -67,12 +67,12 @@ duradmin.duraservice-port=8080
duradmin.duraservice-context=duraservice
###
-# defines notification requirements, for durareport
+# defines notification requirements, for duraboss
###
-durareport.notification.0.type=EMAIL
-durareport.notification.0.username=[username]
-durareport.notification.0.password=[password]
-durareport.notification.0.originator=[from email address]
+duraboss.notification.0.type=EMAIL
+duraboss.notification.0.username=[username]
+duraboss.notification.0.password=[password]
+duraboss.notification.0.originator=[from email address]
###
# defines new users
diff --git a/app-config/src/test/java/org/duracloud/appconfig/ApplicationInitializerTest.java b/app-config/src/test/java/org/duracloud/appconfig/ApplicationInitializerTest.java
index ad2b19212..62306a860 100644
--- a/app-config/src/test/java/org/duracloud/appconfig/ApplicationInitializerTest.java
+++ b/app-config/src/test/java/org/duracloud/appconfig/ApplicationInitializerTest.java
@@ -9,7 +9,7 @@
import org.duracloud.appconfig.domain.Application;
import org.duracloud.appconfig.domain.DuradminConfig;
-import org.duracloud.appconfig.domain.DurareportConfig;
+import org.duracloud.appconfig.domain.DurabossConfig;
import org.duracloud.appconfig.domain.DuraserviceConfig;
import org.duracloud.appconfig.domain.DurastoreConfig;
import org.junit.Assert;
@@ -32,8 +32,8 @@ public class ApplicationInitializerTest {
private String durastoreContext = "durastoreContext";
private String duraservicePort = "duraservicePort";
private String duraserviceContext = "duraserviceContext";
- private String durareportPort = "durareportPort";
- private String durareportContext = "durareportContext";
+ private String durabossPort = "durabossPort";
+ private String durabossContext = "durabossContext";
private String allHost = "allHost";
@Test
@@ -56,7 +56,7 @@ private Properties createProps() {
String pAdm = p + DuradminConfig.QUALIFIER + dot;
String pStr = p + DurastoreConfig.QUALIFIER + dot;
String pSrv = p + DuraserviceConfig.QUALIFIER + dot;
- String pRpt = p + DurareportConfig.QUALIFIER + dot;
+ String pRpt = p + DurabossConfig.QUALIFIER + dot;
String pWild = p + ApplicationInitializer.wildcardKey + dot;
String host = ApplicationInitializer.hostKey;
@@ -66,11 +66,11 @@ private Properties createProps() {
props.put(pAdm + port, duradminPort);
props.put(pStr + port, durastorePort);
props.put(pSrv + port, duraservicePort);
- props.put(pRpt + port, durareportPort);
+ props.put(pRpt + port, durabossPort);
props.put(pAdm + context, duradminContext);
props.put(pStr + context, durastoreContext);
props.put(pSrv + context, duraserviceContext);
- props.put(pRpt + context, durareportContext);
+ props.put(pRpt + context, durabossContext);
props.put(pWild + host, allHost);
return props;
@@ -80,12 +80,12 @@ private void verifyApplicationInitializer(ApplicationInitializer config) {
Application duradmin = config.getDuradmin();
Application durastore = config.getDurastore();
Application duraservice = config.getDuraservice();
- Application durareport = config.getDurareport();
+ Application duraboss = config.getDuraboss();
Assert.assertNotNull(duradmin);
Assert.assertNotNull(durastore);
Assert.assertNotNull(duraservice);
- Assert.assertNotNull(durareport);
+ Assert.assertNotNull(duraboss);
String adminHost = duradmin.getHost();
String adminPort = duradmin.getPort();
@@ -96,9 +96,9 @@ private void verifyApplicationInitializer(ApplicationInitializer config) {
String serviceHost = duraservice.getHost();
String servicePort = duraservice.getPort();
String serviceContext = duraservice.getContext();
- String reportHost = durareport.getHost();
- String reportPort = durareport.getPort();
- String reportContext = durareport.getContext();
+ String reportHost = duraboss.getHost();
+ String reportPort = duraboss.getPort();
+ String reportContext = duraboss.getContext();
Assert.assertNotNull(adminHost);
Assert.assertNotNull(adminPort);
@@ -123,8 +123,8 @@ private void verifyApplicationInitializer(ApplicationInitializer config) {
Assert.assertEquals(duraservicePort, servicePort);
Assert.assertEquals(duraserviceContext, serviceContext);
Assert.assertEquals(allHost, reportHost);
- Assert.assertEquals(durareportPort, reportPort);
- Assert.assertEquals(durareportContext, reportContext);
+ Assert.assertEquals(durabossPort, reportPort);
+ Assert.assertEquals(durabossContext, reportContext);
}
}
diff --git a/app-config/src/test/java/org/duracloud/appconfig/domain/DurareportConfigTest.java b/app-config/src/test/java/org/duracloud/appconfig/domain/DurabossConfigTest.java
similarity index 68%
rename from app-config/src/test/java/org/duracloud/appconfig/domain/DurareportConfigTest.java
rename to app-config/src/test/java/org/duracloud/appconfig/domain/DurabossConfigTest.java
index 9e98fd29e..045fd19ee 100644
--- a/app-config/src/test/java/org/duracloud/appconfig/domain/DurareportConfigTest.java
+++ b/app-config/src/test/java/org/duracloud/appconfig/domain/DurabossConfigTest.java
@@ -18,7 +18,7 @@
* @author: Bill Branan
* Date: 5/12/11
*/
-public class DurareportConfigTest {
+public class DurabossConfigTest {
private String durastoreHost = "durastoreHost";
private String durastorePort = "durastorePort";
@@ -34,40 +34,40 @@ public class DurareportConfigTest {
@Test
public void testLoad() {
- DurareportConfig config = new DurareportConfig();
+ DurabossConfig config = new DurabossConfig();
config.load(createProps());
- verifyDurareportConfig(config);
+ verifyDurabossConfig(config);
}
private Map<String, String> createProps() {
Map<String, String> props = new HashMap<String, String>();
- String p = DurareportConfig.QUALIFIER + ".";
+ String p = DurabossConfig.QUALIFIER + ".";
- props.put(p + DurareportConfig.duraStoreHostKey, durastoreHost);
- props.put(p + DurareportConfig.duraStorePortKey, durastorePort);
- props.put(p + DurareportConfig.duraStoreContextKey, durastoreContext);
- props.put(p + DurareportConfig.duraServiceHostKey, duraserviceHost);
- props.put(p + DurareportConfig.duraServicePortKey, duraservicePort);
- props.put(p + DurareportConfig.duraServiceContextKey, duraserviceContext);
+ props.put(p + DurabossConfig.duraStoreHostKey, durastoreHost);
+ props.put(p + DurabossConfig.duraStorePortKey, durastorePort);
+ props.put(p + DurabossConfig.duraStoreContextKey, durastoreContext);
+ props.put(p + DurabossConfig.duraServiceHostKey, duraserviceHost);
+ props.put(p + DurabossConfig.duraServicePortKey, duraservicePort);
+ props.put(p + DurabossConfig.duraServiceContextKey, duraserviceContext);
- props.put(p + DurareportConfig.notificationKey + ".0." +
- DurareportConfig.notificationTypeKey,
+ props.put(p + DurabossConfig.notificationKey + ".0." +
+ DurabossConfig.notificationTypeKey,
notifyType);
- props.put(p + DurareportConfig.notificationKey + ".0." +
- DurareportConfig.notificationUsernameKey,
+ props.put(p + DurabossConfig.notificationKey + ".0." +
+ DurabossConfig.notificationUsernameKey,
notifyUsername);
- props.put(p + DurareportConfig.notificationKey + ".0." +
- DurareportConfig.notificationPasswordKey,
+ props.put(p + DurabossConfig.notificationKey + ".0." +
+ DurabossConfig.notificationPasswordKey,
notifyPassword);
- props.put(p + DurareportConfig.notificationKey + ".0." +
- DurareportConfig.notificationOriginatorKey,
+ props.put(p + DurabossConfig.notificationKey + ".0." +
+ DurabossConfig.notificationOriginatorKey,
notifyOriginator);
return props;
}
- private void verifyDurareportConfig(DurareportConfig config) {
+ private void verifyDurabossConfig(DurabossConfig config) {
Assert.assertNotNull(config.getDurastoreHost());
Assert.assertNotNull(config.getDurastorePort());
diff --git a/app-config/src/test/java/org/duracloud/appconfig/domain/DuradminConfigTest.java b/app-config/src/test/java/org/duracloud/appconfig/domain/DuradminConfigTest.java
index af63b2362..ac02bef55 100644
--- a/app-config/src/test/java/org/duracloud/appconfig/domain/DuradminConfigTest.java
+++ b/app-config/src/test/java/org/duracloud/appconfig/domain/DuradminConfigTest.java
@@ -28,7 +28,7 @@ public class DuradminConfigTest {
private String duraserviceHost = "duraserviceHost";
private String duraservicePort = "duraservicePort";
private String duraserviceContext = "duraserviceContext";
- private String durareportContext = "durareportContext";
+ private String durabossContext = "durabossContext";
private String amaUrl = "amaUrl";
@@ -54,7 +54,7 @@ private Map<String, String> createProps() {
props.put(p + DuradminConfig.duraServiceHostKey, duraserviceHost);
props.put(p + DuradminConfig.duraServicePortKey, duraservicePort);
props.put(p + DuradminConfig.duraServiceContextKey, duraserviceContext);
- props.put(p + DuradminConfig.duraReportContextKey, durareportContext);
+ props.put(p + DuradminConfig.duraBossContextKey, durabossContext);
props.put(p + DuradminConfig.amaUrlKey, amaUrl);
return props;
@@ -68,7 +68,7 @@ private void verifyDuradminConfig(DuradminConfig config) {
Assert.assertNotNull(config.getDuraserviceHost());
Assert.assertNotNull(config.getDuraservicePort());
Assert.assertNotNull(config.getDuraserviceContext());
- Assert.assertNotNull(config.getDurareportContext());
+ Assert.assertNotNull(config.getDurabossContext());
Assert.assertNotNull(config.getAmaUrl());
@@ -78,7 +78,7 @@ private void verifyDuradminConfig(DuradminConfig config) {
Assert.assertEquals(duraserviceHost, config.getDuraserviceHost());
Assert.assertEquals(duraservicePort, config.getDuraservicePort());
Assert.assertEquals(duraserviceContext, config.getDuraserviceContext());
- Assert.assertEquals(durareportContext, config.getDurareportContext());
+ Assert.assertEquals(durabossContext, config.getDurabossContext());
Assert.assertEquals(amaUrl, config.getAmaUrl());
}
diff --git a/app-config/src/test/java/org/duracloud/appconfig/xml/DurareportInitDocumentBindingTest.java b/app-config/src/test/java/org/duracloud/appconfig/xml/DurabossInitDocumentBindingTest.java
similarity index 88%
rename from app-config/src/test/java/org/duracloud/appconfig/xml/DurareportInitDocumentBindingTest.java
rename to app-config/src/test/java/org/duracloud/appconfig/xml/DurabossInitDocumentBindingTest.java
index 4de42443e..ce77c04c1 100644
--- a/app-config/src/test/java/org/duracloud/appconfig/xml/DurareportInitDocumentBindingTest.java
+++ b/app-config/src/test/java/org/duracloud/appconfig/xml/DurabossInitDocumentBindingTest.java
@@ -7,7 +7,7 @@
*/
package org.duracloud.appconfig.xml;
-import org.duracloud.appconfig.domain.DurareportConfig;
+import org.duracloud.appconfig.domain.DurabossConfig;
import org.duracloud.appconfig.domain.NotificationConfig;
import org.junit.Test;
@@ -24,7 +24,7 @@
* @author: Bill Branan
* Date: 12/6/11
*/
-public class DurareportInitDocumentBindingTest {
+public class DurabossInitDocumentBindingTest {
private String durastoreHost = "durastoreHost";
private String durastorePort = "durastorePort";
@@ -41,7 +41,7 @@ public class DurareportInitDocumentBindingTest {
@Test
public void testXmlRoundTrip() throws Exception {
// Create config
- DurareportConfig config = new DurareportConfig();
+ DurabossConfig config = new DurabossConfig();
config.setDurastoreHost(durastoreHost);
config.setDurastorePort(durastorePort);
config.setDurastoreContext(durastoreContext);
@@ -60,12 +60,12 @@ public void testXmlRoundTrip() throws Exception {
config.setNotificationConfigs(notifyConfigMap);
// Run round trip
- String xml = DurareportInitDocumentBinding.createDocumentFrom(config);
+ String xml = DurabossInitDocumentBinding.createDocumentFrom(config);
assertNotNull(xml);
InputStream xmlStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
- DurareportConfig trippedConfig =
- DurareportInitDocumentBinding.createDurareportConfigFrom(xmlStream);
+ DurabossConfig trippedConfig =
+ DurabossInitDocumentBinding.createDurabossConfigFrom(xmlStream);
// Verify results
assertEquals(config.getDurastoreHost(),
diff --git a/duraboss/pom.xml b/duraboss/pom.xml
new file mode 100644
index 000000000..d85ee2233
--- /dev/null
+++ b/duraboss/pom.xml
@@ -0,0 +1,96 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.duracloud</groupId>
+ <artifactId>duraboss</artifactId>
+ <packaging>war</packaging>
+ <version>1.4.0-SNAPSHOT</version>
+ <name>DuraCloud DuraBoss</name>
+ <url>http://localhost:8080/${artifactId}</url>
+
+ <parent>
+ <groupId>org.duracloud</groupId>
+ <artifactId>duracloud</artifactId>
+ <version>1.4.0-SNAPSHOT</version>
+ <relativePath>../pom.xml</relativePath>
+ </parent>
+
+ <build>
+
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>2.3.1</version>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>for-integration-test</classifier>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+
+ </build>
+
+ <dependencies>
+
+ <!-- internal projects -->
+ <dependency>
+ <groupId>org.duracloud</groupId>
+ <artifactId>common</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.duracloud</groupId>
+ <artifactId>common-rest</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.duracloud</groupId>
+ <artifactId>security</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.duracloud</groupId>
+ <artifactId>reporter</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <!-- for Spring -->
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-core</artifactId>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- for Jersey -->
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-server</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey.contribs</groupId>
+ <artifactId>jersey-spring</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.xml.bind</groupId>
+ <artifactId>jaxb-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.mail</groupId>
+ <artifactId>mail</artifactId>
+ </dependency>
+
+ </dependencies>
+
+</project>
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/BaseRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/BaseRest.java
similarity index 95%
rename from durareport/src/main/java/org/duracloud/durareport/rest/BaseRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/BaseRest.java
index 624034ffd..d1333389b 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/BaseRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/BaseRest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
@@ -35,7 +35,7 @@ public class BaseRest {
MediaType.APPLICATION_XML_TYPE;
public static final MediaType TEXT_PLAIN = MediaType.TEXT_PLAIN_TYPE;
- public static final String APP_NAME = "DuraReport";
+ public static final String APP_NAME = "DuraBoss";
protected Response responseOk(String text) {
return Response.ok(text, TEXT_PLAIN).build();
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/InitRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/InitRest.java
similarity index 92%
rename from durareport/src/main/java/org/duracloud/durareport/rest/InitRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/InitRest.java
index 00a1c02e2..213b019a8 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/InitRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/InitRest.java
@@ -5,17 +5,17 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
-import org.duracloud.appconfig.domain.DurareportConfig;
-import org.duracloud.appconfig.xml.DurareportInitDocumentBinding;
+import org.duracloud.appconfig.domain.DurabossConfig;
+import org.duracloud.appconfig.xml.DurabossInitDocumentBinding;
import org.duracloud.client.ContentStoreManager;
import org.duracloud.client.ContentStoreManagerImpl;
import org.duracloud.client.ServicesManagerImpl;
import org.duracloud.common.model.Credential;
import org.duracloud.common.rest.RestUtil;
import org.duracloud.common.util.InitUtil;
-import org.duracloud.durareport.notification.NotificationManager;
+import org.duracloud.reporter.notification.NotificationManager;
import org.duracloud.security.context.SecurityContextUtil;
import org.duracloud.security.error.NoUserLoggedInException;
import org.duracloud.serviceapi.ServicesManager;
@@ -67,7 +67,7 @@ public InitRest(StorageReportResource storageResource,
}
/**
- * Initializes DuraReport
+ * Initializes DuraBoss
*
* @return 200 response with text indicating success
*/
@@ -87,8 +87,8 @@ public Response initialize(){
}
private void doInitialize(InputStream xml) throws NoUserLoggedInException {
- DurareportConfig config =
- DurareportInitDocumentBinding.createDurareportConfigFrom(xml);
+ DurabossConfig config =
+ DurabossInitDocumentBinding.createDurabossConfigFrom(xml);
Credential credential = securityContextUtil.getCurrentUser();
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/SecurityRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/SecurityRest.java
similarity index 97%
rename from durareport/src/main/java/org/duracloud/durareport/rest/SecurityRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/SecurityRest.java
index 85ba538e8..52c489c5e 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/SecurityRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/SecurityRest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.common.rest.RestUtil;
import org.duracloud.security.DuracloudUserDetailsService;
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportResource.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportResource.java
similarity index 91%
rename from durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportResource.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportResource.java
index 1e7089c6d..75132c985 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportResource.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportResource.java
@@ -5,10 +5,10 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
-import org.duracloud.durareport.service.ServiceNotificationMonitor;
-import org.duracloud.durareport.service.ServiceReportBuilder;
+import org.duracloud.reporter.service.ServiceNotificationMonitor;
+import org.duracloud.reporter.service.ServiceReportBuilder;
import org.duracloud.servicemonitor.ServiceMonitor;
import org.duracloud.servicemonitor.ServiceSummarizer;
import org.duracloud.servicemonitor.ServiceSummaryDirectory;
@@ -75,7 +75,7 @@ public InputStream getCompletedServicesReport(String reportId)
public void checkInitialized() {
if(null == reportBuilder) {
- throw new RuntimeException("DuraReport must be initialized.");
+ throw new RuntimeException("DuraBoss must be initialized.");
}
}
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportRest.java
similarity index 98%
rename from durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportRest.java
index 774540d7b..bc97aa4a2 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/ServiceReportRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/ServiceReportRest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.servicemonitor.error.ServiceSummaryNotFoundException;
import org.slf4j.Logger;
@@ -23,7 +23,7 @@
* @author: Bill Branan
* Date: 5/12/11
*/
-@Path("/servicereport")
+@Path("/report/service")
public class ServiceReportRest extends BaseRest {
private ServiceReportResource resource;
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/StorageReportResource.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportResource.java
similarity index 96%
rename from durareport/src/main/java/org/duracloud/durareport/rest/StorageReportResource.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportResource.java
index b1dce70ac..a866a702a 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/StorageReportResource.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportResource.java
@@ -5,13 +5,13 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.client.ContentStoreManager;
-import org.duracloud.durareport.error.InvalidScheduleException;
-import org.duracloud.durareport.storage.StorageReportBuilder;
-import org.duracloud.durareport.storage.StorageReportHandler;
-import org.duracloud.durareport.storage.StorageReportScheduler;
+import org.duracloud.reporter.error.InvalidScheduleException;
+import org.duracloud.reporter.storage.StorageReportBuilder;
+import org.duracloud.reporter.storage.StorageReportHandler;
+import org.duracloud.reporter.storage.StorageReportScheduler;
import org.duracloud.error.ContentStoreException;
import org.duracloud.reportdata.storage.StorageReportInfo;
import org.duracloud.reportdata.storage.StorageReportList;
@@ -247,7 +247,7 @@ public void dispose() {
private void checkInitialized() {
if(null == storeMgr) {
- throw new RuntimeException("DuraReport must be initialized.");
+ throw new RuntimeException("DuraBoss must be initialized.");
}
}
diff --git a/durareport/src/main/java/org/duracloud/durareport/rest/StorageReportRest.java b/duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportRest.java
similarity index 97%
rename from durareport/src/main/java/org/duracloud/durareport/rest/StorageReportRest.java
rename to duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportRest.java
index e1891f17b..2fb7ea2b5 100644
--- a/durareport/src/main/java/org/duracloud/durareport/rest/StorageReportRest.java
+++ b/duraboss/src/main/java/org/duracloud/duraboss/rest/StorageReportRest.java
@@ -5,9 +5,9 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
-import org.duracloud.durareport.error.InvalidScheduleException;
+import org.duracloud.reporter.error.InvalidScheduleException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -27,7 +27,7 @@
* @author: Bill Branan
* Date: 5/11/11
*/
-@Path("/storagereport")
+@Path("/report/storage")
public class StorageReportRest extends BaseRest {
private StorageReportResource resource;
diff --git a/durareport/src/main/resources/logback.xml b/duraboss/src/main/resources/logback.xml
similarity index 97%
rename from durareport/src/main/resources/logback.xml
rename to duraboss/src/main/resources/logback.xml
index 341dde314..8852cf7b8 100644
--- a/durareport/src/main/resources/logback.xml
+++ b/duraboss/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
<configuration debug="true" scan="true">
<jmxConfigurator/>
- <property name="LOG_FILENAME" value="${duracloud.home}/logs/duracloud-durareport.log" />
+ <property name="LOG_FILENAME" value="${duracloud.home}/logs/duracloud-duraboss.log" />
<appender name="DURACLOUD" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--See also http://logback.qos.ch/manual/appenders.html#RollingFileAppender-->
diff --git a/durareport/src/main/webapp/WEB-INF/config/duracloud-app-config.xml b/duraboss/src/main/webapp/WEB-INF/config/duracloud-app-config.xml
similarity index 100%
rename from durareport/src/main/webapp/WEB-INF/config/duracloud-app-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/duracloud-app-config.xml
diff --git a/durareport/src/main/webapp/WEB-INF/config/messaging-config.xml b/duraboss/src/main/webapp/WEB-INF/config/messaging-config.xml
similarity index 100%
rename from durareport/src/main/webapp/WEB-INF/config/messaging-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/messaging-config.xml
diff --git a/durareport/src/main/webapp/WEB-INF/config/notification-config.xml b/duraboss/src/main/webapp/WEB-INF/config/notification-config.xml
similarity index 70%
rename from durareport/src/main/webapp/WEB-INF/config/notification-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/notification-config.xml
index c738753ee..5b327171d 100644
--- a/durareport/src/main/webapp/WEB-INF/config/notification-config.xml
+++ b/duraboss/src/main/webapp/WEB-INF/config/notification-config.xml
@@ -6,17 +6,17 @@
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="serviceNotificationMonitor"
- class="org.duracloud.durareport.service.ServiceNotificationMonitor">
+ class="org.duracloud.reporter.service.ServiceNotificationMonitor">
<constructor-arg ref="notificationManager" />
<constructor-arg ref="userDetailsSvc" />
</bean>
<bean id="notificationManager"
- class="org.duracloud.durareport.notification.NotificationManager">
+ class="org.duracloud.reporter.notification.NotificationManager">
<constructor-arg ref="emailNotifier"/>
</bean>
<bean id="emailNotifier"
- class="org.duracloud.durareport.notification.EmailNotifier"/>
+ class="org.duracloud.reporter.notification.EmailNotifier"/>
</beans>
\ No newline at end of file
diff --git a/durareport/src/main/webapp/WEB-INF/config/restapi-config.xml b/duraboss/src/main/webapp/WEB-INF/config/restapi-config.xml
similarity index 78%
rename from durareport/src/main/webapp/WEB-INF/config/restapi-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/restapi-config.xml
index 44d74ee71..e78b5c51c 100644
--- a/durareport/src/main/webapp/WEB-INF/config/restapi-config.xml
+++ b/duraboss/src/main/webapp/WEB-INF/config/restapi-config.xml
@@ -6,15 +6,15 @@
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- REST API resources -->
- <bean id="storageReportRest" class="org.duracloud.durareport.rest.StorageReportRest" >
+ <bean id="storageReportRest" class="org.duracloud.duraboss.rest.StorageReportRest" >
<constructor-arg ref="storageResource"/>
</bean>
- <bean id="serviceReportRest" class="org.duracloud.durareport.rest.ServiceReportRest" >
+ <bean id="serviceReportRest" class="org.duracloud.duraboss.rest.ServiceReportRest" >
<constructor-arg ref="serviceResource"/>
</bean>
- <bean id="initRest" class="org.duracloud.durareport.rest.InitRest" >
+ <bean id="initRest" class="org.duracloud.duraboss.rest.InitRest" >
<constructor-arg ref="storageResource"/>
<constructor-arg ref="serviceResource"/>
<constructor-arg ref="summaryDirectory"/>
@@ -24,19 +24,19 @@
<constructor-arg ref="notificationManager"/>
</bean>
- <bean id="securityRest" class="org.duracloud.durareport.rest.SecurityRest">
+ <bean id="securityRest" class="org.duracloud.duraboss.rest.SecurityRest">
<constructor-arg ref="userDetailsSvc" />
<constructor-arg ref="restUtil"/>
</bean>
<!-- Support beans -->
- <bean id="storageResource" class="org.duracloud.durareport.rest.StorageReportResource"
+ <bean id="storageResource" class="org.duracloud.duraboss.rest.StorageReportResource"
destroy-method="dispose">
<constructor-arg value="report/storage-report-"/>
<constructor-arg value="report/error-log-storage-report.txt"/>
</bean>
- <bean id="serviceResource" class="org.duracloud.durareport.rest.ServiceReportResource" >
+ <bean id="serviceResource" class="org.duracloud.duraboss.rest.ServiceReportResource" >
<constructor-arg ref="serviceMonitor"/>
<constructor-arg ref="serviceNotificationMonitor"/>
</bean>
diff --git a/durareport/src/main/webapp/WEB-INF/config/security-config.xml b/duraboss/src/main/webapp/WEB-INF/config/security-config.xml
similarity index 100%
rename from durareport/src/main/webapp/WEB-INF/config/security-config.xml
rename to duraboss/src/main/webapp/WEB-INF/config/security-config.xml
diff --git a/durareport/src/main/webapp/WEB-INF/web.xml b/duraboss/src/main/webapp/WEB-INF/web.xml
similarity index 97%
rename from durareport/src/main/webapp/WEB-INF/web.xml
rename to duraboss/src/main/webapp/WEB-INF/web.xml
index 77fd06a45..af7fb1d7e 100644
--- a/durareport/src/main/webapp/WEB-INF/web.xml
+++ b/duraboss/src/main/webapp/WEB-INF/web.xml
@@ -18,7 +18,7 @@
</listener>
<servlet>
- <servlet-name>durareport</servlet-name>
+ <servlet-name>duraboss</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
diff --git a/durareport/src/main/webapp/index.jsp b/duraboss/src/main/webapp/index.jsp
similarity index 60%
rename from durareport/src/main/webapp/index.jsp
rename to duraboss/src/main/webapp/index.jsp
index 4bf1fd442..0867daa04 100644
--- a/durareport/src/main/webapp/index.jsp
+++ b/duraboss/src/main/webapp/index.jsp
@@ -1,6 +1,6 @@
<html>
<head>
<%-- Redirected because we can't set the welcome page to a virtual URL. --%>
- <meta http-equiv="refresh" content="0; url=/durareport/storagereport">
+ <meta http-equiv="refresh" content="0; url=/duraboss/report/storage">
</head>
</html>
\ No newline at end of file
diff --git a/durareport/src/test/java/org/duracloud/durareport/rest/InitRestTest.java b/duraboss/src/test/java/org/duracloud/duraboss/rest/InitRestTest.java
similarity index 91%
rename from durareport/src/test/java/org/duracloud/durareport/rest/InitRestTest.java
rename to duraboss/src/test/java/org/duracloud/duraboss/rest/InitRestTest.java
index d81415a50..faf416c4a 100644
--- a/durareport/src/test/java/org/duracloud/durareport/rest/InitRestTest.java
+++ b/duraboss/src/test/java/org/duracloud/duraboss/rest/InitRestTest.java
@@ -5,10 +5,9 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.common.rest.RestUtil;
-import org.duracloud.durareport.notification.NotificationManager;
import org.easymock.classextension.EasyMock;
import org.junit.After;
import org.junit.Before;
diff --git a/durareport/src/test/java/org/duracloud/durareport/rest/StorageReportResourceTest.java b/duraboss/src/test/java/org/duracloud/duraboss/rest/StorageReportResourceTest.java
similarity index 94%
rename from durareport/src/test/java/org/duracloud/durareport/rest/StorageReportResourceTest.java
rename to duraboss/src/test/java/org/duracloud/duraboss/rest/StorageReportResourceTest.java
index b83a33ddb..18635b595 100644
--- a/durareport/src/test/java/org/duracloud/durareport/rest/StorageReportResourceTest.java
+++ b/duraboss/src/test/java/org/duracloud/duraboss/rest/StorageReportResourceTest.java
@@ -5,12 +5,12 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.rest;
+package org.duracloud.duraboss.rest;
import org.duracloud.client.ContentStoreManager;
-import org.duracloud.durareport.storage.StorageReportBuilder;
-import org.duracloud.durareport.storage.StorageReportHandler;
-import org.duracloud.durareport.storage.StorageReportScheduler;
+import org.duracloud.reporter.storage.StorageReportBuilder;
+import org.duracloud.reporter.storage.StorageReportHandler;
+import org.duracloud.reporter.storage.StorageReportScheduler;
import org.duracloud.reportdata.storage.StorageReportList;
import org.easymock.classextension.EasyMock;
import org.junit.After;
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/config/DuradminConfig.java b/duradmin/src/main/java/org/duracloud/duradmin/config/DuradminConfig.java
index 0a9bb4244..96b63a994 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/config/DuradminConfig.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/config/DuradminConfig.java
@@ -35,7 +35,7 @@ public class DuradminConfig
private static String duraserviceContextKey = "duraserviceContext";
- private static String durareportContextKey = "durareportContext";
+ private static String durabossContextKey = "durabossContext";
private static boolean initialized = false;
@@ -128,25 +128,25 @@ private static void initFromProperties() {
config.setDuraServiceHost(getPropsHost());
config.setDuraServicePort(getPropsPort());
config.setDuraServiceContext(getPropsDuraServiceContext());
- config.setDuraReportContext(getPropsDuraReportContext());
+ config.setDuraBossContext(getPropsDuraBossContext());
config.setAmaUrl(null); // default is null.
}
- private static String getPropsDuraReportContext() {
- return getProps().getProperty(durareportContextKey, "durareport");
+ private static String getPropsDuraBossContext() {
+ return getProps().getProperty(durabossContextKey, "duraboss");
}
- public static String getDuraReportHost() {
+ public static String getDuraBossHost() {
return getPropsHost();
}
- public static String getDuraReportPort() {
+ public static String getDuraBossPort() {
return getPropsPort();
}
- public static String getDuraReportContext() {
- return getPropsDuraReportContext();
+ public static String getDuraBossContext() {
+ return getPropsDuraBossContext();
}
}
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/control/InitController.java b/duradmin/src/main/java/org/duracloud/duradmin/control/InitController.java
index 596a86d2b..b314af056 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/control/InitController.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/control/InitController.java
@@ -7,18 +7,6 @@
*/
package org.duracloud.duradmin.control;
-import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
-import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
-import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED;
-import static javax.servlet.http.HttpServletResponse.SC_OK;
-import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
-import static org.duracloud.appconfig.xml.DuradminInitDocumentBinding.createDuradminConfigFrom;
-import static org.duracloud.common.util.ExceptionUtil.getStackTraceAsString;
-
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.duracloud.common.util.InitUtil;
import org.duracloud.duradmin.config.DuradminConfig;
import org.duracloud.duradmin.domain.AdminInit;
@@ -27,6 +15,18 @@
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
+import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED;
+import static javax.servlet.http.HttpServletResponse.SC_OK;
+import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
+import static org.duracloud.appconfig.xml.DuradminInitDocumentBinding.createDuradminConfigFrom;
+import static org.duracloud.common.util.ExceptionUtil.getStackTraceAsString;
+
/**
* This class initializes the application based on the xml body of the
* servlet request.
@@ -87,7 +87,7 @@ private void updateInit(org.duracloud.appconfig.domain.DuradminConfig config)
init.setDuraStorePort(config.getDurastorePort());
init.setDuraStoreContext(config.getDurastoreContext());
init.setAmaUrl(config.getAmaUrl());
- init.setDuraReportContext(config.getDurareportContext());
+ init.setDuraBossContext(config.getDurabossContext());
DuradminConfig.setConfig(init);
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/domain/AdminInit.java b/duradmin/src/main/java/org/duracloud/duradmin/domain/AdminInit.java
index fb2c01517..a86141417 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/domain/AdminInit.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/domain/AdminInit.java
@@ -20,7 +20,7 @@ public class AdminInit {
private String duraServicePort;
private String duraServiceContext;
private String amaUrl;
- private String duraReportContext;
+ private String duraBossContext;
public String getDuraStoreHost() {
return duraStoreHost;
@@ -78,11 +78,11 @@ public void setAmaUrl(String amaUrl) {
this.amaUrl = amaUrl;
}
- public void setDuraReportContext(String durareportContext) {
- this.duraReportContext = durareportContext;
+ public void setDuraBossContext(String durabossContext) {
+ this.duraBossContext = durabossContext;
}
- public String getDuraReportContext() {
- return duraReportContext;
+ public String getDuraBossContext() {
+ return duraBossContext;
}
}
\ No newline at end of file
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminServiceReportManagerImpl.java b/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminServiceReportManagerImpl.java
index 0ce7fed09..7ff47e0b0 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminServiceReportManagerImpl.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminServiceReportManagerImpl.java
@@ -18,9 +18,9 @@
public class DuradminServiceReportManagerImpl extends ServiceReportManagerImpl{
public DuradminServiceReportManagerImpl(){
- super(DuradminConfig.getDuraReportHost(),
- DuradminConfig.getDuraReportPort(),
- DuradminConfig.getDuraReportContext());
+ super(DuradminConfig.getDuraBossHost(),
+ DuradminConfig.getDuraBossPort(),
+ DuradminConfig.getDuraBossContext());
}
}
diff --git a/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminStorageReportManagerImpl.java b/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminStorageReportManagerImpl.java
index d39f2a04d..cdc306fa3 100644
--- a/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminStorageReportManagerImpl.java
+++ b/duradmin/src/main/java/org/duracloud/duradmin/report/DuradminStorageReportManagerImpl.java
@@ -18,9 +18,9 @@
public class DuradminStorageReportManagerImpl extends StorageReportManagerImpl{
public DuradminStorageReportManagerImpl(){
- super(DuradminConfig.getDuraReportHost(),
- DuradminConfig.getDuraReportPort(),
- DuradminConfig.getDuraReportContext());
+ super(DuradminConfig.getDuraBossHost(),
+ DuradminConfig.getDuraBossPort(),
+ DuradminConfig.getDuraBossContext());
}
}
diff --git a/pom.xml b/pom.xml
index 38c30178a..f350a075f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -85,7 +85,8 @@
<module>servicemonitor</module>
<module>duraservice</module>
<module>reportdata</module>
- <module>durareport</module>
+ <module>reporter</module>
+ <module>duraboss</module>
<module>reportclient</module>
<module>app-config</module>
<module>serviceclient</module>
diff --git a/reportclient/resources/ExampleReportClient.java b/reportclient/resources/ExampleReportClient.java
index 8916e76e7..c5bd7f30d 100644
--- a/reportclient/resources/ExampleReportClient.java
+++ b/reportclient/resources/ExampleReportClient.java
@@ -24,8 +24,8 @@
import java.util.Map;
/**
- * Example code which connects to the DuraCloud DuraReport REST API by using
- * the ReportClient.
+ * Example code which connects to the DuraCloud DuraBoss reporting REST API
+ * by using the ReportClient.
*
* @author Bill Branan
* Date: 6/2/11
@@ -36,7 +36,7 @@ public class ExampleReportClient {
private static final String PASSWORD = "upw"; // replace as necessary
private static final String HOST = "localhost"; // replace as necessary
private static final String PORT = "8080"; // replace as necessary
- private static final String CONTEXT = "durareport";
+ private static final String CONTEXT = "duraboss";
private StorageReportManager storageReportManager;
private ServiceReportManager serviceReportManager;
diff --git a/reportclient/resources/readme.txt b/reportclient/resources/readme.txt
index 71ac7f584..07ab8cc19 100644
--- a/reportclient/resources/readme.txt
+++ b/reportclient/resources/readme.txt
@@ -4,11 +4,11 @@
DuraCloud provides reporting over both storage and service functions
which occur within the DuraCloud framework. The building of these
-reports is managed by the DuraReport web application. DuraReport
+reports is managed by the DuraBoss web application. DuraBoss
is installed and running on your DuraCloud instance and can be
accessed via a REST interface. In order to aid Java developers in
-communicating with DuraReport, a Java client, called ReportClient
-was written.
+communicating with DuraBoss report features, a Java client, called
+ReportClient was written.
2. Using ReportClient
diff --git a/reportclient/src/main/java/org/duracloud/client/report/BaseReportManager.java b/reportclient/src/main/java/org/duracloud/client/report/BaseReportManager.java
index e44308ace..70553369b 100644
--- a/reportclient/src/main/java/org/duracloud/client/report/BaseReportManager.java
+++ b/reportclient/src/main/java/org/duracloud/client/report/BaseReportManager.java
@@ -25,7 +25,7 @@ public abstract class BaseReportManager implements Securable {
protected RestHttpHelper restHelper;
- private static final String DEFAULT_CONTEXT = "durareport";
+ private static final String DEFAULT_CONTEXT = "duraboss";
private String baseURL = null;
public BaseReportManager(String host, String port) {
diff --git a/reportclient/src/main/java/org/duracloud/client/report/ServiceReportManagerImpl.java b/reportclient/src/main/java/org/duracloud/client/report/ServiceReportManagerImpl.java
index da15ee2c2..6b14fd06a 100644
--- a/reportclient/src/main/java/org/duracloud/client/report/ServiceReportManagerImpl.java
+++ b/reportclient/src/main/java/org/duracloud/client/report/ServiceReportManagerImpl.java
@@ -35,7 +35,7 @@ public ServiceReportManagerImpl(String host, String port, String context) {
}
private String buildURL(String relativeURL) {
- String storageReport = "servicereport";
+ String storageReport = "report/service";
if (null == relativeURL) {
return getBaseURL() + "/" + storageReport;
}
diff --git a/reportclient/src/main/java/org/duracloud/client/report/StorageReportManager.java b/reportclient/src/main/java/org/duracloud/client/report/StorageReportManager.java
index e6ac9a3bf..a9f44d973 100644
--- a/reportclient/src/main/java/org/duracloud/client/report/StorageReportManager.java
+++ b/reportclient/src/main/java/org/duracloud/client/report/StorageReportManager.java
@@ -17,7 +17,7 @@
import java.util.List;
/**
- * Allows for communication with DuraReport
+ * Allows for communication with DuraBoss reporting
*
* @author: Bill Branan
* Date: 6/2/11
@@ -66,7 +66,7 @@ public StorageReportInfo getStorageReportInfo()
throws ReportException;
/**
- * Tells DuraReport to start running a new storage report generation
+ * Tells DuraBoss reporting to start running a new storage report generation
* process. If a report generation process is already underway, this
* call is ignored.
*
diff --git a/reportclient/src/main/java/org/duracloud/client/report/StorageReportManagerImpl.java b/reportclient/src/main/java/org/duracloud/client/report/StorageReportManagerImpl.java
index 6dc1b67b7..3a936136e 100644
--- a/reportclient/src/main/java/org/duracloud/client/report/StorageReportManagerImpl.java
+++ b/reportclient/src/main/java/org/duracloud/client/report/StorageReportManagerImpl.java
@@ -24,7 +24,7 @@
import java.util.List;
/**
- * Allows for communication with DuraReport
+ * Allows for communication with Duraboss reporting
*
* @author: Bill Branan
* Date: 6/2/11
@@ -40,7 +40,7 @@ public StorageReportManagerImpl(String host, String port, String context) {
}
private String buildURL(String relativeURL) {
- String storageReport = "storagereport";
+ String storageReport = "report/storage";
if (null == relativeURL) {
return getBaseURL() + "/" + storageReport;
}
diff --git a/reportclient/src/test/java/org/duracloud/client/report/ServiceReportManagerImplTest.java b/reportclient/src/test/java/org/duracloud/client/report/ServiceReportManagerImplTest.java
index 297c709c0..068d5ca23 100644
--- a/reportclient/src/test/java/org/duracloud/client/report/ServiceReportManagerImplTest.java
+++ b/reportclient/src/test/java/org/duracloud/client/report/ServiceReportManagerImplTest.java
@@ -47,7 +47,7 @@ public void setup() {
}
private String getBaseUrl() {
- return baseUrl + "/servicereport";
+ return baseUrl + "/report/service";
}
@Test
diff --git a/reportclient/src/test/java/org/duracloud/client/report/StorageReportManagerImplTest.java b/reportclient/src/test/java/org/duracloud/client/report/StorageReportManagerImplTest.java
index 6b6c53428..63081cfcc 100644
--- a/reportclient/src/test/java/org/duracloud/client/report/StorageReportManagerImplTest.java
+++ b/reportclient/src/test/java/org/duracloud/client/report/StorageReportManagerImplTest.java
@@ -46,7 +46,7 @@ public void setup() {
}
private String getBaseUrl() {
- return baseUrl + "/storagereport";
+ return baseUrl + "/report/storage";
}
@Test
diff --git a/durareport/.springBeans b/reporter/.springBeans
similarity index 100%
rename from durareport/.springBeans
rename to reporter/.springBeans
diff --git a/durareport/pom.xml b/reporter/pom.xml
similarity index 68%
rename from durareport/pom.xml
rename to reporter/pom.xml
index 0e1a31cb8..35d60103c 100644
--- a/durareport/pom.xml
+++ b/reporter/pom.xml
@@ -1,10 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.duracloud</groupId>
- <artifactId>durareport</artifactId>
- <packaging>war</packaging>
+ <artifactId>reporter</artifactId>
+ <packaging>jar</packaging>
<version>1.4.0-SNAPSHOT</version>
- <name>DuraCloud DuraReport</name>
+ <name>DuraCloud Reporter</name>
<url>http://localhost:8080/${artifactId}</url>
<parent>
@@ -14,31 +14,6 @@
<relativePath>../pom.xml</relativePath>
</parent>
- <build>
-
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <version>2.3.1</version>
- <executions>
- <execution>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <classifier>for-integration-test</classifier>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- </plugins>
-
- </build>
-
<dependencies>
<!-- internal projects -->
@@ -114,31 +89,6 @@
<version>${project.version}</version>
</dependency>
- <!-- for Spring -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <scope>compile</scope>
- </dependency>
-
- <!-- for Jersey -->
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-server</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey.contribs</groupId>
- <artifactId>jersey-spring</artifactId>
- </dependency>
- <dependency>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- </dependency>
-
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
diff --git a/durareport/src/main/java/org/duracloud/durareport/error/InvalidScheduleException.java b/reporter/src/main/java/org/duracloud/reporter/error/InvalidScheduleException.java
similarity index 89%
rename from durareport/src/main/java/org/duracloud/durareport/error/InvalidScheduleException.java
rename to reporter/src/main/java/org/duracloud/reporter/error/InvalidScheduleException.java
index 906ae09a7..369882589 100644
--- a/durareport/src/main/java/org/duracloud/durareport/error/InvalidScheduleException.java
+++ b/reporter/src/main/java/org/duracloud/reporter/error/InvalidScheduleException.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.error;
+package org.duracloud.reporter.error;
import org.duracloud.common.error.DuraCloudRuntimeException;
diff --git a/durareport/src/main/java/org/duracloud/durareport/error/ReportBuilderException.java b/reporter/src/main/java/org/duracloud/reporter/error/ReportBuilderException.java
similarity index 90%
rename from durareport/src/main/java/org/duracloud/durareport/error/ReportBuilderException.java
rename to reporter/src/main/java/org/duracloud/reporter/error/ReportBuilderException.java
index 59e53ce29..8574cd6ee 100644
--- a/durareport/src/main/java/org/duracloud/durareport/error/ReportBuilderException.java
+++ b/reporter/src/main/java/org/duracloud/reporter/error/ReportBuilderException.java
@@ -1,26 +1,26 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.error;
-
-import org.duracloud.common.error.DuraCloudRuntimeException;
-
-/**
- * @author: Bill Branan
- * Date: 5/16/11
- */
-public class ReportBuilderException extends DuraCloudRuntimeException {
-
- public ReportBuilderException(String message) {
- super(message);
- }
-
- public ReportBuilderException(String message, Throwable throwable) {
- super(message, throwable);
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.error;
+
+import org.duracloud.common.error.DuraCloudRuntimeException;
+
+/**
+ * @author: Bill Branan
+ * Date: 5/16/11
+ */
+public class ReportBuilderException extends DuraCloudRuntimeException {
+
+ public ReportBuilderException(String message) {
+ super(message);
+ }
+
+ public ReportBuilderException(String message, Throwable throwable) {
+ super(message, throwable);
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/error/StorageReportCancelledException.java b/reporter/src/main/java/org/duracloud/reporter/error/StorageReportCancelledException.java
similarity index 87%
rename from durareport/src/main/java/org/duracloud/durareport/error/StorageReportCancelledException.java
rename to reporter/src/main/java/org/duracloud/reporter/error/StorageReportCancelledException.java
index 9b2c47e5c..be5613029 100644
--- a/durareport/src/main/java/org/duracloud/durareport/error/StorageReportCancelledException.java
+++ b/reporter/src/main/java/org/duracloud/reporter/error/StorageReportCancelledException.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.error;
+package org.duracloud.reporter.error;
import org.duracloud.common.error.DuraCloudRuntimeException;
diff --git a/durareport/src/main/java/org/duracloud/durareport/notification/EmailNotifier.java b/reporter/src/main/java/org/duracloud/reporter/notification/EmailNotifier.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/notification/EmailNotifier.java
rename to reporter/src/main/java/org/duracloud/reporter/notification/EmailNotifier.java
index b358e039f..db5de363b 100644
--- a/durareport/src/main/java/org/duracloud/durareport/notification/EmailNotifier.java
+++ b/reporter/src/main/java/org/duracloud/reporter/notification/EmailNotifier.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.appconfig.domain.NotificationConfig;
import org.duracloud.notification.AmazonNotificationFactory;
diff --git a/durareport/src/main/java/org/duracloud/durareport/notification/NotificationManager.java b/reporter/src/main/java/org/duracloud/reporter/notification/NotificationManager.java
similarity index 95%
rename from durareport/src/main/java/org/duracloud/durareport/notification/NotificationManager.java
rename to reporter/src/main/java/org/duracloud/reporter/notification/NotificationManager.java
index ed0307506..617b45985 100644
--- a/durareport/src/main/java/org/duracloud/durareport/notification/NotificationManager.java
+++ b/reporter/src/main/java/org/duracloud/reporter/notification/NotificationManager.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.appconfig.domain.NotificationConfig;
diff --git a/durareport/src/main/java/org/duracloud/durareport/notification/NotificationType.java b/reporter/src/main/java/org/duracloud/reporter/notification/NotificationType.java
similarity index 84%
rename from durareport/src/main/java/org/duracloud/durareport/notification/NotificationType.java
rename to reporter/src/main/java/org/duracloud/reporter/notification/NotificationType.java
index 339d6adc1..4f5ade096 100644
--- a/durareport/src/main/java/org/duracloud/durareport/notification/NotificationType.java
+++ b/reporter/src/main/java/org/duracloud/reporter/notification/NotificationType.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
/**
* Defines the supported types of notification.
diff --git a/durareport/src/main/java/org/duracloud/durareport/notification/Notifier.java b/reporter/src/main/java/org/duracloud/reporter/notification/Notifier.java
similarity index 93%
rename from durareport/src/main/java/org/duracloud/durareport/notification/Notifier.java
rename to reporter/src/main/java/org/duracloud/reporter/notification/Notifier.java
index 61f31669d..c1e6895d4 100644
--- a/durareport/src/main/java/org/duracloud/durareport/notification/Notifier.java
+++ b/reporter/src/main/java/org/duracloud/reporter/notification/Notifier.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.appconfig.domain.NotificationConfig;
diff --git a/durareport/src/main/java/org/duracloud/durareport/service/ServiceNotificationMonitor.java b/reporter/src/main/java/org/duracloud/reporter/service/ServiceNotificationMonitor.java
similarity index 92%
rename from durareport/src/main/java/org/duracloud/durareport/service/ServiceNotificationMonitor.java
rename to reporter/src/main/java/org/duracloud/reporter/service/ServiceNotificationMonitor.java
index 93d9917c7..b61f6020b 100644
--- a/durareport/src/main/java/org/duracloud/durareport/service/ServiceNotificationMonitor.java
+++ b/reporter/src/main/java/org/duracloud/reporter/service/ServiceNotificationMonitor.java
@@ -5,10 +5,10 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.service;
+package org.duracloud.reporter.service;
-import org.duracloud.durareport.notification.NotificationManager;
-import org.duracloud.durareport.notification.NotificationType;
+import org.duracloud.reporter.notification.NotificationManager;
+import org.duracloud.reporter.notification.NotificationType;
import org.duracloud.security.DuracloudUserDetailsService;
import org.duracloud.security.domain.SecurityUserBean;
import org.duracloud.serviceconfig.ServiceSummary;
diff --git a/durareport/src/main/java/org/duracloud/durareport/service/ServiceReportBuilder.java b/reporter/src/main/java/org/duracloud/reporter/service/ServiceReportBuilder.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/service/ServiceReportBuilder.java
rename to reporter/src/main/java/org/duracloud/reporter/service/ServiceReportBuilder.java
index 351655670..d1e642615 100644
--- a/durareport/src/main/java/org/duracloud/durareport/service/ServiceReportBuilder.java
+++ b/reporter/src/main/java/org/duracloud/reporter/service/ServiceReportBuilder.java
@@ -5,11 +5,11 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.service;
+package org.duracloud.reporter.service;
import org.duracloud.common.util.IOUtil;
-import org.duracloud.durareport.error.ReportBuilderException;
-import org.duracloud.durareport.storage.StorageReportScheduler;
+import org.duracloud.reporter.error.ReportBuilderException;
+import org.duracloud.reporter.storage.StorageReportScheduler;
import org.duracloud.serviceconfig.ServiceReportList;
import org.duracloud.serviceconfig.ServiceSummariesDocument;
import org.duracloud.serviceconfig.ServiceSummary;
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportBuilder.java b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportBuilder.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/storage/StorageReportBuilder.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/StorageReportBuilder.java
index 806081a85..f084f9d2d 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportBuilder.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportBuilder.java
@@ -1,289 +1,289 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage;
-
-import org.duracloud.client.ContentStore;
-import org.duracloud.client.ContentStoreManager;
-import org.duracloud.common.error.DuraCloudCheckedException;
-import org.duracloud.durareport.error.ReportBuilderException;
-import org.duracloud.durareport.error.StorageReportCancelledException;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
-import org.duracloud.error.ContentStoreException;
-import org.duracloud.reportdata.storage.StorageReport;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Builder to be run in a thread to generate metrics reports.
- *
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class StorageReportBuilder implements Runnable {
-
- public static enum Status {CREATED, RUNNING, COMPLETE, CANCELLED, ERROR};
- private final Logger log =
- LoggerFactory.getLogger(StorageReportBuilder.class);
- public static final int maxRetries = 20;
-
- private ContentStoreManager storeMgr = null;
- private StorageReportHandler reportHandler;
-
- private Status status;
- private String error;
- private long startTime;
- private long stopTime;
- private long elapsedTime;
- private boolean run;
-
- private DuraStoreMetricsCollector durastoreMetrics;
-
- public StorageReportBuilder(ContentStoreManager storeMgr,
- StorageReportHandler reportHandler) {
- this.storeMgr = storeMgr;
- this.reportHandler = reportHandler;
- this.status = Status.CREATED;
- this.error = null;
- this.startTime = 0;
- this.stopTime = 0;
- this.elapsedTime = 0;
-
- try {
- StorageReport lastReport = reportHandler.getLatestStorageReport();
- if(null != lastReport) {
- this.stopTime = lastReport.getCompletionTime();
- this.elapsedTime = lastReport.getElapsedTime();
- }
- } catch(Exception e) {
- log.warn("Unable to retrieve latest storage report due to: " +
- e.getMessage());
- }
- }
-
- @Override
- public void run() {
- run = true;
- error = null;
- startTime = System.currentTimeMillis();
- log.info("Storage Report starting at time: " + startTime);
- status = Status.RUNNING;
- try {
- collectStorageMetrics();
- stopTime = System.currentTimeMillis();
- elapsedTime = stopTime - startTime;
- reportHandler.storeReport(durastoreMetrics,
- stopTime,
- elapsedTime);
- status = Status.COMPLETE;
- log.info("Storage Report completed at time: " + stopTime);
- } catch (StorageReportCancelledException e) {
- stopTime = System.currentTimeMillis();
- log.warn("Storage Report cancelled at: " + stopTime);
- status = Status.CANCELLED;
- } catch(ReportBuilderException e) {
- stopTime = System.currentTimeMillis();
- String errMsg = "Unable to complete metrics collection due to: " +
- e.getMessage();
- error = errMsg;
- log.error(errMsg);
- reportHandler.addToErrorLog(errMsg);
- status = Status.ERROR;
- }
- }
-
- public void cancelReport() {
- new DuraCloudCheckedException(); // loads this exception type
- log.info("Cancelling Storage Report");
- run = false;
- }
-
- private void collectStorageMetrics() {
- durastoreMetrics = new DuraStoreMetricsCollector();
-
- Map<String, ContentStore> contentStores = retryGetContentStores();
- for(ContentStore contentStore : contentStores.values()) {
- checkRun();
- String storeId = contentStore.getStoreId();
- String storeType = contentStore.getStorageProviderType();
- for(String spaceId : retryGetSpaces(contentStore)) {
- checkRun();
- Iterator<String> contentIds =
- retryGetSpaceContents(contentStore, spaceId);
- while(contentIds.hasNext()) {
- checkRun();
- String contentId = contentIds.next();
- Map<String, String> contentProperties =
- retryGetContentProperties(contentStore,
- spaceId,
- contentId);
- updateMetrics(contentProperties,
- storeId,
- storeType,
- spaceId);
- }
- }
- }
- }
-
- private void updateMetrics(Map<String, String> contentProperties,
- String storeId,
- String storeType,
- String spaceId) {
- if(null != contentProperties) {
- String mimetype =
- contentProperties.get(ContentStore.CONTENT_MIMETYPE);
- long size =
- convert(contentProperties.get(ContentStore.CONTENT_SIZE));
- durastoreMetrics.update(storeId, storeType, spaceId, mimetype, size);
- }
- }
-
- private Map<String, ContentStore> retryGetContentStores() {
- for(int i=0; i<maxRetries; i++) {
- checkRun();
- try {
- return storeMgr.getContentStores();
- } catch (ContentStoreException e) {
- log.warn("Exception attempting to retrieve content " +
- "stores list: " + e.getMessage());
- wait(i);
- }
- }
- throw new ReportBuilderException("Exceeded retries attempting to " +
- "retrieve content stores list");
- }
-
- private List<String> retryGetSpaces(ContentStore contentStore) {
- for(int i=0; i<maxRetries; i++) {
- checkRun();
- try {
- return contentStore.getSpaces();
- } catch (ContentStoreException e) {
- String store = getStoreInfo(contentStore);
- log.warn("Exception attempting to retrieve spaces list for " +
- "store: " + store + " due to: " + e.getMessage());
- wait(i);
- }
- }
- throw new ReportBuilderException("Exceeded retries attempting to " +
- "retrieve spaces list");
- }
-
- private Iterator<String> retryGetSpaceContents(ContentStore contentStore,
- String spaceId) {
- for(int i=0; i<maxRetries; i++) {
- checkRun();
- try {
- return contentStore.getSpaceContents(spaceId);
- } catch (ContentStoreException e) {
- String store = getStoreInfo(contentStore);
- log.warn("Exception attempting to retrieve space contents " +
- "list (for " + spaceId + " in store " + store +
- "): " + e.getMessage());
- wait(i);
- }
- }
- throw new ReportBuilderException("Exceeded retries attempting to " +
- "retrieve space contents list " +
- "(for " + spaceId + ")");
- }
-
- private Map<String, String> retryGetContentProperties(ContentStore contentStore,
- String spaceId,
- String contentId) {
- for(int i=0; i<maxRetries; i++) {
- checkRun();
- try {
- return contentStore.getContentProperties(spaceId, contentId);
- } catch (ContentStoreException e) {
- String store = getStoreInfo(contentStore);
- log.warn("Exception attempting to retrieve content properties " +
- "(for " + spaceId + ":" + contentId + " in store " +
- store + "): " + e.getMessage());
- wait(i);
- }
- }
- log.error("Exceeded retries attempting to retrieve content properties " +
- "(for " + spaceId + ":" + contentId + "). Skipping item.");
- return null;
- }
-
- private String getStoreInfo(ContentStore contentStore) {
- return contentStore.getStoreId() + "(" +
- contentStore.getStorageProviderType() + ")";
- }
-
- private long convert(String sizeStr) {
- try {
- return Long.valueOf(sizeStr);
- } catch(NumberFormatException e) {
- return 0;
- }
- }
-
- private void wait(int index) {
- checkRun();
- try {
- Thread.sleep(1000 * index);
- } catch(InterruptedException e) {
- }
- }
-
- private void checkRun() {
- if(!run) {
- throw new StorageReportCancelledException();
- }
- }
-
- /**
- * Gets the current status of the report builder
- */
- public Status getStatus() {
- return status;
- }
-
- /**
- * Gets the text of the last error which occurred (if any)
- */
- public String getError() {
- return error;
- }
-
- /**
- * Gets the current count for the in-process report builder run
- */
- public long getCurrentCount() {
- return durastoreMetrics.getTotalItems();
- }
-
- /**
- * Gets the stop time (in millis) of the most recent report builder run
- */
- public long getStopTime() {
- return stopTime;
- }
-
- /**
- * Gets the starting time (in millis) of the most recent report builder run
- */
- public long getStartTime() {
- return startTime;
- }
-
- /**
- * Gets the time (in millis) required to complete the most recent
- * report builder run
- */
- public long getElapsedTime() {
- return elapsedTime;
- }
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage;
+
+import org.duracloud.client.ContentStore;
+import org.duracloud.client.ContentStoreManager;
+import org.duracloud.common.error.DuraCloudCheckedException;
+import org.duracloud.reporter.error.ReportBuilderException;
+import org.duracloud.reporter.error.StorageReportCancelledException;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.error.ContentStoreException;
+import org.duracloud.reportdata.storage.StorageReport;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Builder to be run in a thread to generate metrics reports.
+ *
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class StorageReportBuilder implements Runnable {
+
+ public static enum Status {CREATED, RUNNING, COMPLETE, CANCELLED, ERROR};
+ private final Logger log =
+ LoggerFactory.getLogger(StorageReportBuilder.class);
+ public static final int maxRetries = 20;
+
+ private ContentStoreManager storeMgr = null;
+ private StorageReportHandler reportHandler;
+
+ private Status status;
+ private String error;
+ private long startTime;
+ private long stopTime;
+ private long elapsedTime;
+ private boolean run;
+
+ private DuraStoreMetricsCollector durastoreMetrics;
+
+ public StorageReportBuilder(ContentStoreManager storeMgr,
+ StorageReportHandler reportHandler) {
+ this.storeMgr = storeMgr;
+ this.reportHandler = reportHandler;
+ this.status = Status.CREATED;
+ this.error = null;
+ this.startTime = 0;
+ this.stopTime = 0;
+ this.elapsedTime = 0;
+
+ try {
+ StorageReport lastReport = reportHandler.getLatestStorageReport();
+ if(null != lastReport) {
+ this.stopTime = lastReport.getCompletionTime();
+ this.elapsedTime = lastReport.getElapsedTime();
+ }
+ } catch(Exception e) {
+ log.warn("Unable to retrieve latest storage report due to: " +
+ e.getMessage());
+ }
+ }
+
+ @Override
+ public void run() {
+ run = true;
+ error = null;
+ startTime = System.currentTimeMillis();
+ log.info("Storage Report starting at time: " + startTime);
+ status = Status.RUNNING;
+ try {
+ collectStorageMetrics();
+ stopTime = System.currentTimeMillis();
+ elapsedTime = stopTime - startTime;
+ reportHandler.storeReport(durastoreMetrics,
+ stopTime,
+ elapsedTime);
+ status = Status.COMPLETE;
+ log.info("Storage Report completed at time: " + stopTime);
+ } catch (StorageReportCancelledException e) {
+ stopTime = System.currentTimeMillis();
+ log.warn("Storage Report cancelled at: " + stopTime);
+ status = Status.CANCELLED;
+ } catch(ReportBuilderException e) {
+ stopTime = System.currentTimeMillis();
+ String errMsg = "Unable to complete metrics collection due to: " +
+ e.getMessage();
+ error = errMsg;
+ log.error(errMsg);
+ reportHandler.addToErrorLog(errMsg);
+ status = Status.ERROR;
+ }
+ }
+
+ public void cancelReport() {
+ new DuraCloudCheckedException(); // loads this exception type
+ log.info("Cancelling Storage Report");
+ run = false;
+ }
+
+ private void collectStorageMetrics() {
+ durastoreMetrics = new DuraStoreMetricsCollector();
+
+ Map<String, ContentStore> contentStores = retryGetContentStores();
+ for(ContentStore contentStore : contentStores.values()) {
+ checkRun();
+ String storeId = contentStore.getStoreId();
+ String storeType = contentStore.getStorageProviderType();
+ for(String spaceId : retryGetSpaces(contentStore)) {
+ checkRun();
+ Iterator<String> contentIds =
+ retryGetSpaceContents(contentStore, spaceId);
+ while(contentIds.hasNext()) {
+ checkRun();
+ String contentId = contentIds.next();
+ Map<String, String> contentProperties =
+ retryGetContentProperties(contentStore,
+ spaceId,
+ contentId);
+ updateMetrics(contentProperties,
+ storeId,
+ storeType,
+ spaceId);
+ }
+ }
+ }
+ }
+
+ private void updateMetrics(Map<String, String> contentProperties,
+ String storeId,
+ String storeType,
+ String spaceId) {
+ if(null != contentProperties) {
+ String mimetype =
+ contentProperties.get(ContentStore.CONTENT_MIMETYPE);
+ long size =
+ convert(contentProperties.get(ContentStore.CONTENT_SIZE));
+ durastoreMetrics.update(storeId, storeType, spaceId, mimetype, size);
+ }
+ }
+
+ private Map<String, ContentStore> retryGetContentStores() {
+ for(int i=0; i<maxRetries; i++) {
+ checkRun();
+ try {
+ return storeMgr.getContentStores();
+ } catch (ContentStoreException e) {
+ log.warn("Exception attempting to retrieve content " +
+ "stores list: " + e.getMessage());
+ wait(i);
+ }
+ }
+ throw new ReportBuilderException("Exceeded retries attempting to " +
+ "retrieve content stores list");
+ }
+
+ private List<String> retryGetSpaces(ContentStore contentStore) {
+ for(int i=0; i<maxRetries; i++) {
+ checkRun();
+ try {
+ return contentStore.getSpaces();
+ } catch (ContentStoreException e) {
+ String store = getStoreInfo(contentStore);
+ log.warn("Exception attempting to retrieve spaces list for " +
+ "store: " + store + " due to: " + e.getMessage());
+ wait(i);
+ }
+ }
+ throw new ReportBuilderException("Exceeded retries attempting to " +
+ "retrieve spaces list");
+ }
+
+ private Iterator<String> retryGetSpaceContents(ContentStore contentStore,
+ String spaceId) {
+ for(int i=0; i<maxRetries; i++) {
+ checkRun();
+ try {
+ return contentStore.getSpaceContents(spaceId);
+ } catch (ContentStoreException e) {
+ String store = getStoreInfo(contentStore);
+ log.warn("Exception attempting to retrieve space contents " +
+ "list (for " + spaceId + " in store " + store +
+ "): " + e.getMessage());
+ wait(i);
+ }
+ }
+ throw new ReportBuilderException("Exceeded retries attempting to " +
+ "retrieve space contents list " +
+ "(for " + spaceId + ")");
+ }
+
+ private Map<String, String> retryGetContentProperties(ContentStore contentStore,
+ String spaceId,
+ String contentId) {
+ for(int i=0; i<maxRetries; i++) {
+ checkRun();
+ try {
+ return contentStore.getContentProperties(spaceId, contentId);
+ } catch (ContentStoreException e) {
+ String store = getStoreInfo(contentStore);
+ log.warn("Exception attempting to retrieve content properties " +
+ "(for " + spaceId + ":" + contentId + " in store " +
+ store + "): " + e.getMessage());
+ wait(i);
+ }
+ }
+ log.error("Exceeded retries attempting to retrieve content properties " +
+ "(for " + spaceId + ":" + contentId + "). Skipping item.");
+ return null;
+ }
+
+ private String getStoreInfo(ContentStore contentStore) {
+ return contentStore.getStoreId() + "(" +
+ contentStore.getStorageProviderType() + ")";
+ }
+
+ private long convert(String sizeStr) {
+ try {
+ return Long.valueOf(sizeStr);
+ } catch(NumberFormatException e) {
+ return 0;
+ }
+ }
+
+ private void wait(int index) {
+ checkRun();
+ try {
+ Thread.sleep(1000 * index);
+ } catch(InterruptedException e) {
+ }
+ }
+
+ private void checkRun() {
+ if(!run) {
+ throw new StorageReportCancelledException();
+ }
+ }
+
+ /**
+ * Gets the current status of the report builder
+ */
+ public Status getStatus() {
+ return status;
+ }
+
+ /**
+ * Gets the text of the last error which occurred (if any)
+ */
+ public String getError() {
+ return error;
+ }
+
+ /**
+ * Gets the current count for the in-process report builder run
+ */
+ public long getCurrentCount() {
+ return durastoreMetrics.getTotalItems();
+ }
+
+ /**
+ * Gets the stop time (in millis) of the most recent report builder run
+ */
+ public long getStopTime() {
+ return stopTime;
+ }
+
+ /**
+ * Gets the starting time (in millis) of the most recent report builder run
+ */
+ public long getStartTime() {
+ return startTime;
+ }
+
+ /**
+ * Gets the time (in millis) required to complete the most recent
+ * report builder run
+ */
+ public long getElapsedTime() {
+ return elapsedTime;
+ }
}
\ No newline at end of file
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportConverter.java b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportConverter.java
similarity index 88%
rename from durareport/src/main/java/org/duracloud/durareport/storage/StorageReportConverter.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/StorageReportConverter.java
index 695f72286..ffea055a2 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportConverter.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportConverter.java
@@ -5,12 +5,12 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
-import org.duracloud.durareport.storage.metrics.MimetypeMetricsCollector;
-import org.duracloud.durareport.storage.metrics.SpaceMetricsCollector;
-import org.duracloud.durareport.storage.metrics.StorageProviderMetricsCollector;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.reporter.storage.metrics.MimetypeMetricsCollector;
+import org.duracloud.reporter.storage.metrics.SpaceMetricsCollector;
+import org.duracloud.reporter.storage.metrics.StorageProviderMetricsCollector;
import org.duracloud.reportdata.storage.StorageReport;
import org.duracloud.reportdata.storage.metrics.MimetypeMetrics;
import org.duracloud.reportdata.storage.metrics.SpaceMetrics;
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportHandler.java b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportHandler.java
similarity index 95%
rename from durareport/src/main/java/org/duracloud/durareport/storage/StorageReportHandler.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/StorageReportHandler.java
index 1b5e87310..0f7c31a38 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportHandler.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportHandler.java
@@ -1,327 +1,327 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage;
-
-import org.apache.commons.io.IOUtils;
-import org.duracloud.client.ContentStore;
-import org.duracloud.client.ContentStoreManager;
-import org.duracloud.common.error.DuraCloudRuntimeException;
-import org.duracloud.common.util.ChecksumUtil;
-import org.duracloud.common.util.DateUtil;
-import org.duracloud.domain.Content;
-import org.duracloud.durareport.error.ReportBuilderException;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
-import org.duracloud.error.ContentStoreException;
-import org.duracloud.error.NotFoundException;
-import org.duracloud.reportdata.storage.StorageReport;
-import org.duracloud.reportdata.storage.StorageReportList;
-import org.duracloud.reportdata.storage.serialize.StorageReportSerializer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.ws.rs.core.MediaType;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.SequenceInputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.Map;
-
-/**
- * Handles the storage and retrieval of storage reports.
- *
- * @author: Bill Branan
- * Date: 5/13/11
- */
-public class StorageReportHandler {
-
- private final Logger log =
- LoggerFactory.getLogger(StorageReportHandler.class);
-
- private static final String REPORT_FILE_NAME_SUFFIX = ".xml";
- public static final String COMPLETION_TIME_META = "completion-time";
- public static final String ELAPSED_TIME_META = "elapsed-time";
- public static final int maxRetries = 8;
-
- protected String storageSpace;
- private ContentStore primaryStore = null;
- private String reportFileNamePrefix;
- private String reportErrorLogFileName;
-
- public StorageReportHandler(ContentStoreManager storeMgr,
- String storageSpace,
- String reportFileNamePrefix,
- String reportErrorLogFileName) {
- this.storageSpace = storageSpace;
- this.reportFileNamePrefix = reportFileNamePrefix;
- this.reportErrorLogFileName = reportErrorLogFileName;
- try {
- this.primaryStore = storeMgr.getPrimaryContentStore();
- try {
- primaryStore.getSpaceProperties(storageSpace);
- } catch(NotFoundException e) {
- primaryStore.createSpace(storageSpace, null);
- }
- } catch(ContentStoreException e) {
- throw new DuraCloudRuntimeException("Error checking metrics " +
- "storage space: " +
- e.getMessage());
- }
- }
-
- /**
- * Returns a specific storage report stream or null if the report does
- * not exist.
- *
- * @param reportId content ID of the report to retrieve
- * @return InputStream containing report
- */
- public InputStream getStorageReportStream(String reportId)
- throws ContentStoreException {
- try {
- return primaryStore.getContent(storageSpace, reportId).getStream();
- } catch(NotFoundException e) {
- return null;
- }
- }
-
- /**
- * Returns a specific storage report or null if the report does not exist.
- *
- * @param reportId content ID of the report to retrieve
- * @return StorageReport
- */
- public StorageReport getStorageReport(String reportId)
- throws ContentStoreException {
- try {
- Content content = primaryStore.getContent(storageSpace, reportId);
- return deserializeStorageReport(content);
- } catch(NotFoundException e) {
- return null;
- }
- }
-
- private StorageReport deserializeStorageReport(Content content) {
- StorageReportSerializer serializer = new StorageReportSerializer();
- return serializer.deserialize(content.getStream());
- }
-
- /**
- * Returns the latest storage report stream or null if no reports exist
- */
- public InputStream getLatestStorageReportStream()
- throws ContentStoreException {
- Content latestContent = getLatestStorageReportContent();
- if(null != latestContent) {
- return latestContent.getStream();
- } else {
- return null;
- }
- }
-
- /**
- * Returns the latest storage report or null if no reports exist
- */
- public StorageReport getLatestStorageReport() throws ContentStoreException {
- Content latestContent = getLatestStorageReportContent();
- if(null != latestContent) {
- return deserializeStorageReport(latestContent);
- } else {
- return null;
- }
- }
-
- private Content getLatestStorageReportContent()
- throws ContentStoreException {
- LinkedList<String> reportList = getSortedReportList();
- if(reportList.size() > 0) {
- String latestContentId = reportList.getFirst();
- Content latestContent =
- primaryStore.getContent(storageSpace, latestContentId);
- return latestContent;
- } else {
- return null;
- }
- }
-
- /*
- * Retrieves a list of all report lists (limited to a maximum of 5000),
- * sorted by name in descending order (i.e. the latest report will be first)
- */
- private LinkedList<String> getSortedReportList()
- throws ContentStoreException {
- Iterator<String> reports =
- primaryStore.getSpaceContents(storageSpace, reportFileNamePrefix);
-
- // Read the list of storage reports into a list, note that there is
- // the assumption here that there will not be a very large number of
- // these files.
- LinkedList<String> reportList = new LinkedList<String>();
- while(reports.hasNext() && reportList.size() < 5000) {
- reportList.add(reports.next());
- }
- if(reportList.size() > 0) {
- Collections.sort(reportList);
- Collections.reverse(reportList);
- }
- return reportList;
- }
-
- /**
- * Retrieve a sorted list of all storage reports in XML format. Sorting
- * is by name in descending order (i.e. the latest report will be first).
- *
- * @return list of storage reports
- * @throws ContentStoreException
- */
- public StorageReportList getStorageReportList() throws ContentStoreException {
- return new StorageReportList(getSortedReportList());
- }
-
- /**
- * Stores a storage report in the primary storage provider,
- * returns the content ID of the new item.
- *
- * @param metrics storage report
- * @param completionTime time report completed (in millis)
- * @param elapsedTime millis required to complete the report
- * @return contentId of the newly stored report
- */
- public String storeReport(DuraStoreMetricsCollector metrics,
- long completionTime,
- long elapsedTime) {
- String contentId = buildContentId(completionTime);
-
- StorageReportConverter converter = new StorageReportConverter();
- StorageReport report = converter.createStorageReport(contentId,
- metrics,
- completionTime,
- elapsedTime);
-
- StorageReportSerializer serializer = new StorageReportSerializer();
- String xml = serializer.serialize(report);
- byte[] metricsBytes = getXmlBytes(xml);
-
- log.info("Storing Storage Report with ID: " + contentId);
- for(int i=0; i<maxRetries; i++) {
- try {
- primaryStore.addContent(storageSpace,
- contentId,
- new ByteArrayInputStream(metricsBytes),
- metricsBytes.length,
- MediaType.APPLICATION_XML,
- getMetricsChecksum(xml),
- null);
- return contentId;
- } catch (ContentStoreException e) {
- log.warn("Exception attempting to store storage report: " +
- e.getMessage());
- wait(i);
- }
- }
- throw new ReportBuilderException("Exceeded retries attempting to " +
- "store storage report");
- }
-
- private String buildContentId(long time) {
- String date = DateUtil.convertToString(time);
- return reportFileNamePrefix + date + REPORT_FILE_NAME_SUFFIX;
- }
-
- private byte[] getXmlBytes(String xml) {
- try {
- return xml.getBytes("UTF-8");
- } catch(UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
- }
-
- private String getMetricsChecksum(String xml) {
- ChecksumUtil util = new ChecksumUtil(ChecksumUtil.Algorithm.MD5);
- return util.generateChecksum(xml);
- }
-
- public void addToErrorLog(String errMsg) {
- InputStream existingLog = null;
- long existingLogSize = 0;
- try {
- Content errorLogContent =
- primaryStore.getContent(storageSpace, reportErrorLogFileName);
- if(null != errorLogContent) {
- existingLog = errorLogContent.getStream();
- existingLogSize = getExistingLogSize(errorLogContent);
- }
- } catch(ContentStoreException e) {
- // Could not get error log, likely because it does not yet exist
- }
-
- String logMsg = createLogMsg(errMsg);
- InputStream newMsg = createLogMsgStream(logMsg);
- InputStream newLog;
- if(null != existingLog) {
- newLog = new SequenceInputStream(newMsg, existingLog);
- } else {
- newLog = newMsg;
- }
-
- for(int i=0; i<maxRetries; i++) {
- try {
- primaryStore.addContent(storageSpace,
- reportErrorLogFileName,
- newLog,
- existingLogSize + logMsg.length(),
- MediaType.TEXT_PLAIN,
- null,
- null);
- return;
- } catch(ContentStoreException e) {
- log.warn("Exception attempting to store error log: " +
- e.getMessage());
- wait(i);
- }
- }
- log.error("Unable to store error log file!");
- }
-
- private String createLogMsg(String msg) {
- return DateUtil.now() + " " + msg + "\n";
- }
-
- private InputStream createLogMsgStream(String logMsg) {
- try {
- return IOUtils.toInputStream(logMsg, "UTF-8");
- } catch(IOException e) {
- throw new RuntimeException(e.getMessage(), e);
- }
- }
-
- private long getExistingLogSize(Content logContent) {
- Map<String, String> properties = logContent.getProperties();
- if(null != properties) {
- String logSize = properties.get(ContentStore.CONTENT_SIZE);
- if(null != logSize) {
- try {
- return Long.valueOf(logSize);
- } catch(NumberFormatException e) {
- }
- }
- }
- return 0;
- }
-
- private void wait(int index) {
- try {
- Thread.sleep(1000 * index);
- } catch(InterruptedException e) {
- }
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage;
+
+import org.apache.commons.io.IOUtils;
+import org.duracloud.client.ContentStore;
+import org.duracloud.client.ContentStoreManager;
+import org.duracloud.common.error.DuraCloudRuntimeException;
+import org.duracloud.common.util.ChecksumUtil;
+import org.duracloud.common.util.DateUtil;
+import org.duracloud.domain.Content;
+import org.duracloud.reporter.error.ReportBuilderException;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.error.ContentStoreException;
+import org.duracloud.error.NotFoundException;
+import org.duracloud.reportdata.storage.StorageReport;
+import org.duracloud.reportdata.storage.StorageReportList;
+import org.duracloud.reportdata.storage.serialize.StorageReportSerializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.core.MediaType;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.SequenceInputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+
+/**
+ * Handles the storage and retrieval of storage reports.
+ *
+ * @author: Bill Branan
+ * Date: 5/13/11
+ */
+public class StorageReportHandler {
+
+ private final Logger log =
+ LoggerFactory.getLogger(StorageReportHandler.class);
+
+ private static final String REPORT_FILE_NAME_SUFFIX = ".xml";
+ public static final String COMPLETION_TIME_META = "completion-time";
+ public static final String ELAPSED_TIME_META = "elapsed-time";
+ public static final int maxRetries = 8;
+
+ protected String storageSpace;
+ private ContentStore primaryStore = null;
+ private String reportFileNamePrefix;
+ private String reportErrorLogFileName;
+
+ public StorageReportHandler(ContentStoreManager storeMgr,
+ String storageSpace,
+ String reportFileNamePrefix,
+ String reportErrorLogFileName) {
+ this.storageSpace = storageSpace;
+ this.reportFileNamePrefix = reportFileNamePrefix;
+ this.reportErrorLogFileName = reportErrorLogFileName;
+ try {
+ this.primaryStore = storeMgr.getPrimaryContentStore();
+ try {
+ primaryStore.getSpaceProperties(storageSpace);
+ } catch(NotFoundException e) {
+ primaryStore.createSpace(storageSpace, null);
+ }
+ } catch(ContentStoreException e) {
+ throw new DuraCloudRuntimeException("Error checking metrics " +
+ "storage space: " +
+ e.getMessage());
+ }
+ }
+
+ /**
+ * Returns a specific storage report stream or null if the report does
+ * not exist.
+ *
+ * @param reportId content ID of the report to retrieve
+ * @return InputStream containing report
+ */
+ public InputStream getStorageReportStream(String reportId)
+ throws ContentStoreException {
+ try {
+ return primaryStore.getContent(storageSpace, reportId).getStream();
+ } catch(NotFoundException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Returns a specific storage report or null if the report does not exist.
+ *
+ * @param reportId content ID of the report to retrieve
+ * @return StorageReport
+ */
+ public StorageReport getStorageReport(String reportId)
+ throws ContentStoreException {
+ try {
+ Content content = primaryStore.getContent(storageSpace, reportId);
+ return deserializeStorageReport(content);
+ } catch(NotFoundException e) {
+ return null;
+ }
+ }
+
+ private StorageReport deserializeStorageReport(Content content) {
+ StorageReportSerializer serializer = new StorageReportSerializer();
+ return serializer.deserialize(content.getStream());
+ }
+
+ /**
+ * Returns the latest storage report stream or null if no reports exist
+ */
+ public InputStream getLatestStorageReportStream()
+ throws ContentStoreException {
+ Content latestContent = getLatestStorageReportContent();
+ if(null != latestContent) {
+ return latestContent.getStream();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the latest storage report or null if no reports exist
+ */
+ public StorageReport getLatestStorageReport() throws ContentStoreException {
+ Content latestContent = getLatestStorageReportContent();
+ if(null != latestContent) {
+ return deserializeStorageReport(latestContent);
+ } else {
+ return null;
+ }
+ }
+
+ private Content getLatestStorageReportContent()
+ throws ContentStoreException {
+ LinkedList<String> reportList = getSortedReportList();
+ if(reportList.size() > 0) {
+ String latestContentId = reportList.getFirst();
+ Content latestContent =
+ primaryStore.getContent(storageSpace, latestContentId);
+ return latestContent;
+ } else {
+ return null;
+ }
+ }
+
+ /*
+ * Retrieves a list of all report lists (limited to a maximum of 5000),
+ * sorted by name in descending order (i.e. the latest report will be first)
+ */
+ private LinkedList<String> getSortedReportList()
+ throws ContentStoreException {
+ Iterator<String> reports =
+ primaryStore.getSpaceContents(storageSpace, reportFileNamePrefix);
+
+ // Read the list of storage reports into a list, note that there is
+ // the assumption here that there will not be a very large number of
+ // these files.
+ LinkedList<String> reportList = new LinkedList<String>();
+ while(reports.hasNext() && reportList.size() < 5000) {
+ reportList.add(reports.next());
+ }
+ if(reportList.size() > 0) {
+ Collections.sort(reportList);
+ Collections.reverse(reportList);
+ }
+ return reportList;
+ }
+
+ /**
+ * Retrieve a sorted list of all storage reports in XML format. Sorting
+ * is by name in descending order (i.e. the latest report will be first).
+ *
+ * @return list of storage reports
+ * @throws ContentStoreException
+ */
+ public StorageReportList getStorageReportList() throws ContentStoreException {
+ return new StorageReportList(getSortedReportList());
+ }
+
+ /**
+ * Stores a storage report in the primary storage provider,
+ * returns the content ID of the new item.
+ *
+ * @param metrics storage report
+ * @param completionTime time report completed (in millis)
+ * @param elapsedTime millis required to complete the report
+ * @return contentId of the newly stored report
+ */
+ public String storeReport(DuraStoreMetricsCollector metrics,
+ long completionTime,
+ long elapsedTime) {
+ String contentId = buildContentId(completionTime);
+
+ StorageReportConverter converter = new StorageReportConverter();
+ StorageReport report = converter.createStorageReport(contentId,
+ metrics,
+ completionTime,
+ elapsedTime);
+
+ StorageReportSerializer serializer = new StorageReportSerializer();
+ String xml = serializer.serialize(report);
+ byte[] metricsBytes = getXmlBytes(xml);
+
+ log.info("Storing Storage Report with ID: " + contentId);
+ for(int i=0; i<maxRetries; i++) {
+ try {
+ primaryStore.addContent(storageSpace,
+ contentId,
+ new ByteArrayInputStream(metricsBytes),
+ metricsBytes.length,
+ MediaType.APPLICATION_XML,
+ getMetricsChecksum(xml),
+ null);
+ return contentId;
+ } catch (ContentStoreException e) {
+ log.warn("Exception attempting to store storage report: " +
+ e.getMessage());
+ wait(i);
+ }
+ }
+ throw new ReportBuilderException("Exceeded retries attempting to " +
+ "store storage report");
+ }
+
+ private String buildContentId(long time) {
+ String date = DateUtil.convertToString(time);
+ return reportFileNamePrefix + date + REPORT_FILE_NAME_SUFFIX;
+ }
+
+ private byte[] getXmlBytes(String xml) {
+ try {
+ return xml.getBytes("UTF-8");
+ } catch(UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private String getMetricsChecksum(String xml) {
+ ChecksumUtil util = new ChecksumUtil(ChecksumUtil.Algorithm.MD5);
+ return util.generateChecksum(xml);
+ }
+
+ public void addToErrorLog(String errMsg) {
+ InputStream existingLog = null;
+ long existingLogSize = 0;
+ try {
+ Content errorLogContent =
+ primaryStore.getContent(storageSpace, reportErrorLogFileName);
+ if(null != errorLogContent) {
+ existingLog = errorLogContent.getStream();
+ existingLogSize = getExistingLogSize(errorLogContent);
+ }
+ } catch(ContentStoreException e) {
+ // Could not get error log, likely because it does not yet exist
+ }
+
+ String logMsg = createLogMsg(errMsg);
+ InputStream newMsg = createLogMsgStream(logMsg);
+ InputStream newLog;
+ if(null != existingLog) {
+ newLog = new SequenceInputStream(newMsg, existingLog);
+ } else {
+ newLog = newMsg;
+ }
+
+ for(int i=0; i<maxRetries; i++) {
+ try {
+ primaryStore.addContent(storageSpace,
+ reportErrorLogFileName,
+ newLog,
+ existingLogSize + logMsg.length(),
+ MediaType.TEXT_PLAIN,
+ null,
+ null);
+ return;
+ } catch(ContentStoreException e) {
+ log.warn("Exception attempting to store error log: " +
+ e.getMessage());
+ wait(i);
+ }
+ }
+ log.error("Unable to store error log file!");
+ }
+
+ private String createLogMsg(String msg) {
+ return DateUtil.now() + " " + msg + "\n";
+ }
+
+ private InputStream createLogMsgStream(String logMsg) {
+ try {
+ return IOUtils.toInputStream(logMsg, "UTF-8");
+ } catch(IOException e) {
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ }
+
+ private long getExistingLogSize(Content logContent) {
+ Map<String, String> properties = logContent.getProperties();
+ if(null != properties) {
+ String logSize = properties.get(ContentStore.CONTENT_SIZE);
+ if(null != logSize) {
+ try {
+ return Long.valueOf(logSize);
+ } catch(NumberFormatException e) {
+ }
+ }
+ }
+ return 0;
+ }
+
+ private void wait(int index) {
+ try {
+ Thread.sleep(1000 * index);
+ } catch(InterruptedException e) {
+ }
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportScheduler.java b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportScheduler.java
similarity index 95%
rename from durareport/src/main/java/org/duracloud/durareport/storage/StorageReportScheduler.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/StorageReportScheduler.java
index df855face..42e58e3c7 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/StorageReportScheduler.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/StorageReportScheduler.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/DuraStoreMetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/DuraStoreMetricsCollector.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/DuraStoreMetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/DuraStoreMetricsCollector.java
index 4d1015d85..dd2440a17 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/DuraStoreMetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/DuraStoreMetricsCollector.java
@@ -1,56 +1,56 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Top level metrics storage data structure for DuraStore. Contains all
- * metrics information for all storage providers.
- *
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class DuraStoreMetricsCollector extends MetricsCollector {
-
- private Map<String, StorageProviderMetricsCollector> storageProviderMetrics;
-
- public DuraStoreMetricsCollector() {
- super();
- this.storageProviderMetrics =
- new HashMap<String, StorageProviderMetricsCollector>();
- }
-
- @Override
- public void update(String mimetype, long size) {
- String error = "Use update(String, String, String, long)";
- throw new UnsupportedOperationException(error);
- }
-
- public void update(String storageProviderId,
- String storageProviderType,
- String spaceId,
- String mimetype,
- long size) {
- super.update(mimetype, size);
-
- StorageProviderMetricsCollector providerMet =
- storageProviderMetrics.get(storageProviderId);
- if(null == providerMet) {
- providerMet = new StorageProviderMetricsCollector(storageProviderId,
- storageProviderType);
- storageProviderMetrics.put(storageProviderId, providerMet);
- }
- providerMet.update(spaceId, mimetype, size);
- }
-
- public Map<String, StorageProviderMetricsCollector> getStorageProviderMetrics() {
- return storageProviderMetrics;
- }
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Top level metrics storage data structure for DuraStore. Contains all
+ * metrics information for all storage providers.
+ *
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class DuraStoreMetricsCollector extends MetricsCollector {
+
+ private Map<String, StorageProviderMetricsCollector> storageProviderMetrics;
+
+ public DuraStoreMetricsCollector() {
+ super();
+ this.storageProviderMetrics =
+ new HashMap<String, StorageProviderMetricsCollector>();
+ }
+
+ @Override
+ public void update(String mimetype, long size) {
+ String error = "Use update(String, String, String, long)";
+ throw new UnsupportedOperationException(error);
+ }
+
+ public void update(String storageProviderId,
+ String storageProviderType,
+ String spaceId,
+ String mimetype,
+ long size) {
+ super.update(mimetype, size);
+
+ StorageProviderMetricsCollector providerMet =
+ storageProviderMetrics.get(storageProviderId);
+ if(null == providerMet) {
+ providerMet = new StorageProviderMetricsCollector(storageProviderId,
+ storageProviderType);
+ storageProviderMetrics.put(storageProviderId, providerMet);
+ }
+ providerMet.update(spaceId, mimetype, size);
+ }
+
+ public Map<String, StorageProviderMetricsCollector> getStorageProviderMetrics() {
+ return storageProviderMetrics;
+ }
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/MetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/MetricsCollector.java
similarity index 92%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/MetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/MetricsCollector.java
index 8c00d553a..c7b139544 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/MetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/MetricsCollector.java
@@ -1,54 +1,54 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public abstract class MetricsCollector {
-
- private long totalItems;
- private long totalSize;
-
- private Map<String, MimetypeMetricsCollector> mimetypeMetrics;
-
- public MetricsCollector() {
- this.totalItems = 0;
- this.totalSize = 0;
- this.mimetypeMetrics = new HashMap<String, MimetypeMetricsCollector>();
- }
-
- public void update(String mimetype, long size) {
- ++totalItems;
- totalSize += size;
-
- MimetypeMetricsCollector mimeMet = mimetypeMetrics.get(mimetype);
- if(null == mimeMet) {
- mimeMet = new MimetypeMetricsCollector(mimetype);
- mimetypeMetrics.put(mimetype, mimeMet);
- }
- mimeMet.update(size);
- }
-
- public long getTotalItems() {
- return totalItems;
- }
-
- public long getTotalSize() {
- return totalSize;
- }
-
- public Map<String, MimetypeMetricsCollector> getMimetypeMetrics() {
- return mimetypeMetrics;
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public abstract class MetricsCollector {
+
+ private long totalItems;
+ private long totalSize;
+
+ private Map<String, MimetypeMetricsCollector> mimetypeMetrics;
+
+ public MetricsCollector() {
+ this.totalItems = 0;
+ this.totalSize = 0;
+ this.mimetypeMetrics = new HashMap<String, MimetypeMetricsCollector>();
+ }
+
+ public void update(String mimetype, long size) {
+ ++totalItems;
+ totalSize += size;
+
+ MimetypeMetricsCollector mimeMet = mimetypeMetrics.get(mimetype);
+ if(null == mimeMet) {
+ mimeMet = new MimetypeMetricsCollector(mimetype);
+ mimetypeMetrics.put(mimetype, mimeMet);
+ }
+ mimeMet.update(size);
+ }
+
+ public long getTotalItems() {
+ return totalItems;
+ }
+
+ public long getTotalSize() {
+ return totalSize;
+ }
+
+ public Map<String, MimetypeMetricsCollector> getMimetypeMetrics() {
+ return mimetypeMetrics;
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/MimetypeMetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/MimetypeMetricsCollector.java
similarity index 90%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/MimetypeMetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/MimetypeMetricsCollector.java
index 3dcc3372e..52d711bab 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/MimetypeMetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/MimetypeMetricsCollector.java
@@ -1,43 +1,43 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-/**
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class MimetypeMetricsCollector {
-
- private String mimetype;
- private long totalItems;
- private long totalSize;
-
- public MimetypeMetricsCollector(String mimetype) {
- this.mimetype = mimetype;
- this.totalItems = 0;
- this.totalSize = 0;
- }
-
- public void update(long size) {
- ++totalItems;
- totalSize += size;
- }
-
- public String getMimetype() {
- return mimetype;
- }
-
- public long getTotalItems() {
- return totalItems;
- }
-
- public long getTotalSize() {
- return totalSize;
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+/**
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class MimetypeMetricsCollector {
+
+ private String mimetype;
+ private long totalItems;
+ private long totalSize;
+
+ public MimetypeMetricsCollector(String mimetype) {
+ this.mimetype = mimetype;
+ this.totalItems = 0;
+ this.totalSize = 0;
+ }
+
+ public void update(long size) {
+ ++totalItems;
+ totalSize += size;
+ }
+
+ public String getMimetype() {
+ return mimetype;
+ }
+
+ public long getTotalItems() {
+ return totalItems;
+ }
+
+ public long getTotalSize() {
+ return totalSize;
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/SpaceMetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/SpaceMetricsCollector.java
similarity index 89%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/SpaceMetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/SpaceMetricsCollector.java
index c501226dc..f13a7b6b4 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/SpaceMetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/SpaceMetricsCollector.java
@@ -1,30 +1,30 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-/**
- * Metrics data structure for spaces. Contains all of the metrics for a single
- * space.
- *
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class SpaceMetricsCollector extends MetricsCollector {
-
- private String spaceName;
-
- public SpaceMetricsCollector(String spaceName) {
- super();
- this.spaceName = spaceName;
- }
-
- public String getSpaceName() {
- return spaceName;
- }
-
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+/**
+ * Metrics data structure for spaces. Contains all of the metrics for a single
+ * space.
+ *
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class SpaceMetricsCollector extends MetricsCollector {
+
+ private String spaceName;
+
+ public SpaceMetricsCollector(String spaceName) {
+ super();
+ this.spaceName = spaceName;
+ }
+
+ public String getSpaceName() {
+ return spaceName;
+ }
+
+}
diff --git a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/StorageProviderMetricsCollector.java b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/StorageProviderMetricsCollector.java
similarity index 94%
rename from durareport/src/main/java/org/duracloud/durareport/storage/metrics/StorageProviderMetricsCollector.java
rename to reporter/src/main/java/org/duracloud/reporter/storage/metrics/StorageProviderMetricsCollector.java
index 38bb121a2..3ad548dc6 100644
--- a/durareport/src/main/java/org/duracloud/durareport/storage/metrics/StorageProviderMetricsCollector.java
+++ b/reporter/src/main/java/org/duracloud/reporter/storage/metrics/StorageProviderMetricsCollector.java
@@ -1,62 +1,62 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Metrics data structure for storage providers. Contains all of the metrics
- * information about a single storage provider and its storage spaces.
- *
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class StorageProviderMetricsCollector extends MetricsCollector {
-
- private String storageProviderId;
- private String storageProviderType;
- private Map<String, SpaceMetricsCollector> spaceMetrics;
-
- public StorageProviderMetricsCollector(String storageProviderId,
- String storageProviderType) {
- super();
- this.storageProviderId = storageProviderId;
- this.storageProviderType = storageProviderType;
- this.spaceMetrics = new HashMap<String, SpaceMetricsCollector>();
- }
-
- @Override
- public void update(String mimetype, long size) {
- String error = "Use update(String, String, long)";
- throw new UnsupportedOperationException(error);
- }
-
- public void update(String spaceId, String mimetype, long size) {
- super.update(mimetype, size);
-
- SpaceMetricsCollector spaceMet = spaceMetrics.get(spaceId);
- if(null == spaceMet) {
- spaceMet = new SpaceMetricsCollector(spaceId);
- spaceMetrics.put(spaceId, spaceMet);
- }
- spaceMet.update(mimetype, size);
- }
-
- public String getStorageProviderId() {
- return storageProviderId;
- }
-
- public String getStorageProviderType() {
- return storageProviderType;
- }
-
- public Map<String, SpaceMetricsCollector> getSpaceMetrics() {
- return spaceMetrics;
- }
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Metrics data structure for storage providers. Contains all of the metrics
+ * information about a single storage provider and its storage spaces.
+ *
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class StorageProviderMetricsCollector extends MetricsCollector {
+
+ private String storageProviderId;
+ private String storageProviderType;
+ private Map<String, SpaceMetricsCollector> spaceMetrics;
+
+ public StorageProviderMetricsCollector(String storageProviderId,
+ String storageProviderType) {
+ super();
+ this.storageProviderId = storageProviderId;
+ this.storageProviderType = storageProviderType;
+ this.spaceMetrics = new HashMap<String, SpaceMetricsCollector>();
+ }
+
+ @Override
+ public void update(String mimetype, long size) {
+ String error = "Use update(String, String, long)";
+ throw new UnsupportedOperationException(error);
+ }
+
+ public void update(String spaceId, String mimetype, long size) {
+ super.update(mimetype, size);
+
+ SpaceMetricsCollector spaceMet = spaceMetrics.get(spaceId);
+ if(null == spaceMet) {
+ spaceMet = new SpaceMetricsCollector(spaceId);
+ spaceMetrics.put(spaceId, spaceMet);
+ }
+ spaceMet.update(mimetype, size);
+ }
+
+ public String getStorageProviderId() {
+ return storageProviderId;
+ }
+
+ public String getStorageProviderType() {
+ return storageProviderType;
+ }
+
+ public Map<String, SpaceMetricsCollector> getSpaceMetrics() {
+ return spaceMetrics;
+ }
+}
diff --git a/durareport/src/test/java/org/duracloud/durareport/notification/EmailNotifierTest.java b/reporter/src/test/java/org/duracloud/reporter/notification/EmailNotifierTest.java
similarity index 93%
rename from durareport/src/test/java/org/duracloud/durareport/notification/EmailNotifierTest.java
rename to reporter/src/test/java/org/duracloud/reporter/notification/EmailNotifierTest.java
index d6d54f742..33a679bfa 100644
--- a/durareport/src/test/java/org/duracloud/durareport/notification/EmailNotifierTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/notification/EmailNotifierTest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.notification.Emailer;
import org.easymock.classextension.EasyMock;
diff --git a/durareport/src/test/java/org/duracloud/durareport/notification/NotificationManagerTest.java b/reporter/src/test/java/org/duracloud/reporter/notification/NotificationManagerTest.java
similarity index 94%
rename from durareport/src/test/java/org/duracloud/durareport/notification/NotificationManagerTest.java
rename to reporter/src/test/java/org/duracloud/reporter/notification/NotificationManagerTest.java
index bd6969c67..094b33aa0 100644
--- a/durareport/src/test/java/org/duracloud/durareport/notification/NotificationManagerTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/notification/NotificationManagerTest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.notification;
+package org.duracloud.reporter.notification;
import org.duracloud.appconfig.domain.NotificationConfig;
import org.easymock.classextension.EasyMock;
diff --git a/durareport/src/test/java/org/duracloud/durareport/service/ServiceNotificationMonitorTest.java b/reporter/src/test/java/org/duracloud/reporter/service/ServiceNotificationMonitorTest.java
similarity index 90%
rename from durareport/src/test/java/org/duracloud/durareport/service/ServiceNotificationMonitorTest.java
rename to reporter/src/test/java/org/duracloud/reporter/service/ServiceNotificationMonitorTest.java
index 024aedee1..695b5161f 100644
--- a/durareport/src/test/java/org/duracloud/durareport/service/ServiceNotificationMonitorTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/service/ServiceNotificationMonitorTest.java
@@ -5,10 +5,10 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.service;
+package org.duracloud.reporter.service;
-import org.duracloud.durareport.notification.NotificationManager;
-import org.duracloud.durareport.notification.NotificationType;
+import org.duracloud.reporter.notification.NotificationManager;
+import org.duracloud.reporter.notification.NotificationType;
import org.duracloud.security.DuracloudUserDetailsService;
import org.duracloud.security.domain.SecurityUserBean;
import org.duracloud.serviceconfig.ServiceSummary;
diff --git a/durareport/src/test/java/org/duracloud/durareport/service/ServiceReportBuilderTest.java b/reporter/src/test/java/org/duracloud/reporter/service/ServiceReportBuilderTest.java
similarity index 96%
rename from durareport/src/test/java/org/duracloud/durareport/service/ServiceReportBuilderTest.java
rename to reporter/src/test/java/org/duracloud/reporter/service/ServiceReportBuilderTest.java
index ab38e16f8..fa63daf29 100644
--- a/durareport/src/test/java/org/duracloud/durareport/service/ServiceReportBuilderTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/service/ServiceReportBuilderTest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.service;
+package org.duracloud.reporter.service;
import org.duracloud.serviceapi.ServicesManager;
import org.duracloud.serviceconfig.ServiceSummary;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportBuilderTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportBuilderTest.java
similarity index 92%
rename from durareport/src/test/java/org/duracloud/durareport/storage/StorageReportBuilderTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/StorageReportBuilderTest.java
index dea6bfeda..163953c6e 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportBuilderTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportBuilderTest.java
@@ -5,14 +5,14 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
import org.duracloud.client.ContentStore;
import org.duracloud.client.ContentStoreManager;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
-import org.duracloud.durareport.storage.metrics.MimetypeMetricsCollector;
-import org.duracloud.durareport.storage.metrics.SpaceMetricsCollector;
-import org.duracloud.durareport.storage.metrics.StorageProviderMetricsCollector;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.reporter.storage.metrics.MimetypeMetricsCollector;
+import org.duracloud.reporter.storage.metrics.SpaceMetricsCollector;
+import org.duracloud.reporter.storage.metrics.StorageProviderMetricsCollector;
import org.duracloud.reportdata.storage.StorageReport;
import org.easymock.Capture;
import org.easymock.IAnswer;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportConverterTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportConverterTest.java
similarity index 95%
rename from durareport/src/test/java/org/duracloud/durareport/storage/StorageReportConverterTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/StorageReportConverterTest.java
index 7130d04eb..7f4606257 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportConverterTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportConverterTest.java
@@ -5,9 +5,9 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
import org.duracloud.reportdata.storage.StorageReport;
import org.duracloud.reportdata.storage.metrics.MimetypeMetrics;
import org.duracloud.reportdata.storage.metrics.SpaceMetrics;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportHandlerTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportHandlerTest.java
similarity index 96%
rename from durareport/src/test/java/org/duracloud/durareport/storage/StorageReportHandlerTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/StorageReportHandlerTest.java
index 790698b34..8860a3833 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportHandlerTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportHandlerTest.java
@@ -5,12 +5,12 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
import org.duracloud.client.ContentStore;
import org.duracloud.client.ContentStoreManager;
import org.duracloud.domain.Content;
-import org.duracloud.durareport.storage.metrics.DuraStoreMetricsCollector;
+import org.duracloud.reporter.storage.metrics.DuraStoreMetricsCollector;
import org.duracloud.reportdata.storage.StorageReport;
import org.duracloud.reportdata.storage.metrics.StorageMetrics;
import org.duracloud.reportdata.storage.serialize.StorageReportSerializer;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportSchedulerTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportSchedulerTest.java
similarity index 94%
rename from durareport/src/test/java/org/duracloud/durareport/storage/StorageReportSchedulerTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/StorageReportSchedulerTest.java
index 1154bfde8..82837b186 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/StorageReportSchedulerTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/StorageReportSchedulerTest.java
@@ -5,7 +5,7 @@
*
* http://duracloud.org/license/
*/
-package org.duracloud.durareport.storage;
+package org.duracloud.reporter.storage;
import org.easymock.classextension.EasyMock;
import org.junit.After;
diff --git a/durareport/src/test/java/org/duracloud/durareport/storage/metrics/MetricsCollectorTest.java b/reporter/src/test/java/org/duracloud/reporter/storage/metrics/MetricsCollectorTest.java
similarity index 96%
rename from durareport/src/test/java/org/duracloud/durareport/storage/metrics/MetricsCollectorTest.java
rename to reporter/src/test/java/org/duracloud/reporter/storage/metrics/MetricsCollectorTest.java
index 542a7e2b2..f8258f5fc 100644
--- a/durareport/src/test/java/org/duracloud/durareport/storage/metrics/MetricsCollectorTest.java
+++ b/reporter/src/test/java/org/duracloud/reporter/storage/metrics/MetricsCollectorTest.java
@@ -1,292 +1,292 @@
-/*
- * The contents of this file are subject to the license and copyright
- * detailed in the LICENSE and NOTICE files at the root of the source
- * tree and available online at
- *
- * http://duracloud.org/license/
- */
-package org.duracloud.durareport.storage.metrics;
-
-import org.junit.Test;
-
-import java.util.Map;
-
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
-
-/**
- * @author: Bill Branan
- * Date: 5/12/11
- */
-public class MetricsCollectorTest {
-
- private String mimetype1 = "text/plain";
- private String mimetype2 = "text/xml";
- private String mimetype3 = "application/xml";
- private String spaceName1 = "space1";
- private String spaceName2 = "space2";
- private String providerId1 = "provider1";
- private String providerType1 = "AMAZON";
- private String providerId2 = "provider2";
- private String providerType2 = "RACKSPACE";
-
- @Test
- public void testMimetypeMetrics() {
- MimetypeMetricsCollector metrics = new MimetypeMetricsCollector(mimetype1);
-
- // Add data
- for(int i=1; i<=100; i++) {
- metrics.update(i);
- }
-
- // Verify totals
- assertEquals(mimetype1, metrics.getMimetype());
- assertEquals(100, metrics.getTotalItems());
- assertEquals(5050, metrics.getTotalSize());
- }
-
- @Test
- public void testSpaceMetrics() {
- SpaceMetricsCollector metrics = new SpaceMetricsCollector(spaceName1);
-
- // Add data
- for(int i=1; i<=10; i++) {
- metrics.update(mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(mimetype3, i);
- }
-
- verifySpaceTotals(spaceName1, metrics);
- }
-
- private void verifySpaceTotals(String spaceName, SpaceMetricsCollector metrics) {
- // Verify space totals
- assertEquals(spaceName, metrics.getSpaceName());
- assertEquals(18, metrics.getTotalItems());
- assertEquals(76, metrics.getTotalSize());
-
- // Verify mimetype totals
- Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
- metrics.getMimetypeMetrics();
- assertEquals(3, mimetypeMetricsMap.size());
-
- MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
- assertNotNull(mimetype1Metrics);
- assertEquals(mimetype1, mimetype1Metrics.getMimetype());
- assertEquals(10, mimetype1Metrics.getTotalItems());
- assertEquals(55, mimetype1Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
- assertNotNull(mimetype2Metrics);
- assertEquals(mimetype2, mimetype2Metrics.getMimetype());
- assertEquals(5, mimetype2Metrics.getTotalItems());
- assertEquals(15, mimetype2Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
- assertNotNull(mimetype3Metrics);
- assertEquals(mimetype3, mimetype3Metrics.getMimetype());
- assertEquals(3, mimetype3Metrics.getTotalItems());
- assertEquals(6, mimetype3Metrics.getTotalSize());
- }
-
- @Test
- public void testStorageProviderMetricsError() {
- StorageProviderMetricsCollector metrics =
- new StorageProviderMetricsCollector(providerId1, providerType1);
-
- try {
- metrics.update(mimetype1, 1);
- fail("Exception expected");
- } catch(UnsupportedOperationException expected) {
- assertNotNull(expected);
- }
- }
-
- @Test
- public void testStorageProviderMetrics() {
- StorageProviderMetricsCollector metrics =
- new StorageProviderMetricsCollector(providerId1, providerType1);
-
- // Add data for space 1
- for(int i=1; i<=10; i++) {
- metrics.update(spaceName1, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(spaceName1, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(spaceName1, mimetype3, i);
- }
-
- // Add data for space 2
- for(int i=1; i<=10; i++) {
- metrics.update(spaceName2, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(spaceName2, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(spaceName2, mimetype3, i);
- }
-
- verifyStorageProviderMetrics(providerId1, metrics);
- }
-
- private void verifyStorageProviderMetrics(String providerId,
- StorageProviderMetricsCollector metrics) {
- // Verify storage provider totals
- assertEquals(providerId, metrics.getStorageProviderId());
- assertEquals(36, metrics.getTotalItems());
- assertEquals(152, metrics.getTotalSize());
-
- // Verify storage provider mimetype totals
- Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
- metrics.getMimetypeMetrics();
- assertEquals(3, mimetypeMetricsMap.size());
-
- MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
- assertNotNull(mimetype1Metrics);
- assertEquals(mimetype1, mimetype1Metrics.getMimetype());
- assertEquals(20, mimetype1Metrics.getTotalItems());
- assertEquals(110, mimetype1Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
- assertNotNull(mimetype2Metrics);
- assertEquals(mimetype2, mimetype2Metrics.getMimetype());
- assertEquals(10, mimetype2Metrics.getTotalItems());
- assertEquals(30, mimetype2Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
- assertNotNull(mimetype3Metrics);
- assertEquals(mimetype3, mimetype3Metrics.getMimetype());
- assertEquals(6, mimetype3Metrics.getTotalItems());
- assertEquals(12, mimetype3Metrics.getTotalSize());
-
- // Verify space metrics map
- Map<String, SpaceMetricsCollector> spaceMetricsMap = metrics.getSpaceMetrics();
- assertNotNull(spaceMetricsMap);
- assertEquals(2, spaceMetricsMap.size());
-
- // Verify space 1 totals
- SpaceMetricsCollector space1Metrics = spaceMetricsMap.get(spaceName1);
- assertNotNull(space1Metrics);
- verifySpaceTotals(spaceName1, space1Metrics);
-
- // Verify space 2 totals
- SpaceMetricsCollector space2Metrics = spaceMetricsMap.get(spaceName2);
- assertNotNull(space2Metrics);
- verifySpaceTotals(spaceName2, space2Metrics);
- }
-
- @Test
- public void testDuraStoreMetricsError() {
- DuraStoreMetricsCollector metrics = new DuraStoreMetricsCollector();
-
- try {
- metrics.update(mimetype1, 1);
- fail("Exception expected");
- } catch(UnsupportedOperationException expected) {
- assertNotNull(expected);
- }
- }
-
- @Test
- public void testDuraStoreMetrics() {
- DuraStoreMetricsCollector metrics = new DuraStoreMetricsCollector();
-
- // Add data
-
- // Provider 1, Space 1
- for(int i=1; i<=10; i++) {
- metrics.update(providerId1, providerType1, spaceName1, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(providerId1, providerType1, spaceName1, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(providerId1, providerType1, spaceName1, mimetype3, i);
- }
-
- // Provider 1, Space 2
- for(int i=1; i<=10; i++) {
- metrics.update(providerId1, providerType1, spaceName2, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(providerId1, providerType1, spaceName2, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(providerId1, providerType1, spaceName2, mimetype3, i);
- }
-
- // Provider 2, Space 1
- for(int i=1; i<=10; i++) {
- metrics.update(providerId2, providerType2, spaceName1, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(providerId2, providerType2, spaceName1, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(providerId2, providerType2, spaceName1, mimetype3, i);
- }
-
- // Provider 2, Space 2
- for(int i=1; i<=10; i++) {
- metrics.update(providerId2, providerType2, spaceName2, mimetype1, i);
- }
- for(int i=1; i<=5; i++) {
- metrics.update(providerId2, providerType2, spaceName2, mimetype2, i);
- }
- for(int i=1; i<=3; i++) {
- metrics.update(providerId2, providerType2, spaceName2, mimetype3, i);
- }
-
- // Verify durastore totals
- assertEquals(72, metrics.getTotalItems());
- assertEquals(304, metrics.getTotalSize());
-
- // Verify durastore mimetype totals
- Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
- metrics.getMimetypeMetrics();
- assertEquals(3, mimetypeMetricsMap.size());
-
- MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
- assertNotNull(mimetype1Metrics);
- assertEquals(mimetype1, mimetype1Metrics.getMimetype());
- assertEquals(40, mimetype1Metrics.getTotalItems());
- assertEquals(220, mimetype1Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
- assertNotNull(mimetype2Metrics);
- assertEquals(mimetype2, mimetype2Metrics.getMimetype());
- assertEquals(20, mimetype2Metrics.getTotalItems());
- assertEquals(60, mimetype2Metrics.getTotalSize());
-
- MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
- assertNotNull(mimetype3Metrics);
- assertEquals(mimetype3, mimetype3Metrics.getMimetype());
- assertEquals(12, mimetype3Metrics.getTotalItems());
- assertEquals(24, mimetype3Metrics.getTotalSize());
-
- // Verify storage provider metrics map
- Map<String, StorageProviderMetricsCollector> storageProviderMetricsMap =
- metrics.getStorageProviderMetrics();
- assertNotNull(storageProviderMetricsMap);
- assertEquals(2, storageProviderMetricsMap.size());
-
- // Verify storage provider 1 totals
- StorageProviderMetricsCollector spMetrics1 =
- storageProviderMetricsMap.get(providerId1);
- assertNotNull(spMetrics1);
- verifyStorageProviderMetrics(providerId1, spMetrics1);
-
- // Verify storage provider 2 totals
- StorageProviderMetricsCollector spMetrics2 =
- storageProviderMetricsMap.get(providerId2);
- assertNotNull(spMetrics2);
- verifyStorageProviderMetrics(providerId2, spMetrics2);
- }
-}
+/*
+ * The contents of this file are subject to the license and copyright
+ * detailed in the LICENSE and NOTICE files at the root of the source
+ * tree and available online at
+ *
+ * http://duracloud.org/license/
+ */
+package org.duracloud.reporter.storage.metrics;
+
+import org.junit.Test;
+
+import java.util.Map;
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @author: Bill Branan
+ * Date: 5/12/11
+ */
+public class MetricsCollectorTest {
+
+ private String mimetype1 = "text/plain";
+ private String mimetype2 = "text/xml";
+ private String mimetype3 = "application/xml";
+ private String spaceName1 = "space1";
+ private String spaceName2 = "space2";
+ private String providerId1 = "provider1";
+ private String providerType1 = "AMAZON";
+ private String providerId2 = "provider2";
+ private String providerType2 = "RACKSPACE";
+
+ @Test
+ public void testMimetypeMetrics() {
+ MimetypeMetricsCollector metrics = new MimetypeMetricsCollector(mimetype1);
+
+ // Add data
+ for(int i=1; i<=100; i++) {
+ metrics.update(i);
+ }
+
+ // Verify totals
+ assertEquals(mimetype1, metrics.getMimetype());
+ assertEquals(100, metrics.getTotalItems());
+ assertEquals(5050, metrics.getTotalSize());
+ }
+
+ @Test
+ public void testSpaceMetrics() {
+ SpaceMetricsCollector metrics = new SpaceMetricsCollector(spaceName1);
+
+ // Add data
+ for(int i=1; i<=10; i++) {
+ metrics.update(mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(mimetype3, i);
+ }
+
+ verifySpaceTotals(spaceName1, metrics);
+ }
+
+ private void verifySpaceTotals(String spaceName, SpaceMetricsCollector metrics) {
+ // Verify space totals
+ assertEquals(spaceName, metrics.getSpaceName());
+ assertEquals(18, metrics.getTotalItems());
+ assertEquals(76, metrics.getTotalSize());
+
+ // Verify mimetype totals
+ Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
+ metrics.getMimetypeMetrics();
+ assertEquals(3, mimetypeMetricsMap.size());
+
+ MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
+ assertNotNull(mimetype1Metrics);
+ assertEquals(mimetype1, mimetype1Metrics.getMimetype());
+ assertEquals(10, mimetype1Metrics.getTotalItems());
+ assertEquals(55, mimetype1Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
+ assertNotNull(mimetype2Metrics);
+ assertEquals(mimetype2, mimetype2Metrics.getMimetype());
+ assertEquals(5, mimetype2Metrics.getTotalItems());
+ assertEquals(15, mimetype2Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
+ assertNotNull(mimetype3Metrics);
+ assertEquals(mimetype3, mimetype3Metrics.getMimetype());
+ assertEquals(3, mimetype3Metrics.getTotalItems());
+ assertEquals(6, mimetype3Metrics.getTotalSize());
+ }
+
+ @Test
+ public void testStorageProviderMetricsError() {
+ StorageProviderMetricsCollector metrics =
+ new StorageProviderMetricsCollector(providerId1, providerType1);
+
+ try {
+ metrics.update(mimetype1, 1);
+ fail("Exception expected");
+ } catch(UnsupportedOperationException expected) {
+ assertNotNull(expected);
+ }
+ }
+
+ @Test
+ public void testStorageProviderMetrics() {
+ StorageProviderMetricsCollector metrics =
+ new StorageProviderMetricsCollector(providerId1, providerType1);
+
+ // Add data for space 1
+ for(int i=1; i<=10; i++) {
+ metrics.update(spaceName1, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(spaceName1, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(spaceName1, mimetype3, i);
+ }
+
+ // Add data for space 2
+ for(int i=1; i<=10; i++) {
+ metrics.update(spaceName2, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(spaceName2, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(spaceName2, mimetype3, i);
+ }
+
+ verifyStorageProviderMetrics(providerId1, metrics);
+ }
+
+ private void verifyStorageProviderMetrics(String providerId,
+ StorageProviderMetricsCollector metrics) {
+ // Verify storage provider totals
+ assertEquals(providerId, metrics.getStorageProviderId());
+ assertEquals(36, metrics.getTotalItems());
+ assertEquals(152, metrics.getTotalSize());
+
+ // Verify storage provider mimetype totals
+ Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
+ metrics.getMimetypeMetrics();
+ assertEquals(3, mimetypeMetricsMap.size());
+
+ MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
+ assertNotNull(mimetype1Metrics);
+ assertEquals(mimetype1, mimetype1Metrics.getMimetype());
+ assertEquals(20, mimetype1Metrics.getTotalItems());
+ assertEquals(110, mimetype1Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
+ assertNotNull(mimetype2Metrics);
+ assertEquals(mimetype2, mimetype2Metrics.getMimetype());
+ assertEquals(10, mimetype2Metrics.getTotalItems());
+ assertEquals(30, mimetype2Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
+ assertNotNull(mimetype3Metrics);
+ assertEquals(mimetype3, mimetype3Metrics.getMimetype());
+ assertEquals(6, mimetype3Metrics.getTotalItems());
+ assertEquals(12, mimetype3Metrics.getTotalSize());
+
+ // Verify space metrics map
+ Map<String, SpaceMetricsCollector> spaceMetricsMap = metrics.getSpaceMetrics();
+ assertNotNull(spaceMetricsMap);
+ assertEquals(2, spaceMetricsMap.size());
+
+ // Verify space 1 totals
+ SpaceMetricsCollector space1Metrics = spaceMetricsMap.get(spaceName1);
+ assertNotNull(space1Metrics);
+ verifySpaceTotals(spaceName1, space1Metrics);
+
+ // Verify space 2 totals
+ SpaceMetricsCollector space2Metrics = spaceMetricsMap.get(spaceName2);
+ assertNotNull(space2Metrics);
+ verifySpaceTotals(spaceName2, space2Metrics);
+ }
+
+ @Test
+ public void testDuraStoreMetricsError() {
+ DuraStoreMetricsCollector metrics = new DuraStoreMetricsCollector();
+
+ try {
+ metrics.update(mimetype1, 1);
+ fail("Exception expected");
+ } catch(UnsupportedOperationException expected) {
+ assertNotNull(expected);
+ }
+ }
+
+ @Test
+ public void testDuraStoreMetrics() {
+ DuraStoreMetricsCollector metrics = new DuraStoreMetricsCollector();
+
+ // Add data
+
+ // Provider 1, Space 1
+ for(int i=1; i<=10; i++) {
+ metrics.update(providerId1, providerType1, spaceName1, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(providerId1, providerType1, spaceName1, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(providerId1, providerType1, spaceName1, mimetype3, i);
+ }
+
+ // Provider 1, Space 2
+ for(int i=1; i<=10; i++) {
+ metrics.update(providerId1, providerType1, spaceName2, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(providerId1, providerType1, spaceName2, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(providerId1, providerType1, spaceName2, mimetype3, i);
+ }
+
+ // Provider 2, Space 1
+ for(int i=1; i<=10; i++) {
+ metrics.update(providerId2, providerType2, spaceName1, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(providerId2, providerType2, spaceName1, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(providerId2, providerType2, spaceName1, mimetype3, i);
+ }
+
+ // Provider 2, Space 2
+ for(int i=1; i<=10; i++) {
+ metrics.update(providerId2, providerType2, spaceName2, mimetype1, i);
+ }
+ for(int i=1; i<=5; i++) {
+ metrics.update(providerId2, providerType2, spaceName2, mimetype2, i);
+ }
+ for(int i=1; i<=3; i++) {
+ metrics.update(providerId2, providerType2, spaceName2, mimetype3, i);
+ }
+
+ // Verify durastore totals
+ assertEquals(72, metrics.getTotalItems());
+ assertEquals(304, metrics.getTotalSize());
+
+ // Verify durastore mimetype totals
+ Map<String, MimetypeMetricsCollector> mimetypeMetricsMap =
+ metrics.getMimetypeMetrics();
+ assertEquals(3, mimetypeMetricsMap.size());
+
+ MimetypeMetricsCollector mimetype1Metrics = mimetypeMetricsMap.get(mimetype1);
+ assertNotNull(mimetype1Metrics);
+ assertEquals(mimetype1, mimetype1Metrics.getMimetype());
+ assertEquals(40, mimetype1Metrics.getTotalItems());
+ assertEquals(220, mimetype1Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype2Metrics = mimetypeMetricsMap.get(mimetype2);
+ assertNotNull(mimetype2Metrics);
+ assertEquals(mimetype2, mimetype2Metrics.getMimetype());
+ assertEquals(20, mimetype2Metrics.getTotalItems());
+ assertEquals(60, mimetype2Metrics.getTotalSize());
+
+ MimetypeMetricsCollector mimetype3Metrics = mimetypeMetricsMap.get(mimetype3);
+ assertNotNull(mimetype3Metrics);
+ assertEquals(mimetype3, mimetype3Metrics.getMimetype());
+ assertEquals(12, mimetype3Metrics.getTotalItems());
+ assertEquals(24, mimetype3Metrics.getTotalSize());
+
+ // Verify storage provider metrics map
+ Map<String, StorageProviderMetricsCollector> storageProviderMetricsMap =
+ metrics.getStorageProviderMetrics();
+ assertNotNull(storageProviderMetricsMap);
+ assertEquals(2, storageProviderMetricsMap.size());
+
+ // Verify storage provider 1 totals
+ StorageProviderMetricsCollector spMetrics1 =
+ storageProviderMetricsMap.get(providerId1);
+ assertNotNull(spMetrics1);
+ verifyStorageProviderMetrics(providerId1, spMetrics1);
+
+ // Verify storage provider 2 totals
+ StorageProviderMetricsCollector spMetrics2 =
+ storageProviderMetricsMap.get(providerId2);
+ assertNotNull(spMetrics2);
+ verifyStorageProviderMetrics(providerId2, spMetrics2);
+ }
+}
diff --git a/resources/readme.txt b/resources/readme.txt
index e6b67eccb..b87a442ab 100644
--- a/resources/readme.txt
+++ b/resources/readme.txt
@@ -6,7 +6,7 @@ This package should include the following:
a. war files
-- durastore.war
-- duraservice.war
--- durareport.war
+-- duraboss.war
-- duradmin.war
b. services
|
4713ae66eda8b146b13970dbbd3e5ab5b92ed6da
|
bendisposto$prob
|
added support for simple theory mapping files
|
a
|
https://github.com/hhu-stups/prob-rodinplugin
|
diff --git a/de.prob.core/src/de/prob/eventb/translator/Theories.java b/de.prob.core/src/de/prob/eventb/translator/Theories.java
index 53e916cf..6b598b55 100644
--- a/de.prob.core/src/de/prob/eventb/translator/Theories.java
+++ b/de.prob.core/src/de/prob/eventb/translator/Theories.java
@@ -1,9 +1,16 @@
package de.prob.eventb.translator;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.util.Collection;
+import java.util.Collections;
import java.util.LinkedList;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eventb.core.IEventBProject;
@@ -41,6 +48,9 @@
import de.prob.prolog.output.IPrologTermOutput;
import de.prob.prolog.output.StructuredPrologOutput;
import de.prob.prolog.term.PrologTerm;
+import de.prob.tmparser.OperatorMapping;
+import de.prob.tmparser.TheoryMappingException;
+import de.prob.tmparser.TheoryMappingParser;
public class Theories {
private static final String PROB_THEORY_MAPPING_SUFFIX = "ptm";
@@ -74,9 +84,12 @@ public static void translate(IEventBProject project, IPrologTermOutput pout)
* the translation is currently very unstable and erroneous. Writing in a
* Prolog object makes sure that the output stream to the Prolog process
* will not be corrupted.
+ *
+ * @throws TranslationFailedException
*/
private static void savePrintTranslation(IDeployedTheoryRoot theory,
- IPrologTermOutput opto) throws RodinDBException {
+ IPrologTermOutput opto) throws RodinDBException,
+ TranslationFailedException {
final StructuredPrologOutput pto = new StructuredPrologOutput();
printTranslation(theory, pto);
@@ -86,7 +99,8 @@ private static void savePrintTranslation(IDeployedTheoryRoot theory,
}
private static void printTranslation(IDeployedTheoryRoot theory,
- StructuredPrologOutput pto) throws RodinDBException {
+ StructuredPrologOutput pto) throws RodinDBException,
+ TranslationFailedException {
pto.openTerm("theory");
printIdentifiers(theory.getSCTypeParameters(), pto);
printDataTypes(theory, pto);
@@ -97,23 +111,51 @@ private static void printTranslation(IDeployedTheoryRoot theory,
}
private static void findProBMappingFile(IDeployedTheoryRoot theory,
- IPrologTermOutput pto) {
+ IPrologTermOutput pto) throws TranslationFailedException {
final String theoryName = theory.getComponentName();
final IPath path = new Path(theoryName + "."
+ PROB_THEORY_MAPPING_SUFFIX);
final IProject project = theory.getRodinProject().getProject();
+ final Collection<OperatorMapping> mappings;
if (project.exists(path)) {
final IFile file = project.getFile(path);
- readAndPrintMapping(file, theory, pto);
+ mappings = readMappingFile(file, theory);
} else {
- pto.printAtom("none");
+ mappings = Collections.emptyList();
}
+ printMappings(mappings, pto);
}
- private static void readAndPrintMapping(IFile file,
- IDeployedTheoryRoot theory, IPrologTermOutput pto) {
- // TODO Auto-generated method stub
+ private static Collection<OperatorMapping> readMappingFile(IFile file,
+ IDeployedTheoryRoot theory) throws TranslationFailedException {
+ try {
+ final InputStream input = file.getContents();
+ final String name = theory.getComponentName();
+ final Reader reader = new InputStreamReader(input);
+ return TheoryMappingParser.parseTheoryMapping(name, reader);
+ } catch (CoreException e) {
+ throw new TranslationFailedException(e);
+ } catch (TheoryMappingException e) {
+ throw new TranslationFailedException(e);
+ } catch (IOException e) {
+ throw new TranslationFailedException(e);
+ }
+ }
+ private static void printMappings(Collection<OperatorMapping> mappings,
+ IPrologTermOutput pto) {
+ pto.openList();
+ // Currently, we support only one kind of operator mapping, just tagging
+ // an operator to indicate that an optimized ProB implementation should
+ // be used. We do not invest any effort in preparing future kinds of
+ // other operator mappings.
+ for (OperatorMapping mapping : mappings) {
+ pto.openTerm("tag");
+ pto.printAtom(mapping.getOperatorName());
+ pto.printAtom(mapping.getSpec());
+ pto.closeTerm();
+ }
+ pto.closeList();
}
private static void printIdentifiers(ISCIdentifierElement[] identifiers,
@@ -250,7 +292,8 @@ private static void printTypedIdentifier(final String functor,
final IPrologTermOutput pto) throws RodinDBException {
pto.openTerm(functor);
pto.printAtom(id.getIdentifierString());
- printType(id.getType(ff), ff, pto);
+ Type type = id.getType(ff);
+ printType(type, ff, pto);
pto.closeTerm();
}
|
06d24042b64d6fa0e179b5845990068f849d9ce5
|
hadoop
|
YARN-1185. Fixed FileSystemRMStateStore to not- leave partial files that prevent subsequent ResourceManager recovery.- Contributed by Omkar Vinit Joshi. svn merge --ignore-ancestry -c 1533803- ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1533805 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 27cf02c418127..8c0ea418f00a0 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -105,6 +105,9 @@ Release 2.2.1 - UNRELEASED
YARN-1295. In UnixLocalWrapperScriptBuilder, using bash -c can cause Text
file busy errors (Sandy Ryza)
+ YARN-1185. Fixed FileSystemRMStateStore to not leave partial files that
+ prevent subsequent ResourceManager recovery. (Omkar Vinit Joshi via vinodkv)
+
Release 2.2.0 - 2013-10-13
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
index 062f5cc55329e..e85ba924a1a74 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
@@ -22,6 +22,7 @@
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@@ -118,6 +119,9 @@ private void loadRMAppState(RMState rmState) throws Exception {
for (FileStatus childNodeStatus : fs.listStatus(appDir.getPath())) {
assert childNodeStatus.isFile();
String childNodeName = childNodeStatus.getPath().getName();
+ if (checkAndRemovePartialRecord(childNodeStatus.getPath())) {
+ continue;
+ }
byte[] childData =
readFile(childNodeStatus.getPath(), childNodeStatus.getLen());
if (childNodeName.startsWith(ApplicationId.appIdStrPrefix)) {
@@ -178,12 +182,28 @@ private void loadRMAppState(RMState rmState) throws Exception {
}
}
+ private boolean checkAndRemovePartialRecord(Path record) throws IOException {
+ // If the file ends with .tmp then it shows that it failed
+ // during saving state into state store. The file will be deleted as a
+ // part of this call
+ if (record.getName().endsWith(".tmp")) {
+ LOG.error("incomplete rm state store entry found :"
+ + record);
+ fs.delete(record, false);
+ return true;
+ }
+ return false;
+ }
+
private void loadRMDTSecretManagerState(RMState rmState) throws Exception {
FileStatus[] childNodes = fs.listStatus(rmDTSecretManagerRoot);
for(FileStatus childNodeStatus : childNodes) {
assert childNodeStatus.isFile();
String childNodeName = childNodeStatus.getPath().getName();
+ if (checkAndRemovePartialRecord(childNodeStatus.getPath())) {
+ continue;
+ }
if(childNodeName.startsWith(DELEGATION_TOKEN_SEQUENCE_NUMBER_PREFIX)) {
rmState.rmSecretManagerState.dtSequenceNumber =
Integer.parseInt(childNodeName.split("_")[1]);
@@ -344,10 +364,19 @@ private byte[] readFile(Path inputPath, long len) throws Exception {
return data;
}
+ /*
+ * In order to make this write atomic as a part of write we will first write
+ * data to .tmp file and then rename it. Here we are assuming that rename is
+ * atomic for underlying file system.
+ */
private void writeFile(Path outputPath, byte[] data) throws Exception {
- FSDataOutputStream fsOut = fs.create(outputPath, false);
+ Path tempPath =
+ new Path(outputPath.getParent(), outputPath.getName() + ".tmp");
+ FSDataOutputStream fsOut = null;
+ fsOut = fs.create(tempPath, false);
fsOut.write(data);
fsOut.close();
+ fs.rename(tempPath, outputPath);
}
private boolean renameFile(Path src, Path dst) throws Exception {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java
similarity index 80%
rename from hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestRMStateStore.java
rename to hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java
index d75fc7d9e18a6..72ef37fa23658 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java
@@ -39,6 +39,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
@@ -75,9 +76,9 @@
import org.junit.Test;
-public class TestRMStateStore extends ClientBaseWithFixes{
+public class RMStateStoreTestBase extends ClientBaseWithFixes{
- public static final Log LOG = LogFactory.getLog(TestRMStateStore.class);
+ public static final Log LOG = LogFactory.getLog(RMStateStoreTestBase.class);
static class TestDispatcher implements
Dispatcher, EventHandler<RMAppAttemptStoredEvent> {
@@ -116,104 +117,6 @@ interface RMStateStoreHelper {
boolean isFinalStateValid() throws Exception;
}
- @Test
- public void testZKRMStateStoreRealZK() throws Exception {
- TestZKRMStateStoreTester zkTester = new TestZKRMStateStoreTester();
- testRMAppStateStore(zkTester);
- testRMDTSecretManagerStateStore(zkTester);
- }
-
- @Test
- public void testFSRMStateStore() throws Exception {
- HdfsConfiguration conf = new HdfsConfiguration();
- MiniDFSCluster cluster =
- new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
- try {
- TestFSRMStateStoreTester fsTester = new TestFSRMStateStoreTester(cluster);
- testRMAppStateStore(fsTester);
- testRMDTSecretManagerStateStore(fsTester);
- } finally {
- cluster.shutdown();
- }
- }
-
- class TestZKRMStateStoreTester implements RMStateStoreHelper {
- ZooKeeper client;
- ZKRMStateStore store;
-
- class TestZKRMStateStore extends ZKRMStateStore {
- public TestZKRMStateStore(Configuration conf, String workingZnode)
- throws Exception {
- init(conf);
- start();
- assertTrue(znodeWorkingPath.equals(workingZnode));
- }
-
- @Override
- public ZooKeeper getNewZooKeeper() throws IOException {
- return client;
- }
- }
-
- public RMStateStore getRMStateStore() throws Exception {
- String workingZnode = "/Test";
- YarnConfiguration conf = new YarnConfiguration();
- conf.set(YarnConfiguration.ZK_RM_STATE_STORE_ADDRESS, hostPort);
- conf.set(YarnConfiguration.ZK_RM_STATE_STORE_PARENT_PATH, workingZnode);
- this.client = createClient();
- this.store = new TestZKRMStateStore(conf, workingZnode);
- return this.store;
- }
-
- @Override
- public boolean isFinalStateValid() throws Exception {
- List<String> nodes = client.getChildren(store.znodeWorkingPath, false);
- return nodes.size() == 1;
- }
- }
-
- class TestFSRMStateStoreTester implements RMStateStoreHelper {
- Path workingDirPathURI;
- FileSystemRMStateStore store;
- MiniDFSCluster cluster;
-
- class TestFileSystemRMStore extends FileSystemRMStateStore {
- TestFileSystemRMStore(Configuration conf) throws Exception {
- init(conf);
- Assert.assertNull(fs);
- assertTrue(workingDirPathURI.equals(fsWorkingPath));
- start();
- Assert.assertNotNull(fs);
- }
- }
-
- public TestFSRMStateStoreTester(MiniDFSCluster cluster) throws Exception {
- Path workingDirPath = new Path("/Test");
- this.cluster = cluster;
- FileSystem fs = cluster.getFileSystem();
- fs.mkdirs(workingDirPath);
- Path clusterURI = new Path(cluster.getURI());
- workingDirPathURI = new Path(clusterURI, workingDirPath);
- fs.close();
- }
-
- @Override
- public RMStateStore getRMStateStore() throws Exception {
- YarnConfiguration conf = new YarnConfiguration();
- conf.set(YarnConfiguration.FS_RM_STATE_STORE_URI,
- workingDirPathURI.toString());
- this.store = new TestFileSystemRMStore(conf);
- return store;
- }
-
- @Override
- public boolean isFinalStateValid() throws Exception {
- FileSystem fs = cluster.getFileSystem();
- FileStatus[] files = fs.listStatus(workingDirPathURI);
- return files.length == 1;
- }
- }
-
void waitNotify(TestDispatcher dispatcher) {
long startTime = System.currentTimeMillis();
while(!dispatcher.notified) {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java
new file mode 100644
index 0000000000000..a1a6eab3fd3d5
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java
@@ -0,0 +1,120 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.yarn.server.resourcemanager.recovery;
+
+import static org.junit.Assert.assertTrue;
+import junit.framework.Assert;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.HdfsConfiguration;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.util.ConverterUtils;
+import org.junit.Test;
+
+public class TestFSRMStateStore extends RMStateStoreTestBase {
+
+ public static final Log LOG = LogFactory.getLog(TestFSRMStateStore.class);
+
+ class TestFSRMStateStoreTester implements RMStateStoreHelper {
+
+ Path workingDirPathURI;
+ FileSystemRMStateStore store;
+ MiniDFSCluster cluster;
+
+ class TestFileSystemRMStore extends FileSystemRMStateStore {
+
+ TestFileSystemRMStore(Configuration conf) throws Exception {
+ init(conf);
+ Assert.assertNull(fs);
+ assertTrue(workingDirPathURI.equals(fsWorkingPath));
+ start();
+ Assert.assertNotNull(fs);
+ }
+ }
+
+ public TestFSRMStateStoreTester(MiniDFSCluster cluster) throws Exception {
+ Path workingDirPath = new Path("/Test");
+ this.cluster = cluster;
+ FileSystem fs = cluster.getFileSystem();
+ fs.mkdirs(workingDirPath);
+ Path clusterURI = new Path(cluster.getURI());
+ workingDirPathURI = new Path(clusterURI, workingDirPath);
+ fs.close();
+ }
+
+ @Override
+ public RMStateStore getRMStateStore() throws Exception {
+ YarnConfiguration conf = new YarnConfiguration();
+ conf.set(YarnConfiguration.FS_RM_STATE_STORE_URI,
+ workingDirPathURI.toString());
+ this.store = new TestFileSystemRMStore(conf);
+ return store;
+ }
+
+ @Override
+ public boolean isFinalStateValid() throws Exception {
+ FileSystem fs = cluster.getFileSystem();
+ FileStatus[] files = fs.listStatus(workingDirPathURI);
+ return files.length == 1;
+ }
+ }
+
+ @Test
+ public void testFSRMStateStore() throws Exception {
+ HdfsConfiguration conf = new HdfsConfiguration();
+ MiniDFSCluster cluster =
+ new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
+ try {
+ TestFSRMStateStoreTester fsTester = new TestFSRMStateStoreTester(cluster);
+ // If the state store is FileSystemRMStateStore then add corrupted entry.
+ // It should discard the entry and remove it from file system.
+ FSDataOutputStream fsOut = null;
+ FileSystemRMStateStore fileSystemRMStateStore =
+ (FileSystemRMStateStore) fsTester.getRMStateStore();
+ String appAttemptIdStr3 = "appattempt_1352994193343_0001_000003";
+ ApplicationAttemptId attemptId3 =
+ ConverterUtils.toApplicationAttemptId(appAttemptIdStr3);
+ Path rootDir =
+ new Path(fileSystemRMStateStore.fsWorkingPath, "FSRMStateRoot");
+ Path appRootDir = new Path(rootDir, "RMAppRoot");
+ Path appDir =
+ new Path(appRootDir, attemptId3.getApplicationId().toString());
+ Path tempAppAttemptFile =
+ new Path(appDir, attemptId3.toString() + ".tmp");
+ fsOut = fileSystemRMStateStore.fs.create(tempAppAttemptFile, false);
+ fsOut.write("Some random data ".getBytes());
+ fsOut.close();
+
+ testRMAppStateStore(fsTester);
+ Assert.assertFalse(fileSystemRMStateStore.fsWorkingPath
+ .getFileSystem(conf).exists(tempAppAttemptFile));
+ testRMDTSecretManagerStateStore(fsTester);
+ } finally {
+ cluster.shutdown();
+ }
+ }
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java
new file mode 100644
index 0000000000000..a6929a8936635
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStore.java
@@ -0,0 +1,80 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.yarn.server.resourcemanager.recovery;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.zookeeper.ZooKeeper;
+import org.junit.Test;
+
+public class TestZKRMStateStore extends RMStateStoreTestBase {
+
+ public static final Log LOG = LogFactory.getLog(TestZKRMStateStore.class);
+
+ class TestZKRMStateStoreTester implements RMStateStoreHelper {
+
+ ZooKeeper client;
+ ZKRMStateStore store;
+
+ class TestZKRMStateStoreInternal extends ZKRMStateStore {
+
+ public TestZKRMStateStoreInternal(Configuration conf, String workingZnode)
+ throws Exception {
+ init(conf);
+ start();
+ assertTrue(znodeWorkingPath.equals(workingZnode));
+ }
+
+ @Override
+ public ZooKeeper getNewZooKeeper() throws IOException {
+ return client;
+ }
+ }
+
+ public RMStateStore getRMStateStore() throws Exception {
+ String workingZnode = "/Test";
+ YarnConfiguration conf = new YarnConfiguration();
+ conf.set(YarnConfiguration.ZK_RM_STATE_STORE_ADDRESS, hostPort);
+ conf.set(YarnConfiguration.ZK_RM_STATE_STORE_PARENT_PATH, workingZnode);
+ this.client = createClient();
+ this.store = new TestZKRMStateStoreInternal(conf, workingZnode);
+ return this.store;
+ }
+
+ @Override
+ public boolean isFinalStateValid() throws Exception {
+ List<String> nodes = client.getChildren(store.znodeWorkingPath, false);
+ return nodes.size() == 1;
+ }
+ }
+
+ @Test
+ public void testZKRMStateStoreRealZK() throws Exception {
+ TestZKRMStateStoreTester zkTester = new TestZKRMStateStoreTester();
+ testRMAppStateStore(zkTester);
+ testRMDTSecretManagerStateStore(zkTester);
+ }
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStoreZKClientConnections.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStoreZKClientConnections.java
index 7c807a5b60202..82e550c9173cc 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStoreZKClientConnections.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestZKRMStateStoreZKClientConnections.java
@@ -24,7 +24,7 @@
import org.apache.hadoop.ha.ClientBaseWithFixes;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.server.resourcemanager.recovery.TestRMStateStore.TestDispatcher;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreTestBase.TestDispatcher;
import org.apache.hadoop.util.ZKUtil;
import org.apache.zookeeper.CreateMode;
@@ -43,17 +43,20 @@
public class TestZKRMStateStoreZKClientConnections extends
ClientBaseWithFixes {
+
private static final int ZK_OP_WAIT_TIME = 3000;
private Log LOG =
LogFactory.getLog(TestZKRMStateStoreZKClientConnections.class);
class TestZKClient {
+
ZKRMStateStore store;
boolean forExpire = false;
TestForwardingWatcher watcher;
CyclicBarrier syncBarrier = new CyclicBarrier(2);
protected class TestZKRMStateStore extends ZKRMStateStore {
+
public TestZKRMStateStore(Configuration conf, String workingZnode)
throws Exception {
init(conf);
@@ -87,6 +90,7 @@ public synchronized void processWatchEvent(WatchedEvent event)
private class TestForwardingWatcher extends
ClientBaseWithFixes.CountdownWatcher {
+
public void process(WatchedEvent event) {
super.process(event);
try {
@@ -187,7 +191,7 @@ public void testZKSessionTimeout() throws Exception {
}
}
- @Test (timeout = 20000)
+ @Test(timeout = 20000)
public void testSetZKAcl() {
TestZKClient zkClientTester = new TestZKClient();
YarnConfiguration conf = new YarnConfiguration();
@@ -196,10 +200,11 @@ public void testSetZKAcl() {
zkClientTester.store.zkClient.delete(zkClientTester.store
.znodeWorkingPath, -1);
fail("Shouldn't be able to delete path");
- } catch (Exception e) {/* expected behavior */}
+ } catch (Exception e) {/* expected behavior */
+ }
}
- @Test (timeout = 20000)
+ @Test(timeout = 20000)
public void testInvalidZKAclConfiguration() {
TestZKClient zkClientTester = new TestZKClient();
YarnConfiguration conf = new YarnConfiguration();
|
a6fd48ba12e0f82b3ea937227845a63e5c1f8bf7
|
hbase
|
HBASE-11499- AsyncProcess.buildDetailedErrorMessage concatenates strings using + in a loop- (Mike Drob)--
|
p
|
https://github.com/apache/hbase
|
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
index c184147d59dd..d1bcc0b2a77b 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
@@ -1407,23 +1407,24 @@ private void decActionCounter(int index) {
}
private String buildDetailedErrorMsg(String string, int index) {
- String error = string + "; called for " + index +
- ", actionsInProgress " + actionsInProgress.get() + "; replica gets: ";
+ StringBuilder error = new StringBuilder(128);
+ error.append(string).append("; called for ").append(index).append(", actionsInProgress ")
+ .append(actionsInProgress.get()).append("; replica gets: ");
if (replicaGetIndices != null) {
for (int i = 0; i < replicaGetIndices.length; ++i) {
- error += replicaGetIndices[i] + ", ";
+ error.append(replicaGetIndices[i]).append(", ");
}
} else {
- error += (hasAnyReplicaGets ? "all" : "none");
+ error.append(hasAnyReplicaGets ? "all" : "none");
}
- error += "; results ";
+ error.append("; results ");
if (results != null) {
for (int i = 0; i < results.length; ++i) {
Object o = results[i];
- error += ((o == null) ? "null" : o.toString()) + ", ";
+ error.append(((o == null) ? "null" : o.toString())).append(", ");
}
}
- return error;
+ return error.toString();
}
@Override
|
55eb41292d2989225b4c4c012a0b34f2edfd54b5
|
camel
|
Fix test error reported by TeamCity--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@739402 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/components/camel-rss/src/test/java/org/apache/camel/dataformat/rss/RssDataFormatTest.java b/components/camel-rss/src/test/java/org/apache/camel/dataformat/rss/RssDataFormatTest.java
index f945699c3f6ee..15b5c9d1fb6fd 100644
--- a/components/camel-rss/src/test/java/org/apache/camel/dataformat/rss/RssDataFormatTest.java
+++ b/components/camel-rss/src/test/java/org/apache/camel/dataformat/rss/RssDataFormatTest.java
@@ -59,9 +59,9 @@ protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
// START SNIPPET: ex
- from("rss:file:src/test/data/rss20.xml?splitEntries=false&consumer.delay=100").marshal().rss().to("mock:marshal");
+ from("rss:file:src/test/data/rss20.xml?splitEntries=false&consumer.delay=1000").marshal().rss().to("mock:marshal");
// END SNIPPET: ex
- from("rss:file:src/test/data/rss20.xml?splitEntries=false&consumer.delay=100").marshal().rss().unmarshal().rss().to("mock:unmarshal");
+ from("rss:file:src/test/data/rss20.xml?splitEntries=false&consumer.delay=1000").marshal().rss().unmarshal().rss().to("mock:unmarshal");
}
};
}
|
13c851fc730cc900605f28582caeb12b8dcc89d9
|
Mylyn Reviews
|
322734: Open Review Compare in another editor
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
index 07d8d272..772324ca 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
@@ -10,18 +10,21 @@
*******************************************************************************/
package org.eclipse.mylyn.reviews.ui.editors;
+import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.eclipse.compare.CompareConfiguration;
+import org.eclipse.compare.CompareEditorInput;
import org.eclipse.compare.CompareUI;
-import org.eclipse.compare.contentmergeviewer.TextMergeViewer;
import org.eclipse.compare.patch.IFilePatch2;
import org.eclipse.compare.patch.PatchConfiguration;
-import org.eclipse.compare.structuremergeviewer.DiffNode;
+import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.CompositeImageDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
@@ -46,7 +49,6 @@
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
-import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Image;
@@ -55,7 +57,6 @@
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
@@ -69,11 +70,6 @@
public class ReviewTaskEditorPart extends AbstractTaskEditorPart {
public static final String ID_PART_REVIEW = "org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPart"; //$NON-NLS-1$
private TableViewer fileList;
- private Viewer viewer;
- private boolean viewerInitialized;
- private int[] weights;
- private SashForm sashComposite;
- private CompareConfiguration configuration;
private Composite composite;
public ReviewTaskEditorPart() {
@@ -95,13 +91,9 @@ public void createControl(Composite parent, FormToolkit toolkit) {
composite.setLayout(new GridLayout(1, true));
- sashComposite = new SashForm(composite, SWT.HORIZONTAL);
- sashComposite
- .setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- fileList = new TableViewer(sashComposite);
+ fileList = new TableViewer(composite);
fileList.getControl().setLayoutData(
- new GridData(SWT.DEFAULT, SWT.FILL, false, true));
+ new GridData(SWT.FILL, SWT.FILL, true, true));
TableViewerColumn column = new TableViewerColumn(fileList, SWT.LEFT);
column.getColumn().setText("");
@@ -173,49 +165,47 @@ public Object[] getElements(Object inputElement) {
return model;
}
});
+ fileList.addDoubleClickListener(new IDoubleClickListener() {
- fileList.addSelectionChangedListener(new ISelectionChangedListener() {
-
- public void selectionChanged(SelectionChangedEvent event) {
+ public void doubleClick(DoubleClickEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof IStructuredSelection) {
IStructuredSelection sel = (IStructuredSelection) selection;
if (sel.getFirstElement() instanceof ReviewDiffModel) {
- ReviewDiffModel diffModel = ((ReviewDiffModel) sel
+ final ReviewDiffModel diffModel = ((ReviewDiffModel) sel
.getFirstElement());
if (diffModel.canReview()) {
- weights = sashComposite.getWeights();
- Viewer newViewer = CompareUI.findContentViewer(
- viewerInitialized ? viewer : null,
- diffModel.getCompareInput(), sashComposite,
- configuration);
- if (newViewer != null && newViewer != viewer) {
- viewer.getControl().dispose();
- viewer = newViewer;
- configureLayoutForDiffViewer();
- viewer.setInput(diffModel.getCompareInput());
- }
+ CompareConfiguration configuration = new CompareConfiguration();
+ configuration.setLeftEditable(false);
+ configuration.setRightEditable(false);
+ configuration
+ .setLeftLabel(Messages.EditorSupport_Original);
+ configuration
+ .setRightLabel(Messages.EditorSupport_Patched);
+ configuration.setProperty(
+ CompareConfiguration.IGNORE_WHITESPACE,
+ false);
+ configuration
+ .setProperty(
+ CompareConfiguration.USE_OUTLINE_VIEW,
+ true);
+ CompareUI.openCompareEditor(new CompareEditorInput(
+ configuration) {
+
+ @Override
+ protected Object prepareInput(
+ IProgressMonitor monitor)
+ throws InvocationTargetException,
+ InterruptedException {
+ return diffModel.getCompareInput();
+ }
+ }, true);
}
}
}
}
});
setInput();
- configuration = new CompareConfiguration();
- configuration.setLeftEditable(false);
- configuration.setRightEditable(false);
- configuration.setLeftLabel(Messages.EditorSupport_Original);
- configuration.setRightLabel(Messages.EditorSupport_Patched);
- configuration
- .setProperty(CompareConfiguration.IGNORE_WHITESPACE, false);
- configuration.setProperty(CompareConfiguration.USE_OUTLINE_VIEW, true);
- // TODO
-
- viewerInitialized = false;
- viewer = new TextMergeViewer(sashComposite, SWT.BORDER, configuration);
- weights = new int[] { 1, 3 };
- configureLayoutForDiffViewer();
- viewer.setInput(getDiffEditorNullInput());
createResultFields(composite, toolkit);
@@ -254,10 +244,11 @@ private void createResultFields(Composite composite, FormToolkit toolkit) {
Composite resultComposite = toolkit.createComposite(composite);
toolkit.paintBordersFor(resultComposite);
resultComposite.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true,
- false));
- resultComposite.setLayout(new GridLayout(2, false));
+ false));
+ resultComposite.setLayout(new GridLayout(2, false));
- toolkit.createLabel(resultComposite, "Rating").setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
+ toolkit.createLabel(resultComposite, "Rating").setForeground(
+ toolkit.getColors().getColor(IFormColors.TITLE));
CCombo ratingsCombo = new CCombo(resultComposite, SWT.READ_ONLY
| SWT.FLAT);
ratingsCombo.setData(FormToolkit.KEY_DRAW_BORDER,
@@ -294,7 +285,8 @@ public Image getImage(Object element) {
ratingList.getControl().setLayoutData(
new GridData(SWT.LEFT, SWT.TOP, false, false));
- toolkit.createLabel(resultComposite, "Review comment").setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
+ toolkit.createLabel(resultComposite, "Review comment").setForeground(
+ toolkit.getColors().getColor(IFormColors.TITLE));
final Text commentText = toolkit.createText(resultComposite, "",
SWT.BORDER | SWT.MULTI);
GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false);
@@ -351,15 +343,6 @@ private Review parseFromAttachments() {
return null;
}
- private void configureLayoutForDiffViewer() {
- viewer.getControl().setLayoutData(
- new GridData(SWT.FILL, SWT.FILL, true, true));
- if (getControl() != null) {
- ((Composite) this.getControl()).layout(true);
- }
- sashComposite.setWeights(weights);
- }
-
/**
* Retrieves the review from the review data manager and fills the left
* table with the files.
@@ -372,10 +355,6 @@ private void setInput() {
}
}
- private DiffNode getDiffEditorNullInput() {
- return new DiffNode(new DiffNode(SWT.LEFT), new DiffNode(SWT.RIGHT));
- }
-
private static class MissingFile extends CompositeImageDescriptor {
ISharedImages sharedImages = PlatformUI.getWorkbench()
.getSharedImages();
@@ -433,10 +412,6 @@ private ImageData getBaseImageData() {
}
- public Control getSashComposite() {
- return sashComposite;
- }
-
@Override
protected void fillToolBar(ToolBarManager manager) {
// Depends on 288171
|
0f92fdd8e6422d5b79c610a7fd8409d222315a49
|
ReactiveX-RxJava
|
RunAsync method for outputting multiple values--
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/Async.java b/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/Async.java
index e091e78a9c..4f04f5fb47 100644
--- a/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/Async.java
+++ b/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/Async.java
@@ -20,10 +20,16 @@
import java.util.concurrent.FutureTask;
import rx.Observable;
+import rx.Observer;
import rx.Scheduler;
import rx.Scheduler.Inner;
+import rx.Subscriber;
+import rx.Subscription;
import rx.schedulers.Schedulers;
import rx.subjects.AsyncSubject;
+import rx.subjects.PublishSubject;
+import rx.subjects.Subject;
+import rx.subscriptions.SerialSubscription;
import rx.util.async.operators.Functionals;
import rx.util.async.operators.OperationDeferFuture;
import rx.util.async.operators.OperationForEachFuture;
@@ -1711,4 +1717,54 @@ public static <R> Observable<R> fromCallable(Callable<? extends R> callable, Sch
public static <R> Observable<R> fromRunnable(final Runnable run, final R result, Scheduler scheduler) {
return Observable.create(OperationFromFunctionals.fromRunnable(run, result)).subscribeOn(scheduler);
}
+ /**
+ * Runs the provided action on the given scheduler and allows propagation
+ * of multiple events to the observers of the returned StoppableObservable.
+ * The action is immediately executed and unobserved values will be lost.
+ * @param <T> the output value type
+ * @param scheduler the scheduler where the action is executed
+ * @param action the action to execute, receives an Observer where the events can be pumped
+ * and a Subscription which lets check for cancellation condition.
+ * @return an Observable which provides a Subscription interface to cancel the action
+ */
+ public static <T> StoppableObservable<T> runAsync(Scheduler scheduler,
+ final Action2<? super Observer<? super T>, ? super Subscription> action) {
+ return runAsync(scheduler, PublishSubject.<T>create(), action);
+ }
+ /**
+ * Runs the provided action on the given scheduler and allows propagation
+ * of multiple events to the observers of the returned StoppableObservable.
+ * The action is immediately executed and unobserved values might be lost,
+ * depending on the subject type used.
+ * @param <T> the output value of the action
+ * @param <U> the output type of the observable sequence
+ * @param scheduler the scheduler where the action is executed
+ * @param subject the subject to use to distribute values emitted by the action
+ * @param action the action to execute, receives an Observer where the events can be pumped
+ * and a Subscription which lets check for cancellation condition.
+ * @return an Observable which provides a Subscription interface to cancel the action
+ */
+ public static <T, U> StoppableObservable<U> runAsync(Scheduler scheduler,
+ final Subject<T, U> subject,
+ final Action2<? super Observer<? super T>, ? super Subscription> action) {
+ final SerialSubscription csub = new SerialSubscription();
+
+ StoppableObservable<U> co = new StoppableObservable<U>(new Observable.OnSubscribe<U>() {
+ @Override
+ public void call(Subscriber<? super U> t1) {
+ subject.subscribe(t1);
+ }
+ }, csub);
+
+ csub.set(scheduler.schedule(new Action1<Inner>() {
+ @Override
+ public void call(Inner t1) {
+ if (!csub.isUnsubscribed()) {
+ action.call(subject, csub);
+ }
+ }
+ }));
+
+ return co;
+ }
}
diff --git a/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/StoppableObservable.java b/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/StoppableObservable.java
new file mode 100644
index 0000000000..ebd9538ed5
--- /dev/null
+++ b/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/StoppableObservable.java
@@ -0,0 +1,41 @@
+/**
+ * Copyright 2014 Netflix, 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 rx.util.async;
+
+import rx.Observable;
+import rx.Subscription;
+
+/**
+ * An Observable which provides a Subscription interface to signal a stop
+ * condition to an asynchronous task.
+ */
+public class StoppableObservable<T> extends Observable<T> implements Subscription {
+ private final Subscription token;
+ public StoppableObservable(Observable.OnSubscribe<T> onSubscribe, Subscription token) {
+ super(onSubscribe);
+ this.token = token;
+ }
+
+ @Override
+ public boolean isUnsubscribed() {
+ return token.isUnsubscribed();
+ }
+
+ @Override
+ public void unsubscribe() {
+ token.unsubscribe();
+ }
+}
diff --git a/rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java b/rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java
index d83d01b047..3146681c5f 100644
--- a/rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java
+++ b/rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java
@@ -16,8 +16,8 @@
package rx.util.async;
+import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.*;
-import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.util.concurrent.TimeUnit;
@@ -35,6 +35,7 @@
import rx.Observable;
import rx.Observer;
+import rx.Subscription;
import rx.observers.TestObserver;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;
@@ -818,4 +819,47 @@ public String answer(InvocationOnMock invocation) throws Throwable {
verify(func, times(1)).call();
}
+ @Test
+ public void testRunAsync() throws InterruptedException {
+ final CountDownLatch cdl = new CountDownLatch(1);
+ final CountDownLatch cdl2 = new CountDownLatch(1);
+ Action2<Observer<? super Integer>, Subscription> action = new Action2<Observer<? super Integer>, Subscription>() {
+ @Override
+ public void call(Observer<? super Integer> t1, Subscription t2) {
+ try {
+ cdl.await();
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+ for (int i = 0; i < 10 && !t2.isUnsubscribed(); i++) {
+ t1.onNext(i);
+ }
+ t1.onCompleted();
+ cdl2.countDown();
+ }
+ };
+
+ @SuppressWarnings("unchecked")
+ Observer<Object> o = mock(Observer.class);
+ InOrder inOrder = inOrder(o);
+
+ StoppableObservable<Integer> so = Async.<Integer>runAsync(Schedulers.io(), action);
+
+ so.subscribe(o);
+
+ cdl.countDown();
+
+ if (!cdl2.await(2, TimeUnit.SECONDS)) {
+ fail("Didn't complete");
+ }
+
+ for (int i = 0; i < 10; i++) {
+ inOrder.verify(o).onNext(i);
+ }
+ inOrder.verify(o).onCompleted();
+ inOrder.verifyNoMoreInteractions();
+ verify(o, never()).onError(any(Throwable.class));
+
+ }
}
|
8b9fdf23e2196dce9c956ba9088dd9b3146be60c
|
camel
|
CAMEL-4244 Add ThreadPoolProfileBuilder and- change ThreadPoolFactory to use the ThreadPoolProfile--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1159342 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java
new file mode 100644
index 0000000000000..8f3af7e1d17d9
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java
@@ -0,0 +1,86 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.builder;
+
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.ThreadPoolRejectedPolicy;
+import org.apache.camel.spi.ThreadPoolProfile;
+
+public class ThreadPoolProfileBuilder {
+ private final ThreadPoolProfile profile;
+
+ public ThreadPoolProfileBuilder(String id) {
+ this.profile = new ThreadPoolProfile(id);
+ }
+
+ public ThreadPoolProfileBuilder(String id, ThreadPoolProfile origProfile) {
+ this.profile = origProfile.clone();
+ this.profile.setId(id);
+ }
+
+ public ThreadPoolProfileBuilder defaultProfile(Boolean defaultProfile) {
+ this.profile.setDefaultProfile(defaultProfile);
+ return this;
+ }
+
+
+ public ThreadPoolProfileBuilder poolSize(Integer poolSize) {
+ profile.setPoolSize(poolSize);
+ return this;
+ }
+
+ public ThreadPoolProfileBuilder maxPoolSize(Integer maxPoolSize) {
+ profile.setMaxPoolSize(maxPoolSize);
+ return this;
+ }
+
+ public ThreadPoolProfileBuilder keepAliveTime(Long keepAliveTime, TimeUnit timeUnit) {
+ profile.setKeepAliveTime(keepAliveTime);
+ profile.setTimeUnit(timeUnit);
+ return this;
+ }
+
+ public ThreadPoolProfileBuilder keepAliveTime(Long keepAliveTime) {
+ profile.setKeepAliveTime(keepAliveTime);
+ return this;
+ }
+
+ public ThreadPoolProfileBuilder maxQueueSize(Integer maxQueueSize) {
+ if (maxQueueSize != null) {
+ profile.setMaxQueueSize(maxQueueSize);
+ }
+ return this;
+ }
+
+ public ThreadPoolProfileBuilder rejectedPolicy(ThreadPoolRejectedPolicy rejectedPolicy) {
+ profile.setRejectedPolicy(rejectedPolicy);
+ return this;
+ }
+
+ /**
+ * Builds the new thread pool
+ *
+ * @return the created thread pool
+ * @throws Exception is thrown if error building the thread pool
+ */
+ public ThreadPoolProfile build() {
+ return profile;
+ }
+
+
+}
diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java
index fe2f4e0907ff4..f874a7b6360c4 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java
@@ -22,7 +22,6 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
-import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
@@ -30,6 +29,7 @@
import org.apache.camel.CamelContext;
import org.apache.camel.ThreadPoolRejectedPolicy;
+import org.apache.camel.builder.ThreadPoolProfileBuilder;
import org.apache.camel.model.OptionalIdentifiedDefinition;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.ProcessorDefinitionHelper;
@@ -56,21 +56,20 @@ public class DefaultExecutorServiceManager extends ServiceSupport implements Exe
private String threadNamePattern;
private String defaultThreadPoolProfileId = "defaultThreadPoolProfile";
private final Map<String, ThreadPoolProfile> threadPoolProfiles = new HashMap<String, ThreadPoolProfile>();
+ private ThreadPoolProfile builtIndefaultProfile;
public DefaultExecutorServiceManager(CamelContext camelContext) {
this.camelContext = camelContext;
- // create and register the default profile
- ThreadPoolProfile defaultProfile = new ThreadPoolProfile(defaultThreadPoolProfileId);
- // the default profile has the following values
- defaultProfile.setDefaultProfile(true);
- defaultProfile.setPoolSize(10);
- defaultProfile.setMaxPoolSize(20);
- defaultProfile.setKeepAliveTime(60L);
- defaultProfile.setTimeUnit(TimeUnit.SECONDS);
- defaultProfile.setMaxQueueSize(1000);
- defaultProfile.setRejectedPolicy(ThreadPoolRejectedPolicy.CallerRuns);
- registerThreadPoolProfile(defaultProfile);
+ builtIndefaultProfile = new ThreadPoolProfileBuilder(defaultThreadPoolProfileId)
+ .defaultProfile(true)
+ .poolSize(10)
+ .maxPoolSize(20)
+ .keepAliveTime(60L, TimeUnit.SECONDS)
+ .maxQueueSize(1000)
+ .rejectedPolicy(ThreadPoolRejectedPolicy.CallerRuns)
+ .build();
+ registerThreadPoolProfile(builtIndefaultProfile);
}
@Override
@@ -102,46 +101,12 @@ public ThreadPoolProfile getDefaultThreadPoolProfile() {
@Override
public void setDefaultThreadPoolProfile(ThreadPoolProfile defaultThreadPoolProfile) {
- ThreadPoolProfile oldProfile = threadPoolProfiles.remove(defaultThreadPoolProfileId);
- if (oldProfile != null) {
- // the old is no longer default
- oldProfile.setDefaultProfile(false);
-
- // fallback and use old default values for new default profile if absent (convention over configuration)
- if (defaultThreadPoolProfile.getKeepAliveTime() == null) {
- defaultThreadPoolProfile.setKeepAliveTime(oldProfile.getKeepAliveTime());
- }
- if (defaultThreadPoolProfile.getMaxPoolSize() == null) {
- defaultThreadPoolProfile.setMaxPoolSize(oldProfile.getMaxPoolSize());
- }
- if (defaultThreadPoolProfile.getRejectedPolicy() == null) {
- defaultThreadPoolProfile.setRejectedPolicy(oldProfile.getRejectedPolicy());
- }
- if (defaultThreadPoolProfile.getMaxQueueSize() == null) {
- defaultThreadPoolProfile.setMaxQueueSize(oldProfile.getMaxQueueSize());
- }
- if (defaultThreadPoolProfile.getPoolSize() == null) {
- defaultThreadPoolProfile.setPoolSize(oldProfile.getPoolSize());
- }
- if (defaultThreadPoolProfile.getTimeUnit() == null) {
- defaultThreadPoolProfile.setTimeUnit(oldProfile.getTimeUnit());
- }
- }
-
- // validate that all options has been given as its mandatory for a default thread pool profile
- // as it is used as fallback for other profiles if they do not have that particular value
- ObjectHelper.notEmpty(defaultThreadPoolProfile.getId(), "id", defaultThreadPoolProfile);
- ObjectHelper.notNull(defaultThreadPoolProfile.getKeepAliveTime(), "keepAliveTime", defaultThreadPoolProfile);
- ObjectHelper.notNull(defaultThreadPoolProfile.getMaxPoolSize(), "maxPoolSize", defaultThreadPoolProfile);
- ObjectHelper.notNull(defaultThreadPoolProfile.getMaxQueueSize(), "maxQueueSize", defaultThreadPoolProfile);
- ObjectHelper.notNull(defaultThreadPoolProfile.getPoolSize(), "poolSize", defaultThreadPoolProfile);
- ObjectHelper.notNull(defaultThreadPoolProfile.getTimeUnit(), "timeUnit", defaultThreadPoolProfile);
+ threadPoolProfiles.remove(defaultThreadPoolProfileId);
+ defaultThreadPoolProfile.addDefaults(builtIndefaultProfile);
LOG.info("Using custom DefaultThreadPoolProfile: " + defaultThreadPoolProfile);
- // and replace with the new default profile
this.defaultThreadPoolProfileId = defaultThreadPoolProfile.getId();
- // and mark the new profile as default
defaultThreadPoolProfile.setDefaultProfile(true);
registerThreadPoolProfile(defaultThreadPoolProfile);
}
@@ -170,12 +135,7 @@ public ExecutorService newDefaultThreadPool(Object source, String name) {
@Override
public ScheduledExecutorService newDefaultScheduledThreadPool(Object source, String name) {
- ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile();
-
- ThreadFactory threadFactory = createThreadFactory(name, true);
- ScheduledExecutorService executorService = threadPoolFactory.newScheduledThreadPool(defaultProfile.getPoolSize(), threadFactory);
- onThreadPoolCreated(executorService, source, null);
- return executorService;
+ return newScheduledThreadPool(source, name, getDefaultThreadPoolProfile());
}
@Override
@@ -194,35 +154,22 @@ public ExecutorService newThreadPool(Object source, String name, ThreadPoolProfi
ObjectHelper.notNull(profile, "ThreadPoolProfile");
ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile();
- // fallback to use values from default profile if not specified
- Integer poolSize = profile.getPoolSize() != null ? profile.getPoolSize() : defaultProfile.getPoolSize();
- Integer maxPoolSize = profile.getMaxPoolSize() != null ? profile.getMaxPoolSize() : defaultProfile.getMaxPoolSize();
- Long keepAliveTime = profile.getKeepAliveTime() != null ? profile.getKeepAliveTime() : defaultProfile.getKeepAliveTime();
- TimeUnit timeUnit = profile.getTimeUnit() != null ? profile.getTimeUnit() : defaultProfile.getTimeUnit();
- Integer maxQueueSize = profile.getMaxQueueSize() != null ? profile.getMaxQueueSize() : defaultProfile.getMaxQueueSize();
- RejectedExecutionHandler handler = profile.getRejectedExecutionHandler() != null ? profile.getRejectedExecutionHandler() : defaultProfile.getRejectedExecutionHandler();
+ profile.addDefaults(defaultProfile);
ThreadFactory threadFactory = createThreadFactory(name, true);
- ExecutorService executorService = threadPoolFactory.newThreadPool(poolSize, maxPoolSize,
- keepAliveTime, timeUnit, maxQueueSize, handler, threadFactory);
+ ExecutorService executorService = threadPoolFactory.newThreadPool(profile, threadFactory);
onThreadPoolCreated(executorService, source, profile.getId());
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Created new ThreadPool for source: {} with name: {}. -> {}", new Object[]{source, name, executorService});
+ }
+
return executorService;
}
@Override
public ExecutorService newThreadPool(Object source, String name, int poolSize, int maxPoolSize) {
- ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile();
-
- // fallback to use values from default profile
- ExecutorService answer = threadPoolFactory.newThreadPool(poolSize, maxPoolSize,
- defaultProfile.getKeepAliveTime(), defaultProfile.getTimeUnit(), defaultProfile.getMaxQueueSize(),
- defaultProfile.getRejectedExecutionHandler(), new CamelThreadFactory(threadNamePattern, name, true));
- onThreadPoolCreated(answer, source, null);
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Created new ThreadPool for source: {} with name: {}. -> {}", new Object[]{source, name, answer});
- }
- return answer;
+ ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).maxPoolSize(maxPoolSize).build();
+ return newThreadPool(source, name, profile);
}
@Override
@@ -232,7 +179,7 @@ public ExecutorService newSingleThreadExecutor(Object source, String name) {
@Override
public ExecutorService newCachedThreadPool(Object source, String name) {
- ExecutorService answer = threadPoolFactory.newCachedThreadPool(new CamelThreadFactory(threadNamePattern, name, true));
+ ExecutorService answer = threadPoolFactory.newCachedThreadPool(createThreadFactory(name, true));
onThreadPoolCreated(answer, source, null);
if (LOG.isDebugEnabled()) {
@@ -243,29 +190,32 @@ public ExecutorService newCachedThreadPool(Object source, String name) {
@Override
public ExecutorService newFixedThreadPool(Object source, String name, int poolSize) {
- ExecutorService answer = threadPoolFactory.newFixedThreadPool(poolSize, new CamelThreadFactory(threadNamePattern, name, true));
- onThreadPoolCreated(answer, source, null);
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Created new FixedThreadPool for source: {} with name: {}. -> {}", new Object[]{source, name, answer});
- }
- return answer;
+ ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).maxPoolSize(poolSize).keepAliveTime(0L).build();
+ return newThreadPool(source, name, profile);
}
@Override
public ScheduledExecutorService newSingleThreadScheduledExecutor(Object source, String name) {
return newScheduledThreadPool(source, name, 1);
}
-
+
@Override
- public ScheduledExecutorService newScheduledThreadPool(Object source, String name, int poolSize) {
- ScheduledExecutorService answer = threadPoolFactory.newScheduledThreadPool(poolSize, new CamelThreadFactory(threadNamePattern, name, true));
+ public ScheduledExecutorService newScheduledThreadPool(Object source, String name, ThreadPoolProfile profile) {
+ profile.addDefaults(getDefaultThreadPoolProfile());
+ ScheduledExecutorService answer = threadPoolFactory.newScheduledThreadPool(profile, createThreadFactory(name, true));
onThreadPoolCreated(answer, source, null);
if (LOG.isDebugEnabled()) {
LOG.debug("Created new ScheduledThreadPool for source: {} with name: {}. -> {}", new Object[]{source, name, answer});
}
return answer;
+
+ }
+
+ @Override
+ public ScheduledExecutorService newScheduledThreadPool(Object source, String name, int poolSize) {
+ ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).build();
+ return newScheduledThreadPool(source, name, profile);
}
@Override
diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java
index 3cbb0fa75bd59..318283fa01efb 100644
--- a/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java
+++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java
@@ -28,6 +28,7 @@
import java.util.concurrent.TimeUnit;
import org.apache.camel.spi.ThreadPoolFactory;
+import org.apache.camel.spi.ThreadPoolProfile;
/**
* Factory for thread pools that uses the JDK {@link Executors} for creating the thread pools.
@@ -37,13 +38,16 @@ public class DefaultThreadPoolFactory implements ThreadPoolFactory {
public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return Executors.newCachedThreadPool(threadFactory);
}
-
- public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) {
- return Executors.newFixedThreadPool(poolSize, threadFactory);
- }
-
- public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException {
- return Executors.newScheduledThreadPool(corePoolSize, threadFactory);
+
+ @Override
+ public ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory factory) {
+ return newThreadPool(profile.getPoolSize(),
+ profile.getMaxPoolSize(),
+ profile.getKeepAliveTime(),
+ profile.getTimeUnit(),
+ profile.getMaxQueueSize(),
+ profile.getRejectedExecutionHandler(),
+ factory);
}
public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit,
@@ -84,5 +88,13 @@ public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long kee
answer.setRejectedExecutionHandler(rejectedExecutionHandler);
return answer;
}
+
+ /* (non-Javadoc)
+ * @see org.apache.camel.impl.ThreadPoolFactory#newScheduledThreadPool(java.lang.Integer, java.util.concurrent.ThreadFactory)
+ */
+ @Override
+ public ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) {
+ return Executors.newScheduledThreadPool(profile.getPoolSize(), threadFactory);
+ }
}
diff --git a/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java
index fcddf40314609..aa5ef9f585d87 100644
--- a/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java
+++ b/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java
@@ -20,6 +20,7 @@
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
+
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@@ -29,10 +30,11 @@
import org.apache.camel.Processor;
import org.apache.camel.ThreadPoolRejectedPolicy;
-import org.apache.camel.builder.ThreadPoolBuilder;
+import org.apache.camel.builder.ThreadPoolProfileBuilder;
import org.apache.camel.builder.xml.TimeUnitAdapter;
import org.apache.camel.processor.Pipeline;
import org.apache.camel.processor.ThreadsProcessor;
+import org.apache.camel.spi.ExecutorServiceManager;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.spi.ThreadPoolProfile;
@@ -81,24 +83,16 @@ public Processor createProcessor(RouteContext routeContext) throws Exception {
executorService = ProcessorDefinitionHelper.getConfiguredExecutorService(routeContext, name, this);
// if no explicit then create from the options
if (executorService == null) {
- ThreadPoolProfile profile = routeContext.getCamelContext().getExecutorServiceManager().getDefaultThreadPoolProfile();
- // use the default thread pool profile as base and then override with values
- // use a custom pool based on the settings
- int core = getPoolSize() != null ? getPoolSize() : profile.getPoolSize();
- int max = getMaxPoolSize() != null ? getMaxPoolSize() : profile.getMaxPoolSize();
- long keepAlive = getKeepAliveTime() != null ? getKeepAliveTime() : profile.getKeepAliveTime();
- int maxQueue = getMaxQueueSize() != null ? getMaxQueueSize() : profile.getMaxQueueSize();
- TimeUnit tu = getTimeUnit() != null ? getTimeUnit() : profile.getTimeUnit();
- ThreadPoolRejectedPolicy rejected = getRejectedPolicy() != null ? getRejectedPolicy() : profile.getRejectedPolicy();
-
+ ExecutorServiceManager manager = routeContext.getCamelContext().getExecutorServiceManager();
// create the thread pool using a builder
- executorService = new ThreadPoolBuilder(routeContext.getCamelContext())
- .poolSize(core)
- .maxPoolSize(max)
- .keepAliveTime(keepAlive, tu)
- .maxQueueSize(maxQueue)
- .rejectedPolicy(rejected)
- .build(this, name);
+ ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name)
+ .poolSize(getPoolSize())
+ .maxPoolSize(getMaxPoolSize())
+ .keepAliveTime(getKeepAliveTime(), getTimeUnit())
+ .maxQueueSize(getMaxQueueSize())
+ .rejectedPolicy(getRejectedPolicy())
+ .build();
+ executorService = manager.newThreadPool(this, name, profile);
}
ThreadsProcessor thread = new ThreadsProcessor(routeContext.getCamelContext(), executorService);
diff --git a/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java b/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java
index 49efb0720c1b5..11070a96e0dcd 100644
--- a/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java
+++ b/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java
@@ -220,6 +220,8 @@ public interface ExecutorServiceManager extends ShutdownableService {
* @return the created thread pool
*/
ScheduledExecutorService newSingleThreadScheduledExecutor(Object source, String name);
+
+ ScheduledExecutorService newScheduledThreadPool(Object source, String name, ThreadPoolProfile profile);
/**
* Shutdown the given executor service.
@@ -237,4 +239,5 @@ public interface ExecutorServiceManager extends ShutdownableService {
* @see java.util.concurrent.ExecutorService#shutdownNow()
*/
List<Runnable> shutdownNow(ExecutorService executorService);
+
}
diff --git a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java
index c97f5ab68ea06..cc31ad23ad938 100644
--- a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java
+++ b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java
@@ -17,73 +17,41 @@
package org.apache.camel.spi;
import java.util.concurrent.ExecutorService;
-import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
/**
- * Factory to crate {@link ExecutorService} and {@link ScheduledExecutorService} instances
- * <p/>
- * This interface allows to customize the creation of these objects to adapt Camel
- * for application servers and other environments where thread pools should
- * not be created with the JDK methods, as provided by the {@link org.apache.camel.impl.DefaultThreadPoolFactory}.
- *
- * @see ExecutorServiceManager
+ * Creates ExecutorService and ScheduledExecutorService objects that work with a thread pool for a given ThreadPoolProfile and ThreadFactory.
+ *
+ * This interface allows to customize the creation of these objects to adapt camel for application servers and other environments where thread pools
+ * should not be created with the jdk methods
*/
public interface ThreadPoolFactory {
-
/**
* Creates a new cached thread pool
* <p/>
* The cached thread pool is a term from the JDK from the method {@link java.util.concurrent.Executors#newCachedThreadPool()}.
- * Implementators of this interface, may create a different kind of pool than the cached, or check the source code
- * of the JDK to create a pool using the same settings.
+ * Typically it will have no size limit (this is why it is handled separately
*
* @param threadFactory factory for creating threads
* @return the created thread pool
*/
ExecutorService newCachedThreadPool(ThreadFactory threadFactory);
-
+
/**
- * Creates a new fixed thread pool
- * <p/>
- * The fixed thread pool is a term from the JDK from the method {@link java.util.concurrent.Executors#newFixedThreadPool(int)}.
- * Implementators of this interface, may create a different kind of pool than the fixed, or check the source code
- * of the JDK to create a pool using the same settings.
- *
- * @param poolSize the number of threads in the pool
- * @param threadFactory factory for creating threads
- * @return the created thread pool
+ * Create a thread pool using the given thread pool profile
+ *
+ * @param profile
+ * @param threadFactory
+ * @return
*/
- ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory);
-
+ ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory);
+
/**
- * Creates a new scheduled thread pool
- *
- * @param corePoolSize the core pool size
- * @param threadFactory factory for creating threads
- * @return the created thread pool
- * @throws IllegalArgumentException if parameters is not valid
- */
- ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException;
-
- /**
- * Creates a new thread pool
- *
- * @param corePoolSize the core pool size
- * @param maxPoolSize the maximum pool size
- * @param keepAliveTime keep alive time
- * @param timeUnit keep alive time unit
- * @param maxQueueSize the maximum number of tasks in the queue, use <tt>Integer.MAX_VALUE</tt> or <tt>-1</tt> to indicate unbounded
- * @param rejectedExecutionHandler the handler for tasks which cannot be executed by the thread pool.
- * If <tt>null</tt> is provided then {@link java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy CallerRunsPolicy} is used.
- * @param threadFactory factory for creating threads
- * @return the created thread pool
- * @throws IllegalArgumentException if parameters is not valid
+ * Create a scheduled thread pool using the given thread pool profile
+ * @param profile
+ * @param threadFactory
+ * @return
*/
- ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit,
- int maxQueueSize, RejectedExecutionHandler rejectedExecutionHandler,
- ThreadFactory threadFactory) throws IllegalArgumentException;
-
-}
+ ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory);
+}
\ No newline at end of file
diff --git a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java
index c4f2e933477b0..87b9a01fd991b 100644
--- a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java
+++ b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java
@@ -219,6 +219,49 @@ public void setRejectedPolicy(ThreadPoolRejectedPolicy rejectedPolicy) {
this.rejectedPolicy = rejectedPolicy;
}
+ /**
+ * Overwrites each attribute that is null with the attribute from defaultProfile
+ *
+ * @param defaultProfile2
+ */
+ public void addDefaults(ThreadPoolProfile defaultProfile2) {
+ if (defaultProfile2 == null) {
+ return;
+ }
+ if (poolSize == null) {
+ poolSize = defaultProfile2.getPoolSize();
+ }
+ if (maxPoolSize == null) {
+ maxPoolSize = defaultProfile2.getMaxPoolSize();
+ }
+ if (keepAliveTime == null) {
+ keepAliveTime = defaultProfile2.getKeepAliveTime();
+ }
+ if (timeUnit == null) {
+ timeUnit = defaultProfile2.getTimeUnit();
+ }
+ if (maxQueueSize == null) {
+ maxQueueSize = defaultProfile2.getMaxQueueSize();
+ }
+ if (rejectedPolicy == null) {
+ rejectedPolicy = defaultProfile2.getRejectedPolicy();
+ }
+ }
+
+ @Override
+ public ThreadPoolProfile clone() {
+ ThreadPoolProfile cloned = new ThreadPoolProfile();
+ cloned.setDefaultProfile(defaultProfile);
+ cloned.setId(id);
+ cloned.setKeepAliveTime(keepAliveTime);
+ cloned.setMaxPoolSize(maxPoolSize);
+ cloned.setMaxQueueSize(maxQueueSize);
+ cloned.setPoolSize(maxPoolSize);
+ cloned.setRejectedPolicy(rejectedPolicy);
+ cloned.setTimeUnit(timeUnit);
+ return cloned;
+ }
+
@Override
public String toString() {
return "ThreadPoolProfile[" + id + " (" + defaultProfile + ") size:" + poolSize + "-" + maxPoolSize
diff --git a/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java b/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java
index 6d26693cc0b2c..f5467c0ef541e 100644
--- a/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java
+++ b/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java
@@ -18,7 +18,6 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
-import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
@@ -54,18 +53,6 @@ public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return super.newCachedThreadPool(threadFactory);
}
- @Override
- public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) {
- invoked = true;
- return super.newFixedThreadPool(poolSize, threadFactory);
- }
-
- @Override
- public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException {
- invoked = true;
- return super.newScheduledThreadPool(corePoolSize, threadFactory);
- }
-
@Override
public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, int maxQueueSize,
RejectedExecutionHandler rejectedExecutionHandler, ThreadFactory threadFactory) throws IllegalArgumentException {
diff --git a/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java b/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java
index af9c1963afd91..75204f0f93e76 100644
--- a/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java
+++ b/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java
@@ -357,8 +357,8 @@ public void testNewFixedThreadPool() throws Exception {
ThreadPoolExecutor tp = assertIsInstanceOf(ThreadPoolExecutor.class, pool);
// a fixed dont use keep alive
- assertEquals(0, tp.getKeepAliveTime(TimeUnit.SECONDS));
- assertEquals(5, tp.getMaximumPoolSize());
+ assertEquals("keepAliveTime", 0, tp.getKeepAliveTime(TimeUnit.SECONDS));
+ assertEquals("maximumPoolSize", 5, tp.getMaximumPoolSize());
assertEquals(5, tp.getCorePoolSize());
assertFalse(tp.isShutdown());
@@ -373,8 +373,8 @@ public void testNewSingleThreadExecutor() throws Exception {
ThreadPoolExecutor tp = assertIsInstanceOf(ThreadPoolExecutor.class, pool);
// a single dont use keep alive
- assertEquals(0, tp.getKeepAliveTime(TimeUnit.SECONDS));
- assertEquals(1, tp.getMaximumPoolSize());
+ assertEquals("keepAliveTime", 0, tp.getKeepAliveTime(TimeUnit.SECONDS));
+ assertEquals("maximumPoolSize", 1, tp.getMaximumPoolSize());
assertEquals(1, tp.getCorePoolSize());
assertFalse(tp.isShutdown());
diff --git a/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java b/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java
index 47338594284c3..624ab8087eb55 100644
--- a/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java
+++ b/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java
@@ -25,8 +25,9 @@
import org.apache.camel.CamelContext;
import org.apache.camel.ThreadPoolRejectedPolicy;
-import org.apache.camel.builder.ThreadPoolBuilder;
+import org.apache.camel.builder.ThreadPoolProfileBuilder;
import org.apache.camel.builder.xml.TimeUnitAdapter;
+import org.apache.camel.spi.ThreadPoolProfile;
import org.apache.camel.util.CamelContextHelper;
/**
@@ -74,10 +75,14 @@ public ExecutorService getObject() throws Exception {
queueSize = CamelContextHelper.parseInteger(getCamelContext(), maxQueueSize);
}
- ExecutorService answer = new ThreadPoolBuilder(getCamelContext())
- .poolSize(size).maxPoolSize(max).keepAliveTime(keepAlive, getTimeUnit())
- .maxQueueSize(queueSize).rejectedPolicy(getRejectedPolicy())
- .build(getId(), getThreadName());
+ ThreadPoolProfile profile = new ThreadPoolProfileBuilder(getId())
+ .poolSize(size)
+ .maxPoolSize(max)
+ .keepAliveTime(keepAlive, timeUnit)
+ .maxQueueSize(queueSize)
+ .rejectedPolicy(rejectedPolicy)
+ .build();
+ ExecutorService answer = getCamelContext().getExecutorServiceManager().newThreadPool(getId(), getThreadName(), profile);
return answer;
}
diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java
index a756b06391406..31729538c3ce3 100644
--- a/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java
+++ b/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java
@@ -18,7 +18,6 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
-import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
@@ -56,18 +55,6 @@ public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return super.newCachedThreadPool(threadFactory);
}
- @Override
- public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) {
- invoked = true;
- return super.newFixedThreadPool(poolSize, threadFactory);
- }
-
- @Override
- public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException {
- invoked = true;
- return super.newScheduledThreadPool(corePoolSize, threadFactory);
- }
-
@Override
public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, int maxQueueSize,
RejectedExecutionHandler rejectedExecutionHandler, ThreadFactory threadFactory) throws IllegalArgumentException {
|
e3f99578304cb30f1b59c34a4193b9b700f3566a
|
hbase
|
HBASE-12176 WALCellCodec Encoders support for- non-KeyValue Cells (Anoop Sam John)--
|
a
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SecureWALCellCodec.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SecureWALCellCodec.java
index 504e9cbb00af..46f3b88fb2cd 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SecureWALCellCodec.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SecureWALCellCodec.java
@@ -30,6 +30,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.codec.KeyValueCodec;
import org.apache.hadoop.hbase.io.crypto.Decryptor;
import org.apache.hadoop.hbase.io.crypto.Encryption;
@@ -179,16 +180,11 @@ public EncryptedKvEncoder(OutputStream os, Encryptor encryptor) {
@Override
public void write(Cell cell) throws IOException {
- if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
if (encryptor == null) {
super.write(cell);
return;
}
- KeyValue kv = (KeyValue)cell;
- byte[] kvBuffer = kv.getBuffer();
- int offset = kv.getOffset();
-
byte[] iv = nextIv();
encryptor.setIv(iv);
encryptor.reset();
@@ -205,23 +201,27 @@ public void write(Cell cell) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream cout = encryptor.createEncryptionStream(baos);
+ int tlen = cell.getTagsLength();
// Write the KeyValue infrastructure as VInts.
- StreamUtils.writeRawVInt32(cout, kv.getKeyLength());
- StreamUtils.writeRawVInt32(cout, kv.getValueLength());
+ StreamUtils.writeRawVInt32(cout, KeyValueUtil.keyLength(cell));
+ StreamUtils.writeRawVInt32(cout, cell.getValueLength());
// To support tags
- StreamUtils.writeRawVInt32(cout, kv.getTagsLength());
+ StreamUtils.writeRawVInt32(cout, tlen);
// Write row, qualifier, and family
- StreamUtils.writeRawVInt32(cout, kv.getRowLength());
- cout.write(kvBuffer, kv.getRowOffset(), kv.getRowLength());
- StreamUtils.writeRawVInt32(cout, kv.getFamilyLength());
- cout.write(kvBuffer, kv.getFamilyOffset(), kv.getFamilyLength());
- StreamUtils.writeRawVInt32(cout, kv.getQualifierLength());
- cout.write(kvBuffer, kv.getQualifierOffset(), kv.getQualifierLength());
- // Write the rest
- int pos = kv.getTimestampOffset();
- int remainingLength = kv.getLength() + offset - pos;
- cout.write(kvBuffer, pos, remainingLength);
+ StreamUtils.writeRawVInt32(cout, cell.getRowLength());
+ cout.write(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
+ StreamUtils.writeRawVInt32(cout, cell.getFamilyLength());
+ cout.write(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
+ StreamUtils.writeRawVInt32(cout, cell.getQualifierLength());
+ cout.write(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
+ // Write the rest ie. ts, type, value and tags parts
+ StreamUtils.writeLong(cout, cell.getTimestamp());
+ cout.write(cell.getTypeByte());
+ cout.write(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
+ if (tlen > 0) {
+ cout.write(cell.getTagsArray(), cell.getTagsOffset(), tlen);
+ }
cout.close();
StreamUtils.writeRawVInt32(out, baos.size());
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java
index ae8613127f5a..89f4b869fc10 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java
@@ -27,6 +27,7 @@
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.codec.BaseDecoder;
import org.apache.hadoop.hbase.codec.BaseEncoder;
import org.apache.hadoop.hbase.codec.Codec;
@@ -190,41 +191,34 @@ public CompressedKvEncoder(OutputStream out, CompressionContext compression) {
@Override
public void write(Cell cell) throws IOException {
- if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
- KeyValue kv = (KeyValue)cell;
- byte[] kvBuffer = kv.getBuffer();
- int offset = kv.getOffset();
-
// We first write the KeyValue infrastructure as VInts.
- StreamUtils.writeRawVInt32(out, kv.getKeyLength());
- StreamUtils.writeRawVInt32(out, kv.getValueLength());
+ StreamUtils.writeRawVInt32(out, KeyValueUtil.keyLength(cell));
+ StreamUtils.writeRawVInt32(out, cell.getValueLength());
// To support tags
- int tagsLength = kv.getTagsLength();
+ int tagsLength = cell.getTagsLength();
StreamUtils.writeRawVInt32(out, tagsLength);
// Write row, qualifier, and family; use dictionary
// compression as they're likely to have duplicates.
- write(kvBuffer, kv.getRowOffset(), kv.getRowLength(), compression.rowDict);
- write(kvBuffer, kv.getFamilyOffset(), kv.getFamilyLength(), compression.familyDict);
- write(kvBuffer, kv.getQualifierOffset(), kv.getQualifierLength(), compression.qualifierDict);
+ write(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), compression.rowDict);
+ write(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
+ compression.familyDict);
+ write(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(),
+ compression.qualifierDict);
// Write timestamp, type and value as uncompressed.
- int pos = kv.getTimestampOffset();
- int tsTypeValLen = kv.getLength() + offset - pos;
- if (tagsLength > 0) {
- tsTypeValLen = tsTypeValLen - tagsLength - KeyValue.TAGS_LENGTH_SIZE;
- }
- assert tsTypeValLen > 0;
- out.write(kvBuffer, pos, tsTypeValLen);
+ StreamUtils.writeLong(out, cell.getTimestamp());
+ out.write(cell.getTypeByte());
+ out.write(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
if (tagsLength > 0) {
if (compression.tagCompressionContext != null) {
// Write tags using Dictionary compression
- compression.tagCompressionContext.compressTags(out, kvBuffer, kv.getTagsOffset(),
- tagsLength);
+ compression.tagCompressionContext.compressTags(out, cell.getTagsArray(),
+ cell.getTagsOffset(), tagsLength);
} else {
// Tag compression is disabled within the WAL compression. Just write the tags bytes as
// it is.
- out.write(kvBuffer, kv.getTagsOffset(), tagsLength);
+ out.write(cell.getTagsArray(), cell.getTagsOffset(), tagsLength);
}
}
}
@@ -340,10 +334,9 @@ public EnsureKvEncoder(OutputStream out) {
}
@Override
public void write(Cell cell) throws IOException {
- if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
checkFlushed();
// Make sure to write tags into WAL
- KeyValue.oswrite((KeyValue) cell, this.out, true);
+ KeyValueUtil.oswrite(cell, this.out, true);
}
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java
index 350f8ab50b30..df4fb72e1899 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java
@@ -22,7 +22,7 @@
import java.util.Map;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
-import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.util.Bytes;
@@ -140,9 +140,10 @@ String toFamilyString() {
String qualifier;
if (o instanceof byte[]) {
qualifier = Bytes.toString((byte[])o);
- } else if (o instanceof KeyValue) {
- byte[] rawQualifier = ((KeyValue)o).getQualifier();
- qualifier = Bytes.toString(rawQualifier);
+ } else if (o instanceof Cell) {
+ Cell c = (Cell) o;
+ qualifier = Bytes.toString(c.getQualifierArray(), c.getQualifierOffset(),
+ c.getQualifierLength());
} else {
// Shouldn't really reach this?
qualifier = o.toString();
|
5cea1f83748ed49c4cf9d2612c55ab7101599186
|
fozziethebeat$s-space
|
Changes based on Keith's review. A few tweaks to EdgeSet to help tracking edge
removal
modified: src/edu/ucla/sspace/common/Similarity.java
- Updated to use VectorMath.dotProduct for the Tanimoto coefficient
deleted: src/edu/ucla/sspace/common/WordComparator.java
- Moved to SimpleNearestNeighborFinder
modified: src/edu/ucla/sspace/dependency/SimpleDependencyPath.java
- Removed println
modified: src/edu/ucla/sspace/graph/AbstractGraph.java
- Added missing implementation to Subgraph class so now all the unit tests pass
modified: src/edu/ucla/sspace/graph/DirectedMultigraph.java
- Added missing implementation to Subgraph class so now all the unit tests pass
- Fixed bug for reporting the correct edge types after removal
- Removed dead code
modified: src/edu/ucla/sspace/graph/EdgeSet.java
- Updated so that disconnect() now returns the number of edges that were removed
modified: src/edu/ucla/sspace/graph/GenericEdgeSet.java
modified: src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java
modified: src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java
modified: src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java
modified: src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java
modified: src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java
- Updated to support EdgeSet interface change
deleted: src/edu/ucla/sspace/graph/GraphRandomizer.java
- Removed dead class (functionality is in Graphs.java)
modified: src/edu/ucla/sspace/graph/SimpleWeightedEdge.java
- Fixed hashCode()
deleted: src/edu/ucla/sspace/graph/SparseSymmetricEdgeSet.java
- Removed dead class
modified: src/edu/ucla/sspace/graph/UndirectedMultigraph.java
- Added missing implementation to Subgraph class so now all the unit tests pass
- Fixed bug for reporting the correct edge types after removal
- Removed dead code
modified: src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java
- Updated to replace WordComparator with SimpleNearestNeighborFinder
modified: src/edu/ucla/sspace/mains/LexSubWordsiMain.java
- Updated to replace WordComparator with SimpleNearestNeighborFinder
modified: src/edu/ucla/sspace/text/LabeledParsedStringDocument.java
- Updated for new ParsedDocument interface
modified: src/edu/ucla/sspace/text/ParsedDocument.java
- Updated to specify the format of text() as the tokens with white space delimiters.
- Added a new prettyPrintText() which is the attempt to nicely format the tokens
as they would have been originally.
modified: src/edu/ucla/sspace/text/PukWaCDocumentIterator.java
- Fixed javadoc
modified: src/edu/ucla/sspace/text/UkWaCDocumentIterator.java
- Added more class javadoc
modified: src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java
- Updated to use the class instances instead of the interface
modified: src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java
- Updated to replace WordComparator with PartitioningNearestNeighborFinder
modified: src/edu/ucla/sspace/tools/SimilarityListGenerator.java
- Updated to replace WordComparator with PartitioningNearestNeighborFinder
modified: src/edu/ucla/sspace/util/HashIndexer.java
- Fixed javadoc
modified: src/edu/ucla/sspace/util/PairCounter.java
- Fixed javadoc
renamed: src/edu/ucla/sspace/util/NearestNeighborFinder.java -> src/edu/ucla/sspace/util/PartitioningNearestNeighborFinder.java
- Moved so that NearestNeighborFinder can be an interface
modified: src/edu/ucla/sspace/util/ReflectionUtil.java
- Removed dead code
modified: src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java
- Added javadoc
modified: src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java
- Added javadoc
modified: test/edu/ucla/sspace/graph/DirectedMultigraphTests.java
- Uncommented out unit tests
modified: test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java
modified: test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java
modified: test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java
modified: test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java
modified: test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java
modified: test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java
modified: test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java
modified: test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java
modified: test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java
modified: test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java
- Fixed unit tests to support proper tab-delimiting of the CoNLL format
|
p
|
https://github.com/fozziethebeat/s-space
|
diff --git a/src/edu/ucla/sspace/common/Similarity.java b/src/edu/ucla/sspace/common/Similarity.java
index d56934dd..8a46db3b 100644
--- a/src/edu/ucla/sspace/common/Similarity.java
+++ b/src/edu/ucla/sspace/common/Similarity.java
@@ -41,6 +41,7 @@
import edu.ucla.sspace.vector.IntegerVector;
import edu.ucla.sspace.vector.SparseVector;
import edu.ucla.sspace.vector.Vector;
+import edu.ucla.sspace.vector.VectorMath;
import edu.ucla.sspace.vector.Vectors;
import edu.ucla.sspace.vector.SparseIntegerVector;
@@ -2187,7 +2188,7 @@ public static double tanimotoCoefficient(Vector a, Vector b) {
public static double tanimotoCoefficient(DoubleVector a, DoubleVector b) {
check(a,b);
- // IMPLEMENTATION NOTE: The Tanimoto coefficient uses the squart of the
+ // IMPLEMENTATION NOTE: The Tanimoto coefficient uses the square of the
// vector magnitudes, which we could compute by just summing the square
// of the vector values. This would save a .sqrt() call from the
// .magnitude() call. However, we expect that this method might be
@@ -2195,83 +2196,13 @@ public static double tanimotoCoefficient(DoubleVector a, DoubleVector b) {
// should only be two multiplications instaned of |nz| multiplications
// on the second call (assuming the vector instances cache their
// magnitude, which almost all do).
- double dotProduct = 0.0;
double aMagnitude = a.magnitude();
double bMagnitude = b.magnitude();
-
- // Check whether both vectors support fast iteration over their non-zero
- // values. If so, use only the non-zero indices to speed up the
- // computation by avoiding zero multiplications
- if (a instanceof Iterable && b instanceof Iterable) {
- // Check whether we can easily determine how many non-zero values
- // are in each vector. This value is used to select the iteration
- // order, which affects the number of get(value) calls.
- boolean useA =
- (a instanceof SparseVector && b instanceof SparseVector)
- && ((SparseVector)a).getNonZeroIndices().length <
- ((SparseVector)b).getNonZeroIndices().length;
-
- // Choose the smaller of the two to use in computing the dot
- // product. Because it would be more expensive to compute the
- // intersection of the two sets, we assume that any potential
- // misses would be less of a performance hit.
- if (useA) {
- for (DoubleEntry e : ((Iterable<DoubleEntry>)a)) {
- int index = e.index();
- double aValue = e.value();
- double bValue = b.get(index);
- dotProduct += aValue * bValue;
- }
- }
- else {
- for (DoubleEntry e : ((Iterable<DoubleEntry>)b)) {
- int index = e.index();
- double aValue = a.get(index);
- double bValue = e.value();
- dotProduct += aValue * bValue;
- }
- }
- }
-
- // Check whether both vectors are sparse. If so, use only the non-zero
- // indices to speed up the computation by avoiding zero multiplications
- else if (a instanceof SparseVector && b instanceof SparseVector) {
- SparseVector svA = (SparseVector)a;
- SparseVector svB = (SparseVector)b;
- int[] nzA = svA.getNonZeroIndices();
- int[] nzB = svB.getNonZeroIndices();
- // Choose the smaller of the two to use in computing the dot
- // product. Because it would be more expensive to compute the
- // intersection of the two sets, we assume that any potential
- // misses would be less of a performance hit.
- if (nzA.length < nzB.length) {
- for (int nz : nzA) {
- double aValue = a.get(nz);
- double bValue = b.get(nz);
- dotProduct += aValue * bValue;
- }
- }
- else {
- for (int nz : nzB) {
- double aValue = a.get(nz);
- double bValue = b.get(nz);
- dotProduct += aValue * bValue;
- }
- }
- }
-
- // Otherwise, just assume both are dense and compute the full amount
- else {
- for (int i = 0; i < b.length(); i++) {
- double aValue = a.get(i);
- double bValue = b.get(i);
- dotProduct += aValue * bValue;
- }
- }
-
+
if (aMagnitude == 0 || bMagnitude == 0)
return 0;
-
+
+ double dotProduct = VectorMath.dotProduct(a, b);
double aMagSq = aMagnitude * aMagnitude;
double bMagSq = bMagnitude * bMagnitude;
@@ -2297,82 +2228,13 @@ public static double tanimotoCoefficient(IntegerVector a, IntegerVector b) {
// should only be two multiplications instaned of |nz| multiplications
// on the second call (assuming the vector instances cache their
// magnitude, which almost all do).
- int dotProduct = 0;
double aMagnitude = a.magnitude();
double bMagnitude = b.magnitude();
- // Check whether both vectors support fast iteration over their non-zero
- // values. If so, use only the non-zero indices to speed up the
- // computation by avoiding zero multiplications
- if (a instanceof Iterable && b instanceof Iterable) {
- // Check whether we can easily determine how many non-zero values
- // are in each vector. This value is used to select the iteration
- // order, which affects the number of get(value) calls.
- boolean useA =
- (a instanceof SparseVector && b instanceof SparseVector)
- && ((SparseVector)a).getNonZeroIndices().length <
- ((SparseVector)b).getNonZeroIndices().length;
- // Choose the smaller of the two to use in computing the dot
- // product. Because it would be more expensive to compute the
- // intersection of the two sets, we assume that any potential
- // misses would be less of a performance hit.
- if (useA) {
- for (IntegerEntry e : ((Iterable<IntegerEntry>)a)) {
- int index = e.index();
- int aValue = e.value();
- int bValue = b.get(index);
- dotProduct += aValue * bValue;
- }
- }
- else {
- for (IntegerEntry e : ((Iterable<IntegerEntry>)b)) {
- int index = e.index();
- int aValue = a.get(index);
- int bValue = e.value();
- dotProduct += aValue * bValue;
- }
- }
- }
-
- // Check whether both vectors are sparse. If so, use only the non-zero
- // indices to speed up the computation by avoiding zero multiplications
- else if (a instanceof SparseVector && b instanceof SparseVector) {
- SparseVector svA = (SparseVector)a;
- SparseVector svB = (SparseVector)b;
- int[] nzA = svA.getNonZeroIndices();
- int[] nzB = svB.getNonZeroIndices();
- // Choose the smaller of the two to use in computing the dot
- // product. Because it would be more expensive to compute the
- // intersection of the two sets, we assume that any potential
- // misses would be less of a performance hit.
- if (nzA.length < nzB.length) {
- for (int nz : nzA) {
- int aValue = a.get(nz);
- int bValue = b.get(nz);
- dotProduct += aValue * bValue;
- }
- }
- else {
- for (int nz : nzB) {
- int aValue = a.get(nz);
- int bValue = b.get(nz);
- dotProduct += aValue * bValue;
- }
- }
- }
-
- // Otherwise, just assume both are dense and compute the full amount
- else {
- for (int i = 0; i < b.length(); i++) {
- int aValue = a.get(i);
- int bValue = b.get(i);
- dotProduct += aValue * bValue;
- }
- }
-
if (aMagnitude == 0 || bMagnitude == 0)
return 0;
-
+
+ int dotProduct = VectorMath.dotProduct(a, b);
double aMagSq = aMagnitude * aMagnitude;
double bMagSq = bMagnitude * bMagnitude;
diff --git a/src/edu/ucla/sspace/common/WordComparator.java b/src/edu/ucla/sspace/common/WordComparator.java
deleted file mode 100644
index f6b76303..00000000
--- a/src/edu/ucla/sspace/common/WordComparator.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 2009 David Jurgens
- *
- * This file is part of the S-Space package and is covered under the terms and
- * conditions therein.
- *
- * The S-Space package is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License version 2 as published
- * by the Free Software Foundation and distributed hereunder to you.
- *
- * THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
- * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
- * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
- * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
- * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
- * RIGHTS.
- *
- * 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 edu.ucla.sspace.common;
-
-import edu.ucla.sspace.util.BoundedSortedMultiMap;
-import edu.ucla.sspace.util.MultiMap;
-import edu.ucla.sspace.util.SortedMultiMap;
-import edu.ucla.sspace.util.WorkQueue;
-
-import edu.ucla.sspace.vector.Vector;
-
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedMap;
-
-
-/**
- * A utility class for finding the {@code k} most-similar words to a provided
- * word in a {@link SemanticSpace}. The comparisons required for generating the
- * list maybe be run in parallel by configuring an instance of this class to use
- * multiple threads. <p>
- *
- * All instances of this class are thread-safe.
- *
- * @author David Jurgens
- */
-public class WordComparator {
-
- /**
- * The {@link WorkQueue} from which worker threads run word-word comparisons
- */
- private final WorkQueue workQueue;
-
- /**
- * Creates this {@code WordComparator} with as many threads as processors.
- */
- public WordComparator() {
- this(Runtime.getRuntime().availableProcessors());
- }
-
- /**
- * Creates this {@code WordComparator} with the specified number of threads.
- */
- public WordComparator(int numThreads) {
- workQueue = WorkQueue.getWorkQueue(numThreads);
- }
-
- /**
- * Compares the provided word to all other words in the provided {@link
- * SemanticSpace} and return the specified number of words that were most
- * similar according to the specified similarity measure.
- *
- * @return the most similar words, or {@code null} if the provided word was
- * not in the semantic space.
- */
- public SortedMultiMap<Double,String> getMostSimilar(
- final String word, final SemanticSpace sspace,
- int numberOfSimilarWords, final Similarity.SimType similarityType) {
-
- Vector v = sspace.getVector(word);
-
- // if the semantic space did not have the word, then return null
- if (v == null) {
- return null;
- }
-
- final Vector vector = v;
- return getMostSimilar(v, sspace, numberOfSimilarWords, similarityType);
- }
-
- public SortedMultiMap<Double,String> getMostSimilar(
- final Vector vector, final SemanticSpace sspace,
- int numberOfSimilarWords, final Similarity.SimType similarityType) {
- Set<String> words = sspace.getWords();
-
- // the most-similar set will automatically retain only a fixed number
- // of elements
- final SortedMultiMap<Double,String> mostSimilar =
- new BoundedSortedMultiMap<Double,String>(numberOfSimilarWords,
- false);
-
- Object key = workQueue.registerTaskGroup(words.size());
-
- // loop through all the other words computing their similarity
- for (final String other : words) {
- workQueue.add(key, new Runnable() {
- public void run() {
- Vector otherV = sspace.getVector(other);
- // Skip the comparison if the vectors are actually the same.
- if (otherV == vector)
- return;
-
- Double similarity = Similarity.getSimilarity(
- similarityType, vector, otherV);
-
- // lock on the Map, as it is not thread-safe
- synchronized(mostSimilar) {
- mostSimilar.put(similarity, other);
- }
- }
- });
- }
-
- workQueue.await(key);
- return mostSimilar;
- }
-}
diff --git a/src/edu/ucla/sspace/dependency/SimpleDependencyPath.java b/src/edu/ucla/sspace/dependency/SimpleDependencyPath.java
index 576caa6f..51343ad8 100644
--- a/src/edu/ucla/sspace/dependency/SimpleDependencyPath.java
+++ b/src/edu/ucla/sspace/dependency/SimpleDependencyPath.java
@@ -73,7 +73,6 @@ public SimpleDependencyPath(List<DependencyRelation> path,
nodes.add(next);
cur = next;
}
- System.out.printf("path: %s,%nnodes: %s%n", path, nodes);
}
/**
diff --git a/src/edu/ucla/sspace/graph/AbstractGraph.java b/src/edu/ucla/sspace/graph/AbstractGraph.java
index 2ffa38fe..d9189a42 100755
--- a/src/edu/ucla/sspace/graph/AbstractGraph.java
+++ b/src/edu/ucla/sspace/graph/AbstractGraph.java
@@ -967,8 +967,10 @@ public Set<T> getAdjacencyList(int vertex) {
* {@inheritDoc}
*/
public IntSet getNeighbors(int vertex) {
- if (!vertexSubset.contains(vertex))
- return PrimitiveCollections.emptyIntSet();
+ return (!vertexSubset.contains(vertex))
+ ? PrimitiveCollections.emptyIntSet()
+ : new SubgraphNeighborsView(vertex);
+ /*
// REMINDER: make this a view, rather than a created set
IntSet neighbors = new TroveIntSet();
IntIterator it =
@@ -979,6 +981,7 @@ public IntSet getNeighbors(int vertex) {
neighbors.add(v);
}
return neighbors;
+ */
}
/**
@@ -1084,7 +1087,7 @@ public IntSet vertices() {
* subgraph. This class monitors for changes to edge set to update the
* state of this graph
*/
- private class SubgraphAdjacencyListView extends AbstractSet<T> {
+ private class SubgraphAdjacencyListView extends AbstractSet<T> {
private final int root;
@@ -1275,7 +1278,7 @@ public void remove() {
* subview. This view monitors for additions and removals to the set in
* order to update the state of this {@code Subgraph}.
*/
- private class SubgraphNeighborsView extends AbstractSet<Integer> {
+ private class SubgraphNeighborsView extends AbstractIntSet {
private int root;
@@ -1285,15 +1288,20 @@ private class SubgraphNeighborsView extends AbstractSet<Integer> {
public SubgraphNeighborsView(int root) {
this.root = root;
}
+
+ public boolean add(int vertex) {
+ throw new UnsupportedOperationException(
+ "Cannot add vertices to subgraph");
+ }
- /**
- * Adds an edge to this vertex and adds the vertex to the graph if it
- * was not present before.
- */
public boolean add(Integer vertex) {
throw new UnsupportedOperationException(
"Cannot add vertices to subgraph");
}
+
+ public boolean contains(int vertex) {
+ return vertexSubset.contains(vertex) && checkVertex(vertex);
+ }
public boolean contains(Object o) {
if (!(o instanceof Integer))
@@ -1309,12 +1317,18 @@ private boolean checkVertex(int i) {
return AbstractGraph.this.contains(i, root);
}
- public Iterator<Integer> iterator() {
+ public IntIterator iterator() {
return new SubgraphNeighborsIterator();
}
- public boolean remove(Object o) {
- throw new UnsupportedOperationException();
+ public boolean remove(int vertex) {
+ throw new UnsupportedOperationException(
+ "Cannot remove vertices from subgraph");
+ }
+
+ public boolean remove(Object vertex) {
+ throw new UnsupportedOperationException(
+ "Cannot remove vertices from subgraph");
}
public int size() {
@@ -1333,7 +1347,7 @@ public int size() {
* vertices set, which keeps track of which neighboring vertices are
* actually in this subview.
*/
- private class SubgraphNeighborsIterator implements Iterator<Integer> {
+ private class SubgraphNeighborsIterator implements IntIterator {
private final IntIterator iter;
@@ -1368,6 +1382,10 @@ public Integer next() {
return cur;
}
+ public int nextInt() {
+ return next();
+ }
+
/**
* Throws an {@link UnsupportedOperationException} if called.
*/
diff --git a/src/edu/ucla/sspace/graph/DirectedMultigraph.java b/src/edu/ucla/sspace/graph/DirectedMultigraph.java
index 9a2b60c5..0792e9d1 100644
--- a/src/edu/ucla/sspace/graph/DirectedMultigraph.java
+++ b/src/edu/ucla/sspace/graph/DirectedMultigraph.java
@@ -43,6 +43,8 @@
import edu.ucla.sspace.util.DisjointSets;
import edu.ucla.sspace.util.SetDecorator;
+import edu.ucla.sspace.util.primitive.AbstractIntSet;
+import edu.ucla.sspace.util.primitive.IntIterator;
import edu.ucla.sspace.util.primitive.IntSet;
import edu.ucla.sspace.util.primitive.PrimitiveCollections;
import edu.ucla.sspace.util.primitive.TroveIntSet;
@@ -51,8 +53,9 @@
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.map.TIntObjectMap;
+import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TIntObjectHashMap;
-import gnu.trove.procedure.TObjectProcedure;
+import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
@@ -72,9 +75,9 @@ public class DirectedMultigraph<T>
private static final long serialVersionUID = 1L;
/**
- * The set of types contained in this graph.
+ * The count of the type distribution for all edges in the graph.
*/
- private final Set<T> types;
+ private final TObjectIntMap<T> typeCounts;
/**
* The set of vertices in this mutligraph. This set is maintained
@@ -104,7 +107,7 @@ public class DirectedMultigraph<T>
* Creates an empty graph with node edges
*/
public DirectedMultigraph() {
- types = new HashSet<T>();
+ typeCounts = new TObjectIntHashMap<T>();
vertexToEdges = new TIntObjectHashMap<SparseDirectedTypedEdgeSet<T>>();
subgraphs = new ArrayList<WeakReference<Subgraph>>();
size = 0;
@@ -143,7 +146,7 @@ public boolean add(DirectedTypedEdge<T> e) {
vertexToEdges.put(e.from(), from);
}
if (from.add(e)) {
- types.add(e.edgeType());
+ updateTypeCounts(e.edgeType(), 1);
SparseDirectedTypedEdgeSet<T> to = vertexToEdges.get(e.to());
if (to == null) {
to = new SparseDirectedTypedEdgeSet<T>(e.to());
@@ -161,7 +164,7 @@ public boolean add(DirectedTypedEdge<T> e) {
*/
public void clear() {
vertexToEdges.clear();
- types.clear();
+ typeCounts.clear();
size = 0;
}
@@ -225,14 +228,10 @@ public DirectedMultigraph<T> copy(Set<Integer> toCopy) {
return new DirectedMultigraph<T>(this);
DirectedMultigraph<T> g = new DirectedMultigraph<T>();
- //long s = System.currentTimeMillis();
for (int v : toCopy) {
if (!vertexToEdges.containsKey(v))
throw new IllegalArgumentException(
"Request copy of non-present vertex: " + v);
-// SparseDirectedTypedEdgeSet<T> edges = vertexToEdges.get(v);
-// g.vertexToEdges.put(v, edges.copy(toCopy));
-
g.add(v);
SparseDirectedTypedEdgeSet<T> edges = vertexToEdges.get(v);
if (edges == null)
@@ -245,8 +244,6 @@ public DirectedMultigraph<T> copy(Set<Integer> toCopy) {
g.add(e);
}
}
-// if (toCopy.size() > 0)
-// System.out.printf("Copy %d vertices (%d), %d edges%n", g.order(), toCopy.size(), g.size());
return g;
}
@@ -284,7 +281,7 @@ public Set<DirectedTypedEdge<T>> edges(T t) {
* Returns the set of edge types currently present in this graph.
*/
public Set<T> edgeTypes() {
- return Collections.unmodifiableSet(types);
+ return Collections.unmodifiableSet(typeCounts.keySet());
}
/**
@@ -293,7 +290,7 @@ public Set<T> edgeTypes() {
@Override public boolean equals(Object o) {
if (o instanceof DirectedMultigraph) {
DirectedMultigraph<?> dm = (DirectedMultigraph<?>)(o);
- if (dm.types.equals(types)) {
+ if (dm.typeCounts.equals(typeCounts)) {
return vertexToEdges.equals(dm.vertexToEdges);
}
return false;
@@ -301,7 +298,7 @@ public Set<T> edgeTypes() {
else if (o instanceof Multigraph) {
@SuppressWarnings("unchecked")
Multigraph<?,TypedEdge<?>> m = (Multigraph<?,TypedEdge<?>>)o;
- if (m.edgeTypes().equals(types)) {
+ if (m.edgeTypes().equals(typeCounts.keySet())) {
return m.order() == order()
&& m.size() == size()
&& m.vertices().equals(vertices())
@@ -372,7 +369,7 @@ public boolean hasCycles() {
* {@inheritDoc}
*/
public int hashCode() {
- return vertexToEdges.keySet().hashCode() ^ (types.hashCode() * size);
+ return vertexToEdges.keySet().hashCode() ^ (typeCounts.hashCode() * size);
}
/**
@@ -448,6 +445,8 @@ public boolean remove(int vertex) {
// Check whether removing this vertex has caused us to remove
// the last edge for this type in the graph. If so, the graph
// no longer has this type and we need to update the state.
+ for (DirectedTypedEdge<T> e : edges)
+ updateTypeCounts(e.edgeType(), -1);
// Update any of the subgraphs that had this vertex to notify them
// that it was removed
@@ -467,7 +466,7 @@ public boolean remove(int vertex) {
if (s.vertexSubset.remove(vertex)) {
Iterator<T> subgraphTypesIter = s.validTypes.iterator();
while (subgraphTypesIter.hasNext()) {
- if (!types.contains(subgraphTypesIter.next()))
+ if (!typeCounts.containsKey(subgraphTypesIter.next()))
subgraphTypesIter.remove();
}
}
@@ -488,25 +487,24 @@ public boolean remove(DirectedTypedEdge<T> edge) {
// Check whether we've just removed the last edge for this type
// in the graph. If so, the graph no longer has this type and
// we need to update the state.
-
- // TODO !!
-
-
- // Remove this edge type from all the subgraphs as well
- Iterator<WeakReference<Subgraph>> sIt = subgraphs.iterator();
- while (sIt.hasNext()) {
- WeakReference<Subgraph> ref = sIt.next();
- Subgraph s = ref.get();
- // Check whether this subgraph was already gc'd (the
- // subgraph was no longer in use) and if so, remove the
- // ref from the list to avoid iterating over it again
- if (s == null) {
- sIt.remove();
- continue;
+ updateTypeCounts(edge.edgeType(), -1);
+
+ if (!typeCounts.containsKey(edge.edgeType())) {
+ // Remove this edge type from all the subgraphs as well
+ Iterator<WeakReference<Subgraph>> sIt = subgraphs.iterator();
+ while (sIt.hasNext()) {
+ WeakReference<Subgraph> ref = sIt.next();
+ Subgraph s = ref.get();
+ // Check whether this subgraph was already gc'd (the
+ // subgraph was no longer in use) and if so, remove the
+ // ref from the list to avoid iterating over it again
+ if (s == null) {
+ sIt.remove();
+ continue;
+ }
+ s.validTypes.remove(edge.edgeType());
}
- // FILL IN...
}
-
return true;
}
return false;
@@ -517,19 +515,6 @@ public boolean remove(DirectedTypedEdge<T> edge) {
*/
public int size() {
return size;
-// CountingProcedure count = new CountingProcedure();
-// vertexToEdges.forEachValue(count);
-// return count.count / 2;
- }
-
- private class CountingProcedure
- implements TObjectProcedure<SparseDirectedTypedEdgeSet<T>> {
-
- int count = 0;
- public boolean execute(SparseDirectedTypedEdgeSet<T> edges) {
- count += edges.size();
- return true;
- }
}
/**
@@ -546,7 +531,7 @@ public IntSet successors(int vertex) {
* {@inheritDoc}
*/
public DirectedMultigraph<T> subgraph(Set<Integer> subset) {
- Subgraph sub = new Subgraph(types, subset);
+ Subgraph sub = new Subgraph(typeCounts.keySet(), subset);
subgraphs.add(new WeakReference<Subgraph>(sub));
return sub;
}
@@ -557,7 +542,7 @@ public DirectedMultigraph<T> subgraph(Set<Integer> subset) {
public DirectedMultigraph<T> subgraph(Set<Integer> subset, Set<T> edgeTypes) {
if (edgeTypes.isEmpty())
throw new IllegalArgumentException("Must specify at least one type");
- if (!types.containsAll(edgeTypes)) {
+ if (!typeCounts.keySet().containsAll(edgeTypes)) {
throw new IllegalArgumentException(
"Cannot create subgraph with more types than exist");
}
@@ -574,12 +559,33 @@ public String toString() {
return "{ vertices: " + vertices() + ", edges: " + edges() + "}";
}
+ /**
+ * Updates how many edges have this type in the graph
+ */
+ private void updateTypeCounts(T type, int delta) {
+ if (!typeCounts.containsKey(type)) {
+ assert delta > 0
+ : "removing edge type that was not originally present";
+ typeCounts.put(type, delta);
+ }
+ else {
+ int curCount = typeCounts.get(type);
+ int newCount = curCount + delta;
+ assert newCount >= 0
+ : "removing edge type that was not originally present";
+ if (newCount == 0)
+ typeCounts.remove(type);
+ else
+ typeCounts.put(type, newCount);
+ }
+ }
+
/**
* {@inheritDoc}
*/
public IntSet vertices() {
- // TODO: make this unmodifiable
- return TroveIntSet.wrap(vertexToEdges.keySet());
+ return PrimitiveCollections.unmodifiableSet(
+ TroveIntSet.wrap(vertexToEdges.keySet()));
}
/**
@@ -611,8 +617,8 @@ public Iterator<DirectedTypedEdge<T>> iterator() {
public boolean remove(Object o) {
if (o instanceof DirectedTypedEdge) {
DirectedTypedEdge<?> e = (DirectedTypedEdge<?>)o;
- return DirectedMultigraph.this.types.
- contains(e.edgeType())
+ return DirectedMultigraph.this.typeCounts.
+ containsKey(e.edgeType())
&& DirectedMultigraph.this.remove((DirectedTypedEdge<T>)o);
}
return false;
@@ -933,7 +939,7 @@ public IntSet getNeighbors(int vertex) {
SparseDirectedTypedEdgeSet<T> edges = vertexToEdges.get(vertex);
return (edges == null)
? PrimitiveCollections.emptyIntSet()
- : PrimitiveCollections.unmodifiableSet(edges.connected());
+ : new SubgraphNeighborsView(vertex);
}
/**
@@ -947,7 +953,7 @@ public boolean hasCycles() {
* {@inheritDoc}
*/
public int hashCode() {
- return vertices().hashCode() ^ (types.hashCode() * size());
+ return vertices().hashCode() ^ (validTypes.hashCode() * size());
}
/**
@@ -1118,7 +1124,6 @@ public DirectedMultigraph<T> subgraph(Set<Integer> verts, Set<T> edgeTypes) {
* {@inheritDoc}
*/
public IntSet vertices() {
- // Check that the vertices are up to date with the backing graph
return PrimitiveCollections.unmodifiableSet(vertexSubset);
}
@@ -1323,7 +1328,7 @@ public void remove() {
* subview. This view monitors for additions and removals to the set in
* order to update the state of this {@code Subgraph}.
*/
- private class SubgraphNeighborsView extends AbstractSet<Integer> {
+ private class SubgraphNeighborsView extends AbstractIntSet {
private int root;
@@ -1333,15 +1338,21 @@ private class SubgraphNeighborsView extends AbstractSet<Integer> {
public SubgraphNeighborsView(int root) {
this.root = root;
}
+
+ public boolean add(int vertex) {
+ throw new UnsupportedOperationException(
+ "Cannot add vertices to subgraph");
+ }
- /**
- * Adds an edge to this vertex and adds the vertex to the graph if it
- * was not present before.
- */
public boolean add(Integer vertex) {
throw new UnsupportedOperationException(
"Cannot add vertices to subgraph");
}
+
+ public boolean contains(int vertex) {
+ return vertexSubset.contains(vertex)
+ && isNeighboringVertex(vertex);
+ }
public boolean contains(Object o) {
if (!(o instanceof Integer))
@@ -1354,12 +1365,18 @@ private boolean isNeighboringVertex(Integer i) {
return Subgraph.this.contains(root, i);
}
- public Iterator<Integer> iterator() {
+ public IntIterator iterator() {
return new SubgraphNeighborsIterator();
}
- public boolean remove(Object o) {
- throw new UnsupportedOperationException();
+ public boolean remove(int vertex) {
+ throw new UnsupportedOperationException(
+ "Cannot remove vertices from subgraph");
+ }
+
+ public boolean remove(Object vertex) {
+ throw new UnsupportedOperationException(
+ "Cannot remove vertices from subgraph");
}
public int size() {
@@ -1376,7 +1393,7 @@ public int size() {
* vertices set, which keeps track of which neighboring vertices are
* actually in this subview.
*/
- private class SubgraphNeighborsIterator implements Iterator<Integer> {
+ private class SubgraphNeighborsIterator implements IntIterator {
private final Iterator<Integer> iter;
@@ -1411,6 +1428,10 @@ public Integer next() {
return cur;
}
+ public int nextInt() {
+ return next();
+ }
+
/**
* Throws an {@link UnsupportedOperationException} if called.
*/
diff --git a/src/edu/ucla/sspace/graph/EdgeSet.java b/src/edu/ucla/sspace/graph/EdgeSet.java
index 49facf17..eec197e7 100755
--- a/src/edu/ucla/sspace/graph/EdgeSet.java
+++ b/src/edu/ucla/sspace/graph/EdgeSet.java
@@ -64,9 +64,10 @@ public interface EdgeSet<T extends Edge> extends Set<T> {
EdgeSet copy(IntSet vertices);
/**
- * Removes all edges instances that connect to the specified vertex.
+ * Removes all edges instances that connect to the specified vertex,
+ * returning the number of edges that were removed, if any.
*/
- boolean disconnect(int vertex);
+ int disconnect(int vertex);
/**
* Returns the set of {@link Edge} instances that connect the root vertex
diff --git a/src/edu/ucla/sspace/graph/GenericEdgeSet.java b/src/edu/ucla/sspace/graph/GenericEdgeSet.java
index 97ca6fe0..1674aee2 100644
--- a/src/edu/ucla/sspace/graph/GenericEdgeSet.java
+++ b/src/edu/ucla/sspace/graph/GenericEdgeSet.java
@@ -40,46 +40,34 @@
* edges that may be contained within. This class keeps track of which vertices
* are in the set as well, allowing for efficient vertex-based operations.
*
- * <p> Due not knowing the {@link Edge} type, this class prevents modification via
- * adding or removing vertices.
- *
* @author David Jurgens
*
* @param T the type of edge to be stored in the set
*/
public class GenericEdgeSet<T extends Edge> extends AbstractSet<T>
- implements EdgeSet<T> {
+ implements EdgeSet<T>, java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * The vertex to which all edges in the set are connected
+ */
private final int rootVertex;
-// private final BitSet vertices;
-
-// private final Set<T> edges;
-
+ /**
+ * A mapping from connected vertices to the edges that connect to them
+ */
private final MultiMap<Integer,T> vertexToEdges ;
public GenericEdgeSet(int rootVertex) {
this.rootVertex = rootVertex;
-// edges = new HashSet<T>();
-// vertices = new BitSet();
vertexToEdges = new HashMultiMap<Integer,T>();
}
/**
- * Adds the edge to this set if one of the vertices is the root vertex and
- * if the non-root vertex has a greater index that this vertex.
+ * {@inheritDoc}
*/
public boolean add(T e) {
-// if (e.from() == rootVertex && edges.add(e)) {
-// connected.set(e.to());
-// return true;
-// }
-// else if (e.to() == rootVertex && edges.add(e)) {
-// connected.add(e.from());
-// return true;
-// }
-// return false;
-
return (e.from() == rootVertex && vertexToEdges.put(e.to(), e))
|| (e.to() == rootVertex && vertexToEdges.put(e.from(), e));
}
@@ -96,15 +84,16 @@ public IntSet connected() {
* {@inheritDoc}
*/
public boolean connects(int vertex) {
- return vertexToEdges.containsKey(vertex); //vertices.get(vertex);
+ return vertexToEdges.containsKey(vertex);
}
/**
* {@inheritDoc}
*/
- public boolean disconnect(int vertex) {
- return vertexToEdges.remove(vertex) != null;
+ public int disconnect(int vertex) {
+ Set<T> edges = vertexToEdges.remove(vertex);
+ return (edges == null) ? 0 : edges.size();
}
/**
diff --git a/src/edu/ucla/sspace/graph/GraphRandomizer.java b/src/edu/ucla/sspace/graph/GraphRandomizer.java
deleted file mode 100644
index cb1f2f4a..00000000
--- a/src/edu/ucla/sspace/graph/GraphRandomizer.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 2011 David Jurgens
- *
- * This file is part of the S-Space package and is covered under the terms and
- * conditions therein.
- *
- * The S-Space package is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License version 2 as published
- * by the Free Software Foundation and distributed hereunder to you.
- *
- * THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
- * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
- * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
- * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
- * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
- * RIGHTS.
- *
- * 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 edu.ucla.sspace.graph;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-
-public class GraphRandomizer {
-
- public static <T extends Edge> void shufflePreserveDegreeInMemory(Graph<T> g) {
-
- List<T> edges = new ArrayList<T>(g.edges());
-
- // Decide on number of iterations
- int swapIterations = 3 * g.size();
- for (int s = 0; s < swapIterations; ++s) {
-
- // Pick two vertices from which the edges will be selected
- int i = (int)(Math.random() * edges.size());
- int j = i;
- // Pick another vertex that is not v1
- while (i == j)
- j = (int)(Math.random() * edges.size());
-
- T e1 = edges.get(i);
- T e2 = edges.get(j);
-
- // Swap their end points
- T swapped1 = e1.<T>clone(e1.from(), e2.to());
- T swapped2 = e2.<T>clone(e2.from(), e1.to());
-
- // Check that the new edges do not already exist in the graph
- if (g.contains(swapped1)
- || g.contains(swapped2))
- continue;
-
- // Remove the old edges
- g.remove(e1);
- g.remove(e2);
-
- // Put in the swapped-end-point edges
- g.add(swapped1);
- g.add(swapped2);
-
- // Update the in-memory edges set so that if these edges are drawn
- // again, they don't point to old edges
- edges.set(i, swapped1);
- edges.set(j, swapped2);
- }
- }
-
- public static <T extends Edge> void shufflePreserveDegree(Graph<T> g) {
-
- // Copy the vertices to a list to support random access
- List<Integer> vertices = new ArrayList<Integer>(g.vertices());
-
- // Decide on number of iterations
- int swapIterations = 3 * g.size();
- for (int i = 0; i < swapIterations; ++i) {
-
- // Pick two vertices from which the edges will be selected
- int v1 = vertices.get((int)(Math.random() * vertices.size()));
- int v2 = v1;
- // Pick another vertex that is not v1
- while (v1 == v2)
- v2 = vertices.get((int)(Math.random() * vertices.size()));
-
- // From the two vertices, select an edge from each of their adjacency
- // lists.
- T e1 = getRandomEdge(g.getAdjacencyList(v1));
- T e2 = getRandomEdge(g.getAdjacencyList(v2));
-
- // Swap their end points
- T swapped1 = e1.<T>clone(e1.from(), e2.to());
- T swapped2 = e2.<T>clone(e2.from(), e1.to());
-
- // Check that the new edges do not already exist in the graph
- if (g.contains(swapped1)
- || g.contains(swapped2))
- continue;
-
- // Remove the old edges
- g.remove(e1);
- g.remove(e2);
-
- // Put in the swapped-end-point edges
- g.add(swapped1);
- g.add(swapped2);
- }
- }
-
- private static <T> T getRandomEdge(Set<T> edges) {
- int edgeToSelect = (int)(edges.size() * Math.random());
- Iterator<T> it = edges.iterator();
- int i = 0;
- while (it.hasNext()) {
- T edge = it.next();
- if (i == edgeToSelect)
- return edge;
- i++;
- }
- throw new AssertionError("Random edge selection logic is incorrect");
- }
-}
\ No newline at end of file
diff --git a/src/edu/ucla/sspace/graph/SimpleWeightedEdge.java b/src/edu/ucla/sspace/graph/SimpleWeightedEdge.java
index eae597ea..c45988e2 100644
--- a/src/edu/ucla/sspace/graph/SimpleWeightedEdge.java
+++ b/src/edu/ucla/sspace/graph/SimpleWeightedEdge.java
@@ -70,8 +70,7 @@ public boolean equals(Object o) {
* {@inheritDoc}
*/
public int hashCode() {
- long bits = Double.doubleToLongBits(weight);
- return from ^ to ^ (int)(bits ^ (bits >>> 32));
+ return from ^ to;
}
/**
diff --git a/src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java
index a0dd1768..5b3ba736 100644
--- a/src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java
+++ b/src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java
@@ -43,7 +43,9 @@
* @author David Jurgens
*/
public class SparseDirectedEdgeSet extends AbstractSet<DirectedEdge>
- implements EdgeSet<DirectedEdge> {
+ implements EdgeSet<DirectedEdge>, java.io.Serializable {
+
+ private static final long serialVersionUID = 1L;
/**
* The vertex to which all edges in the set are connected
@@ -149,8 +151,13 @@ public SparseDirectedEdgeSet copy(IntSet vertices) {
/**
* {@inheritDoc}
*/
- public boolean disconnect(int vertex) {
- return inEdges.remove(vertex) | outEdges.remove(vertex);
+ public int disconnect(int vertex) {
+ int removed = 0;
+ if (inEdges.remove(vertex))
+ removed++;
+ if (outEdges.remove(vertex))
+ removed++;
+ return removed;
}
/**
diff --git a/src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java
index 2c6828a1..e267bddb 100644
--- a/src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java
+++ b/src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java
@@ -59,9 +59,10 @@
/**
- * An {@link EdgeSet} implementation that stores {@link TypedEdge} instances for
- * a vertex. This class provides additional methods beyond the {@code EdgeSet}
- * interface for interacting with edges on the basis of their type.
+ * An {@link EdgeSet} implementation that stores {@link DirectedTypedEdge}
+ * instances for a vertex. This class provides additional methods beyond the
+ * {@code EdgeSet} interface for interacting with edges on the basis of their
+ * type and their orientation.
*/
public class SparseDirectedTypedEdgeSet<T>
extends AbstractSet<DirectedTypedEdge<T>>
@@ -305,6 +306,8 @@ public SparseDirectedTypedEdgeSet<T> copy(IntSet vertices) {
* reasons. I was hoping the DirectedMultigraph.copy() could be sped up by
* copying the raw data faster than the Edge-based data, but this
* implementation actually slows down DirectedMultigraph.copy() by 100X.
+ * It's being left in as a future study on how to fix it to speed up the
+ * copy operation.
*/
// public SparseDirectedTypedEdgeSet<T> copy(Set<Integer> vertices) {
@@ -340,19 +343,28 @@ public SparseDirectedTypedEdgeSet<T> copy(IntSet vertices) {
// }
/**
- * Removes all edges to {@code v}.
+ * {@inheritDoc}
*/
- public boolean disconnect(int v) {
+ public int disconnect(int v) {
if (connected.remove(v)) {
+ int removed = 0;
BitSet b = inEdges.remove(v);
- if (b != null)
- size -= b.cardinality();
+ if (b != null) {
+ int edges = b.cardinality();
+ size -= edges;
+ removed += edges;
+ }
b = outEdges.remove(v);
- if (b != null)
- size -= b.cardinality();
- return true;
+ if (b != null) {
+ int edges = b.cardinality();
+ size -= edges;
+ removed += edges;
+ }
+ assert removed > 0 :
+ "connected removed an edge that wasn't listed elsewhere";
+ return removed;
}
- return false;
+ return 0;
}
/**
diff --git a/src/edu/ucla/sspace/graph/SparseSymmetricEdgeSet.java b/src/edu/ucla/sspace/graph/SparseSymmetricEdgeSet.java
deleted file mode 100755
index 82a5e461..00000000
--- a/src/edu/ucla/sspace/graph/SparseSymmetricEdgeSet.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright 2011 David Jurgens
- *
- * This file is part of the S-Space package and is covered under the terms and
- * conditions therein.
- *
- * The S-Space package is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License version 2 as published
- * by the Free Software Foundation and distributed hereunder to you.
- *
- * THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES,
- * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE
- * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY
- * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION
- * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER
- * RIGHTS.
- *
- * 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 edu.ucla.sspace.graph;
-
-import java.util.AbstractSet;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.Set;
-
-import edu.ucla.sspace.util.OpenIntSet;
-
-
-/**
- *
- */
-public class SparseSymmetricEdgeSet {
-
- private final int rootVertex;
-
- private final OpenIntSet edges;
-
- public SparseSymmetricEdgeSet(int rootVertex) {
- this.rootVertex = rootVertex;
- edges = new OpenIntSet();
- }
-
- /**
- * Adds the edge to this set if one of the vertices is the root vertex and
- * if the non-root vertex has a greater index that this vertex.
- */
- public boolean add(Edge e) {
- int toAdd = -1;
- if (e.from() == rootVertex) {
- toAdd = e.to();
- }
- else {
- if (e.to() != rootVertex)
- return false;
- // else e.to() == rootVertex
- toAdd = e.from();
- }
-
- // Only add the vertex if the index for it is greated than this vertex.
- // In a set of EdgeSets, this ensure that for two indices i,j only one
- // edge is ever present
- if (rootVertex < toAdd)
- return edges.add(toAdd);
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<Integer> connected() {
- // REMINDER: wrap to prevent adding self edges?
- return edges;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean connects(int vertex) {
- return edges.contains(vertex);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean contains(Object o) {
- if (o instanceof Edge) {
- Edge e = (Edge)o;
- if (e.to() == rootVertex)
- return e.from() > rootVertex && edges.contains(e.from());
- else
- return e.from() == rootVertex && edges.contains(e.to());
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean disconnect(int vertex) {
- return edges.remove(vertex);
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<Edge> getEdges(int vertex) {
- return (edges.contains(vertex))
- ? Collections.<Edge>singleton(new SimpleEdge(rootVertex, vertex))
- : null;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getRoot() {
- return rootVertex;
- }
-
- /**
- * {@inheritDoc}
- */
- public Iterator<Edge> iterator() {
- return new EdgeIterator();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean remove(Object o) {
- if (o instanceof Edge) {
- Edge e = (Edge)o;
- if (e.to() == rootVertex)
- return e.from() > rootVertex && edges.remove(e.from());
- else
- return e.from() == rootVertex && edges.remove(e.to());
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public int size() {
- return edges.size();
- }
-
- /**
- * An iterator over the edges in this set that constructs {@link Edge}
- * instances as it traverses through the set of connected vertices.
- */
- private class EdgeIterator implements Iterator<Edge> {
-
- private Iterator<Integer> otherVertices;
-
- public EdgeIterator() {
- otherVertices = edges.iterator();
- }
-
- public boolean hasNext() {
- return otherVertices.hasNext();
- }
-
- public Edge next() {
- Integer i = otherVertices.next();
- return new SimpleEdge(rootVertex, i);
- }
-
- public void remove() {
- otherVertices.remove();
- }
- }
-}
\ No newline at end of file
diff --git a/src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java
index 56fc0271..1dffc854 100644
--- a/src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java
+++ b/src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java
@@ -278,15 +278,16 @@ public SparseTypedEdgeSet<T> copy(IntSet vertices) {
}
/**
- * Removes all edges to {@code v}.
+ * {@inheritDoc}
*/
- public boolean disconnect(int v) {
+ public int disconnect(int v) {
BitSet b = edges.remove(v);
if (b != null) {
- size -= b.cardinality();
- return true;
+ int edges = b.cardinality();
+ size -= edges;
+ return edges;
}
- return false;
+ return 0;
}
/**
@@ -518,7 +519,10 @@ else if (curIndex != oldIndex) {
}
}
-
+ /**
+ * A utility class for exposing the objects for types of the edges in this
+ * set, which are otherwise represented as bits.
+ */
private class Types extends AbstractSet<T> {
public boolean contains(Object o) {
diff --git a/src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java
index 67c991c6..705fc71f 100644
--- a/src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java
+++ b/src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java
@@ -41,7 +41,9 @@
* A {@link EdgeSet} implementation for holding {@link Edge} instances.
*/
public class SparseUndirectedEdgeSet extends AbstractSet<Edge>
- implements EdgeSet<Edge> {
+ implements EdgeSet<Edge>, java.io.Serializable {
+
+ private static final long serialVersionUID = 1L;
/**
* The vertex that is connected to all the edges in this set
@@ -135,8 +137,8 @@ public SparseUndirectedEdgeSet copy(IntSet vertices) {
/**
* {@inheritDoc}
*/
- public boolean disconnect(int vertex) {
- return edges.remove(vertex);
+ public int disconnect(int vertex) {
+ return (edges.remove(vertex)) ? 1 : 0;
}
/**
diff --git a/src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java
index 448a0cec..bb022d0c 100644
--- a/src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java
+++ b/src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java
@@ -49,7 +49,7 @@
* two vertices will only have at most one edge between them. If an edge exists
* for vertices {@code i} and {@code j} with weight {@code w}<sub>1</sub>, then
* adding a new edge to the same vertices with weight {@code w}<sub>2</sub> will
- * not add a parallel edge and increase the set of this set, even though the
+ * not add a parallel edge and increase the size of this set, even though the
* edges are not equal. Rather, the weight on the edge between the two vertices
* is changed to {@code w}<sub>2</sub>. Similarly, any contains or removal
* operation will return its value based on the {@code WeightedEdge}'s vertices
@@ -176,12 +176,12 @@ public SparseWeightedEdgeSet copy(IntSet vertices) {
/**
* {@inheritDoc}
*/
- public boolean disconnect(int vertex) {
+ public int disconnect(int vertex) {
if (edges.containsKey(vertex)) {
edges.remove(vertex);
- return true;
+ return 1;
}
- return false;
+ return 0;
}
/**
diff --git a/src/edu/ucla/sspace/graph/UndirectedMultigraph.java b/src/edu/ucla/sspace/graph/UndirectedMultigraph.java
index 90983a6c..f74e9b63 100644
--- a/src/edu/ucla/sspace/graph/UndirectedMultigraph.java
+++ b/src/edu/ucla/sspace/graph/UndirectedMultigraph.java
@@ -53,8 +53,9 @@
import gnu.trove.iterator.TIntIterator;
import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.map.TIntObjectMap;
+import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TIntObjectHashMap;
-import gnu.trove.procedure.TObjectProcedure;
+import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
@@ -73,9 +74,9 @@ public class UndirectedMultigraph<T>
private static final long serialVersionUID = 1L;
/**
- * The set of types contained in this graph.
+ * The count of the type distribution for all edges in the graph.
*/
- private final Set<T> types;
+ private final TObjectIntMap<T> typeCounts;
/**
* The set of vertices in this mutligraph. This set is maintained
@@ -105,7 +106,7 @@ public class UndirectedMultigraph<T>
* Creates an empty graph with node edges
*/
public UndirectedMultigraph() {
- types = new HashSet<T>();
+ typeCounts = new TObjectIntHashMap<T>();
vertexToEdges = new TIntObjectHashMap<SparseTypedEdgeSet<T>>();
subgraphs = new ArrayList<WeakReference<Subgraph>>();
size = 0;
@@ -144,7 +145,7 @@ public boolean add(TypedEdge<T> e) {
vertexToEdges.put(e.from(), from);
}
if (from.add(e)) {
- types.add(e.edgeType());
+ updateTypeCounts(e.edgeType(), 1);
SparseTypedEdgeSet<T> to = vertexToEdges.get(e.to());
if (to == null) {
to = new SparseTypedEdgeSet<T>(e.to());
@@ -162,7 +163,7 @@ public boolean add(TypedEdge<T> e) {
*/
public void clear() {
vertexToEdges.clear();
- types.clear();
+ typeCounts.clear();
size = 0;
}
@@ -231,8 +232,6 @@ public UndirectedMultigraph<T> copy(Set<Integer> toCopy) {
if (!vertexToEdges.containsKey(v))
throw new IllegalArgumentException(
"Request copy of non-present vertex: " + v);
-// SparseTypedEdgeSet<T> edges = vertexToEdges.get(v);
-// g.vertexToEdges.put(v, edges.copy(toCopy));
g.add(v);
SparseTypedEdgeSet<T> edges = vertexToEdges.get(v);
@@ -246,8 +245,6 @@ public UndirectedMultigraph<T> copy(Set<Integer> toCopy) {
g.add(e);
}
}
-// if (toCopy.size() > 0)
-// System.out.printf("Copy %d vertices (%d), %d edges%n", g.order(), toCopy.size(), g.size());
return g;
}
@@ -283,7 +280,7 @@ public Set<TypedEdge<T>> edges(T t) {
* Returns the set of edge types currently present in this graph.
*/
public Set<T> edgeTypes() {
- return Collections.unmodifiableSet(types);
+ return Collections.unmodifiableSet(typeCounts.keySet());
}
/**
@@ -292,7 +289,7 @@ public Set<T> edgeTypes() {
@Override public boolean equals(Object o) {
if (o instanceof UndirectedMultigraph) {
UndirectedMultigraph<?> dm = (UndirectedMultigraph<?>)(o);
- if (dm.types.equals(types)) {
+ if (dm.typeCounts.equals(typeCounts)) {
return vertexToEdges.equals(dm.vertexToEdges);
}
return false;
@@ -300,7 +297,7 @@ public Set<T> edgeTypes() {
else if (o instanceof Multigraph) {
@SuppressWarnings("unchecked")
Multigraph<?,TypedEdge<?>> m = (Multigraph<?,TypedEdge<?>>)o;
- if (m.edgeTypes().equals(types)) {
+ if (m.edgeTypes().equals(typeCounts.keySet())) {
return m.order() == order()
&& m.size() == size()
&& m.vertices().equals(vertices())
@@ -371,7 +368,8 @@ public boolean hasCycles() {
* {@inheritDoc}
*/
public int hashCode() {
- return vertexToEdges.keySet().hashCode() ^ (types.hashCode() * size);
+ return vertexToEdges.keySet().hashCode() ^
+ (typeCounts.keySet().hashCode() * size);
}
/**
@@ -397,6 +395,8 @@ public boolean remove(int vertex) {
// Check whether removing this vertex has caused us to remove
// the last edge for this type in the graph. If so, the graph
// no longer has this type and we need to update the state.
+ for (TypedEdge<T> e : edges)
+ updateTypeCounts(e.edgeType(), -1);
// Update any of the subgraphs that had this vertex to notify them
// that it was removed
@@ -416,7 +416,7 @@ public boolean remove(int vertex) {
if (s.vertexSubset.remove(vertex)) {
Iterator<T> subgraphTypesIter = s.validTypes.iterator();
while (subgraphTypesIter.hasNext()) {
- if (!types.contains(subgraphTypesIter.next()))
+ if (!typeCounts.containsKey(subgraphTypesIter.next()))
subgraphTypesIter.remove();
}
}
@@ -434,26 +434,27 @@ public boolean remove(TypedEdge<T> edge) {
if (edges != null && edges.remove(edge)) {
vertexToEdges.get(edge.from()).remove(edge);
size--;
+
// Check whether we've just removed the last edge for this type
// in the graph. If so, the graph no longer has this type and
// we need to update the state.
-
- // TODO !!
-
-
- // Remove this edge type from all the subgraphs as well
- Iterator<WeakReference<Subgraph>> sIt = subgraphs.iterator();
- while (sIt.hasNext()) {
- WeakReference<Subgraph> ref = sIt.next();
- Subgraph s = ref.get();
- // Check whether this subgraph was already gc'd (the
- // subgraph was no longer in use) and if so, remove the
- // ref from the list to avoid iterating over it again
- if (s == null) {
- sIt.remove();
- continue;
+ updateTypeCounts(edge.edgeType(), -1);
+
+ if (!typeCounts.containsKey(edge.edgeType())) {
+ // Remove this edge type from all the subgraphs as well
+ Iterator<WeakReference<Subgraph>> sIt = subgraphs.iterator();
+ while (sIt.hasNext()) {
+ WeakReference<Subgraph> ref = sIt.next();
+ Subgraph s = ref.get();
+ // Check whether this subgraph was already gc'd (the
+ // subgraph was no longer in use) and if so, remove the
+ // ref from the list to avoid iterating over it again
+ if (s == null) {
+ sIt.remove();
+ continue;
+ }
+ s.validTypes.remove(edge.edgeType());
}
- // FILL IN...
}
return true;
@@ -466,26 +467,13 @@ public boolean remove(TypedEdge<T> edge) {
*/
public int size() {
return size;
-// CountingProcedure count = new CountingProcedure();
-// vertexToEdges.forEachValue(count);
-// return count.count / 2;
- }
-
- private class CountingProcedure
- implements TObjectProcedure<SparseTypedEdgeSet<T>> {
-
- int count = 0;
- public boolean execute(SparseTypedEdgeSet<T> edges) {
- count += edges.size();
- return true;
- }
}
/**
* {@inheritDoc}
*/
public UndirectedMultigraph<T> subgraph(Set<Integer> subset) {
- Subgraph sub = new Subgraph(types, subset);
+ Subgraph sub = new Subgraph(typeCounts.keySet(), subset);
subgraphs.add(new WeakReference<Subgraph>(sub));
return sub;
}
@@ -496,7 +484,7 @@ public UndirectedMultigraph<T> subgraph(Set<Integer> subset) {
public UndirectedMultigraph<T> subgraph(Set<Integer> subset, Set<T> edgeTypes) {
if (edgeTypes.isEmpty())
throw new IllegalArgumentException("Must specify at least one type");
- if (!types.containsAll(edgeTypes)) {
+ if (!typeCounts.keySet().containsAll(edgeTypes)) {
throw new IllegalArgumentException(
"Cannot create subgraph with more types than exist");
}
@@ -513,11 +501,31 @@ public String toString() {
return "{ vertices: " + vertices() + ", edges: " + edges() + "}";
}
+ /**
+ * Updates how many edges have this type in the graph
+ */
+ private void updateTypeCounts(T type, int delta) {
+ if (!typeCounts.containsKey(type)) {
+ assert delta > 0
+ : "removing edge type that was not originally present";
+ typeCounts.put(type, delta);
+ }
+ else {
+ int curCount = typeCounts.get(type);
+ int newCount = curCount + delta;
+ assert newCount >= 0
+ : "removing edge type that was not originally present";
+ if (newCount == 0)
+ typeCounts.remove(type);
+ else
+ typeCounts.put(type, newCount);
+ }
+ }
+
/**
* {@inheritDoc}
*/
public IntSet vertices() {
- // TODO: make this unmodifiable
return PrimitiveCollections.unmodifiableSet(
TroveIntSet.wrap(vertexToEdges.keySet()));
}
@@ -551,8 +559,8 @@ public Iterator<TypedEdge<T>> iterator() {
public boolean remove(Object o) {
if (o instanceof TypedEdge) {
TypedEdge<?> e = (TypedEdge<?>)o;
- return UndirectedMultigraph.this.types.
- contains(e.edgeType())
+ return UndirectedMultigraph.this.typeCounts.
+ containsKey(e.edgeType())
&& UndirectedMultigraph.this.remove((TypedEdge<T>)o);
}
return false;
@@ -886,7 +894,8 @@ public boolean hasCycles() {
* {@inheritDoc}
*/
public int hashCode() {
- return vertices().hashCode() ^ (types.hashCode() * size());
+ return vertices().hashCode() ^
+ (validTypes.hashCode() * size());
}
/**
diff --git a/src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java b/src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java
index 53a3bf3e..8466e9a5 100644
--- a/src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java
+++ b/src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java
@@ -27,7 +27,6 @@
import edu.ucla.sspace.common.SemanticSpaceIO.SSpaceFormat;
import edu.ucla.sspace.common.Similarity;
import edu.ucla.sspace.common.Similarity.SimType;
-import edu.ucla.sspace.common.WordComparator;
import edu.ucla.sspace.ri.IndexVectorUtil;
@@ -43,6 +42,8 @@
import edu.ucla.sspace.util.CombinedIterator;
import edu.ucla.sspace.util.MultiMap;
+import edu.ucla.sspace.util.NearestNeighborFinder;
+import edu.ucla.sspace.util.SimpleNearestNeighborFinder;
import edu.ucla.sspace.util.SortedMultiMap;
import edu.ucla.sspace.util.TimeSpan;
import edu.ucla.sspace.util.TreeMultiMap;
@@ -172,12 +173,6 @@ public class FixedDurationTemporalRandomIndexingMain {
*/
private boolean printShiftRankings;
- /**
- * The word comparator used for computing similarity scores when calculating
- * the semantic shift.
- */
- private WordComparator wordComparator;
-
/**
* A mapping from each word to the vectors that account for its temporal
* semantics according to the specified time span
@@ -368,9 +363,6 @@ public void run(String[] args) throws Exception {
numThreads = argOptions.getIntOption("threads");
}
- // initialize the word comparator based on the number of threads
- wordComparator = new WordComparator(numThreads);
-
overwrite = true;
if (argOptions.hasOption("overwrite")) {
overwrite = argOptions.getBooleanOption("overwrite");
@@ -680,12 +672,13 @@ private void printWordNeighbors(String dateString,
LOGGER.info("printing the most similar words for the semantic partition" +
" starting at: " + dateString);
+ NearestNeighborFinder nnf =
+ new SimpleNearestNeighborFinder(semanticPartition);
+
// generate the similarity lists
for (String toExamine : interestingWords) {
SortedMultiMap<Double,String> mostSimilar =
- wordComparator.getMostSimilar(toExamine, semanticPartition,
- interestingWordNeighbors,
- Similarity.SimType.COSINE);
+ nnf.getMostSimilar(toExamine, interestingWordNeighbors);
if (mostSimilar != null) {
File neighborFile =
diff --git a/src/edu/ucla/sspace/mains/LexSubWordsiMain.java b/src/edu/ucla/sspace/mains/LexSubWordsiMain.java
index 262ac826..62d0a3a0 100644
--- a/src/edu/ucla/sspace/mains/LexSubWordsiMain.java
+++ b/src/edu/ucla/sspace/mains/LexSubWordsiMain.java
@@ -6,7 +6,6 @@
import edu.ucla.sspace.common.Similarity;
import edu.ucla.sspace.common.Similarity.SimType;
import edu.ucla.sspace.common.StaticSemanticSpace;
-import edu.ucla.sspace.common.WordComparator;
import edu.ucla.sspace.hal.LinearWeighting;
@@ -15,7 +14,9 @@
import edu.ucla.sspace.text.corpora.SemEvalLexSubReader;
import edu.ucla.sspace.util.MultiMap;
+import edu.ucla.sspace.util.NearestNeighborFinder;
import edu.ucla.sspace.util.SerializableUtil;
+import edu.ucla.sspace.util.SimpleNearestNeighborFinder;
import edu.ucla.sspace.vector.SparseDoubleVector;
import edu.ucla.sspace.vector.Vector;
@@ -59,7 +60,7 @@ public static void main(String[] args) {
}
public static class LexSubWordsi implements Wordsi {
- private final WordComparator comparator;
+ private final NearestNeighborFinder comparator;
private final PrintWriter output;
@@ -67,9 +68,9 @@ public static class LexSubWordsi implements Wordsi {
public LexSubWordsi(String outFile, String sspaceFile) {
try {
- comparator = new WordComparator();
output = new PrintWriter(outFile);
wordsiSpace = new StaticSemanticSpace(sspaceFile);
+ comparator = new SimpleNearestNeighborFinder(wordsiSpace);
} catch (IOException ioe) {
throw new IOError(ioe);
}
@@ -86,10 +87,9 @@ public void handleContextVector(String focus,
System.err.printf("Processing %s\n", secondary);
String bestSense = getBaseSense(focus, vector);
if (bestSense == null)
- return;
-
+ return;
MultiMap<Double, String> topWords = comparator.getMostSimilar(
- bestSense, wordsiSpace, 10, SimType.COSINE);
+ bestSense, 10);
output.printf("%s ::", secondary);
for (String term : topWords.values())
output.printf(" %s", term);
diff --git a/src/edu/ucla/sspace/text/LabeledParsedStringDocument.java b/src/edu/ucla/sspace/text/LabeledParsedStringDocument.java
index 2fe2ac90..acd25992 100644
--- a/src/edu/ucla/sspace/text/LabeledParsedStringDocument.java
+++ b/src/edu/ucla/sspace/text/LabeledParsedStringDocument.java
@@ -64,6 +64,21 @@ public DependencyTreeNode[] parsedDocument() {
* {@inheritDoc}
*/
public String text() {
+ DependencyTreeNode[] nodes = parsedDocument();
+ StringBuilder sb = new StringBuilder(nodes.length * 8);
+ for (int i = 0; i < nodes.length; ++i) {
+ String token = nodes[i].word();
+ sb.append(token);
+ if (i+1 < nodes.length)
+ sb.append(' ');
+ }
+ return sb.toString();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String prettyPrintText() {
Pattern punctuation = Pattern.compile("[!,-.:;?`]");
DependencyTreeNode[] nodes = parsedDocument();
StringBuilder sb = new StringBuilder(nodes.length * 8);
diff --git a/src/edu/ucla/sspace/text/ParsedDocument.java b/src/edu/ucla/sspace/text/ParsedDocument.java
index e5406df0..fcc9b566 100644
--- a/src/edu/ucla/sspace/text/ParsedDocument.java
+++ b/src/edu/ucla/sspace/text/ParsedDocument.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2011 David Jurgens
+ * Copyright 2012 David Jurgens
*
* This file is part of the S-Space package and is covered under the terms and
* conditions therein.
@@ -40,7 +40,18 @@ public interface ParsedDocument extends Document {
/**
* Returns the text of the parsed document without any of the
- * parsing-related annotation.
+ * parsing-related annotation, with each parsed token separated by
+ * whitespace.
*/
String text();
+
+ /**
+ * Returns a pretty-printed version of the document's text without any of
+ * the parsing-related annotation and using heuristics to appropriately
+ * space punctuation, quotes, and contractions. This methods is intended as
+ * only a useful way to displaying the document's text in a more readable
+ * format than {@link #text()}, but makes no claims as to reproducing the
+ * original surface form of the document prior to parsing.
+ */
+ String prettyPrintText();
}
diff --git a/src/edu/ucla/sspace/text/PukWaCDocumentIterator.java b/src/edu/ucla/sspace/text/PukWaCDocumentIterator.java
index 34e37664..7037e315 100644
--- a/src/edu/ucla/sspace/text/PukWaCDocumentIterator.java
+++ b/src/edu/ucla/sspace/text/PukWaCDocumentIterator.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2011 David Jurgens
+ * Copyright 2012 David Jurgens
*
* This file is part of the S-Space package and is covered under the terms and
* conditions therein.
@@ -36,12 +36,14 @@
* An iterator implementation that returns {@link Document} containg a single
* dependency parsed sentence given a file in the <a
* href="http://nextens.uvt.nl/depparse-wiki/DataFormat">CoNLL Format</a> which
- * is contained in the XML format provided in the WaCkypedia corpus.
+ * is contained in the XML format provided in the WaCkypedia corpus. See the <a
+ * href="http://wacky.sslmit.unibo.it/doku.php?id=corpora">WaCky</a> group's
+ * website for more information on the PukWaC.
*/
public class PukWaCDocumentIterator implements Iterator<LabeledParsedDocument> {
/**
- * The extractor used to build trees from the pukWaC documents
+ * The extractor used to build trees from the PukWaC documents
*/
private static final DependencyExtractor extractor =
new WaCKyDependencyExtractor();
@@ -65,7 +67,7 @@ public class PukWaCDocumentIterator implements Iterator<LabeledParsedDocument> {
* Creates an {@code Iterator} over the file where each document returned
* contains the sequence of dependency parsed words composing a sentence..
*
- * @param documentsFile the name of the pukWaC file containing dependency
+ * @param documentsFile the name of the PukWaC file containing dependency
* parsed sentences in the <a
* href="http://nextens.uvt.nl/depparse-wiki/DataFormat">CoNLL
* Format</a> separated by XML tags for the sentences and articles
@@ -100,7 +102,7 @@ else if (line.equals("<s>")) {
while ((line = documentsReader.readLine()) != null
&& !line.equals("</s>")) {
- // Unfortunately, the XML of the pukWaC is broken and some
+ // Unfortunately, the XML of the PukWaC is broken and some
// <text> elements are inside the <s> elements, so this code
// is needed to avoid putting those inside the CONLL data
if (line.contains("<text")) {
diff --git a/src/edu/ucla/sspace/text/UkWaCDocumentIterator.java b/src/edu/ucla/sspace/text/UkWaCDocumentIterator.java
index 1243d3bb..9a654563 100644
--- a/src/edu/ucla/sspace/text/UkWaCDocumentIterator.java
+++ b/src/edu/ucla/sspace/text/UkWaCDocumentIterator.java
@@ -31,13 +31,11 @@
/**
- * An iterator implementation that returns {@link Document} containg a single
- * dependency parsed sentence given a file in the <a
- * href="http://nextens.uvt.nl/depparse-wiki/DataFormat">CoNLL Format</a>
- *
- * <p>
- *
- * This class is thread-safe.
+ * An iterator implementation that returns {@link Document} instances labled
+ * with the source URL from which its text was obtained, as specified in the
+ * ukWaC. See the <a
+ * href="http://wacky.sslmit.unibo.it/doku.php?id=corpora">WaCky</a> group's
+ * website for more information on the ukWaC.
*/
public class UkWaCDocumentIterator implements Iterator<LabeledDocument> {
diff --git a/src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java b/src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java
index 756b24d2..cb48efa0 100644
--- a/src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java
+++ b/src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java
@@ -28,6 +28,7 @@
import edu.ucla.sspace.util.LoggerUtil;
import edu.ucla.sspace.util.MultiMap;
import edu.ucla.sspace.util.NearestNeighborFinder;
+import edu.ucla.sspace.util.PartitioningNearestNeighborFinder;
import edu.ucla.sspace.util.SerializableUtil;
import java.io.File;
@@ -93,27 +94,29 @@ public static void main(String[] args) {
SemanticSpaceIO.load(options.getStringOption('C'));
int numWords = sspace.getWords().size();
// See how many principle vectors to create
- int principleVectors = -1;
+ int numPrincipleVectors = -1;
if (options.hasOption('p')) {
- principleVectors = options.getIntOption('p');
- if (principleVectors > numWords) {
+ numPrincipleVectors = options.getIntOption('p');
+ if (numPrincipleVectors > numWords) {
throw new IllegalArgumentException(
"Cannot have more principle vectors than " +
- "word vectors: " + principleVectors);
+ "word vectors: " + numPrincipleVectors);
}
- else if (principleVectors < 1) {
+ else if (numPrincipleVectors < 1) {
throw new IllegalArgumentException(
"Must have at least one principle vector");
}
}
else {
- principleVectors =
+ numPrincipleVectors =
Math.min((int)(Math.ceil(Math.log(numWords))), 1000);
System.err.printf("Choosing a heuristically selected %d " +
- "principle vectors%n", principleVectors);
+ "principle vectors%n",
+ numPrincipleVectors);
}
- nnf = new NearestNeighborFinder(sspace, principleVectors);
+ nnf = new PartitioningNearestNeighborFinder(
+ sspace, numPrincipleVectors);
} catch (IOException ioe) {
throw new IOError(ioe);
}
diff --git a/src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java b/src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java
index b22050f1..c7f697f1 100644
--- a/src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java
+++ b/src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java
@@ -26,10 +26,12 @@
import edu.ucla.sspace.common.SemanticSpace;
import edu.ucla.sspace.common.SemanticSpaceIO;
import edu.ucla.sspace.common.Similarity;
-import edu.ucla.sspace.common.WordComparator;
import edu.ucla.sspace.text.WordIterator;
+import edu.ucla.sspace.util.NearestNeighborFinder;
+import edu.ucla.sspace.util.PartitioningNearestNeighborFinder;
+
import edu.ucla.sspace.vector.SparseVector;
import edu.ucla.sspace.vector.Vector;
import edu.ucla.sspace.vector.VectorIO;
@@ -102,12 +104,6 @@ private enum Command {
}
}
- /**
- * The comparator to be used when identifying the nearest neighbors to words
- * in a semantic space.
- */
- private final WordComparator wordComparator;
-
/**
* The mapping from file name to the {@code SemanticSpace} that was loaded
* from that file.
@@ -125,11 +121,16 @@ private enum Command {
*/
private SemanticSpace current;
+ /**
+ * The {@code NearestNeighborFinder} for the current {@code SemanticSpace}
+ * or {@code null} if the nearest terms have yet to be searched for.
+ */
+ private NearestNeighborFinder currentNnf;
+
/**
* Constructs an instance of {@code SemanticSpaceExplorer}.
*/
- private SemanticSpaceExplorer() {
- this.wordComparator = new WordComparator();
+ private SemanticSpaceExplorer() {
fileNameToSSpace = new LinkedHashMap<String,SemanticSpace>();
aliasToFileName = new HashMap<String,String>();
current = null;
@@ -240,6 +241,7 @@ private boolean execute(Iterator<String> commandTokens, PrintStream out) {
}
fileNameToSSpace.put(sspaceFileName, sspace);
current = sspace;
+ currentNnf = null;
break;
}
@@ -319,31 +321,16 @@ private boolean execute(Iterator<String> commandTokens, PrintStream out) {
return false;
}
}
- Similarity.SimType simType = Similarity.SimType.COSINE;
- if (commandTokens.hasNext()) {
- // Upper case since it's an enum
- String simTypeStr = commandTokens.next().toUpperCase();
- try {
- simType = Similarity.SimType.valueOf(simTypeStr);
- } catch (IllegalArgumentException iae) {
- // See if the user provided a prefix of the similarity
- // measure's name
- for (Similarity.SimType t : Similarity.SimType.values())
- if (t.name().startsWith(simTypeStr))
- simType = t;
- // If no prefix was found, report an error
- if (simType == null) {
- out.println("invalid similarity measure: " +simTypeStr);
- return false;
- }
- }
- }
+ // If this is the first time the nearest neighbors have been
+ // searched for, construct a new NNF
+ if (currentNnf == null)
+ currentNnf = new PartitioningNearestNeighborFinder(current);
+
// Using the provided or default arguments find the closest
// neighbors to the target word in the current semantic space
SortedMultiMap<Double,String> mostSimilar =
- wordComparator.getMostSimilar(focusWord, current, neighbors,
- simType);
+ currentNnf.getMostSimilar(focusWord, neighbors);
if (mostSimilar == null) {
out.println(focusWord +
@@ -375,7 +362,7 @@ private boolean execute(Iterator<String> commandTokens, PrintStream out) {
out.println("missing word argument");
return false;
}
- String word2 = commandTokens.next();
+ String word2 = commandTokens.next();
Similarity.SimType simType = Similarity.SimType.COSINE;
if (commandTokens.hasNext()) {
diff --git a/src/edu/ucla/sspace/tools/SimilarityListGenerator.java b/src/edu/ucla/sspace/tools/SimilarityListGenerator.java
index a0dbb5fd..9703a36b 100644
--- a/src/edu/ucla/sspace/tools/SimilarityListGenerator.java
+++ b/src/edu/ucla/sspace/tools/SimilarityListGenerator.java
@@ -26,9 +26,10 @@
import edu.ucla.sspace.common.Similarity.SimType;
import edu.ucla.sspace.common.SemanticSpace;
import edu.ucla.sspace.common.SemanticSpaceIO;
-import edu.ucla.sspace.common.WordComparator;
import edu.ucla.sspace.util.BoundedSortedMap;
+import edu.ucla.sspace.util.NearestNeighborFinder;
+import edu.ucla.sspace.util.PartitioningNearestNeighborFinder;
import edu.ucla.sspace.util.Pair;
import edu.ucla.sspace.util.SortedMultiMap;
@@ -77,9 +78,10 @@ private void addOptions() {
"whether to print the similarity score " +
"(default: false)",
false, null, "Program Options");
- argOptions.addOption('s', "similarityFunction",
- "name of a similarity function (default: cosine)",
- true, "String", "Program Options");
+ // dj: current unsupported; will be next release
+ // argOptions.addOption('s', "similarityFunction",
+ // "name of a similarity function (default: cosine)",
+ // true, "String", "Program Options");
argOptions.addOption('n', "numSimilar", "the number of similar words " +
"to print (default: 10)", true, "String",
"Program Options");
@@ -153,12 +155,13 @@ public void run(String[] args) throws Exception {
// load the behavior options
final boolean printSimilarity = argOptions.hasOption('p');
- String similarityTypeName = (argOptions.hasOption('s'))
- ? argOptions.getStringOption('s').toUpperCase() : "COSINE";
+ // dj: setting the similarity type is currently unsupported but will be
+ // in the next release
- SimType similarityType = SimType.valueOf(similarityTypeName);
-
- LOGGER.fine("using similarity measure: " + similarityType);
+ // String similarityTypeName = (argOptions.hasOption('s'))
+ // ? argOptions.getStringOption('s').toUpperCase() : "COSINE";
+ // SimType similarityType = SimType.valueOf(similarityTypeName);
+ // LOGGER.fine("using similarity measure: " + similarityType);
final int numSimilar = (argOptions.hasOption('n'))
? argOptions.getIntOption('n') : 10;
@@ -175,14 +178,14 @@ public void run(String[] args) throws Exception {
final PrintWriter outputWriter = new PrintWriter(output);
final Set<String> words = sspace.getWords();
- WordComparator comparator = new WordComparator(numThreads);
+ NearestNeighborFinder nnf =
+ new PartitioningNearestNeighborFinder(sspace);
for (String word : words) {
// compute the k most-similar words to this word
SortedMultiMap<Double,String> mostSimilar =
- comparator.getMostSimilar(word, sspace, numSimilar,
- similarityType);
+ nnf.getMostSimilar(word, numSimilar);
// once processing has finished write the k most-similar words to
// the output file.
diff --git a/src/edu/ucla/sspace/util/HashIndexer.java b/src/edu/ucla/sspace/util/HashIndexer.java
index 28a90a79..97807ca6 100644
--- a/src/edu/ucla/sspace/util/HashIndexer.java
+++ b/src/edu/ucla/sspace/util/HashIndexer.java
@@ -37,7 +37,7 @@
/**
* A utility class for mapping a set of objects to unique indices based on
- * object equality. The indices returned by this class will always being at
+ * object equality. The indices returned by this class will always begin at
* {@code 0}.
*
* <p> This implementation provides faster {@link #index(Object)} performance
diff --git a/src/edu/ucla/sspace/util/PairCounter.java b/src/edu/ucla/sspace/util/PairCounter.java
index 89b9f2d1..21591721 100644
--- a/src/edu/ucla/sspace/util/PairCounter.java
+++ b/src/edu/ucla/sspace/util/PairCounter.java
@@ -253,7 +253,7 @@ public Set<Pair<T>> items() {
}
/**
- * Returns an interator over the pairs that have been counted thusfar and
+ * Returns an iterator over the pairs that have been counted thusfar and
* their respective counts.
*/
public Iterator<Map.Entry<Pair<T>,Integer>> iterator() {
diff --git a/src/edu/ucla/sspace/util/NearestNeighborFinder.java b/src/edu/ucla/sspace/util/PartitioningNearestNeighborFinder.java
similarity index 90%
rename from src/edu/ucla/sspace/util/NearestNeighborFinder.java
rename to src/edu/ucla/sspace/util/PartitioningNearestNeighborFinder.java
index c92c8bc4..be4db381 100644
--- a/src/edu/ucla/sspace/util/NearestNeighborFinder.java
+++ b/src/edu/ucla/sspace/util/PartitioningNearestNeighborFinder.java
@@ -65,10 +65,12 @@
* A class for finding the <i>k</i>-nearest neighbors of one or more words. The
* {@code NearestNeighborFinder} operates by generating a set of <b>principle
* vectors</b> that reflect average words in a {@link SemanticSpace} and then
- * identifying mapping each principle vector to the set of words to which it is
- * closest. Finding the nearest neighbor then entails finding the
- * <i>k</i>-closest principle vectors and comparing only their words, rather
- * than all the words in the space. This dramatically reduces the search space.
+ * mapping each principle vector to the set of words to which it is closest.
+ * Finding the nearest neighbor then entails finding the <i>k</i>-closest
+ * principle vectors and comparing only their words, rather than all the words
+ * in the space. This dramatically reduces the search space by partitioning the
+ * vectors of the {@code SemanticSpace} into smaller sets, not all of which need
+ * to be searched.
*
* <p> The number of principle vectors is typically far less than the total
* number of vectors in the {@code SemanticSpace}, but should be more than the
@@ -77,8 +79,14 @@
* (|Sspace| / p))}, where {@code p} is the number of principle components,
* {@code k} is the number of nearest neighbors to be found, and {@code
* |Sspace|} is the size of the semantic space.
+ *
+ * <p> Instances of this class are also serializable. If the backing {@code
+ * SemanticSpace} is also serializable, the space will be saved. However, if
+ * the space is not serializable, its contents will be converted to a static
+ * version and saved as a copy.
*/
-public class NearestNeighborFinder implements java.io.Serializable {
+public class PartitioningNearestNeighborFinder
+ implements NearestNeighborFinder, java.io.Serializable {
private static final long serialVersionUID = 1L;
@@ -86,7 +94,7 @@ public class NearestNeighborFinder implements java.io.Serializable {
* The logger to which clustering status updates will be written.
*/
private static final Logger LOGGER =
- Logger.getLogger(NearestNeighborFinder.class.getName());
+ Logger.getLogger(PartitioningNearestNeighborFinder.class.getName());
/**
* The semantic space from which the principle vectors are derived
@@ -104,29 +112,41 @@ public class NearestNeighborFinder implements java.io.Serializable {
*/
private transient WorkQueue workQueue;
+ /**
+ * Creates a new {@code NearestNeighborFinder} for the {@link
+ * SemanticSpace}, using log<sub>10</log>(|words|) principle vectors to
+ * efficiently search for neighbors.
+ *
+ * @param sspace a semantic space to search
+ */
+ public PartitioningNearestNeighborFinder(SemanticSpace sspace) {
+ this(sspace, (int)(Math.ceil(Math.log10(sspace.getWords().size()))));
+ }
+
/**
* Creates a new {@code NearestNeighborFinder} for the {@link
* SemanticSpace}, using the specified number of principle vectors to
* efficiently search for neighbors.
*
* @param sspace a semantic space to search
- * @param principleVectors the number of principle vectors to use in
+ * @param numPrincipleVectors the number of principle vectors to use in
* representing the content of the space.
*/
- public NearestNeighborFinder(SemanticSpace sspace, int principleVectors) {
+ public PartitioningNearestNeighborFinder(SemanticSpace sspace,
+ int numPrincipleVectors) {
if (sspace == null)
throw new NullPointerException();
- if (principleVectors > sspace.getWords().size())
+ if (numPrincipleVectors > sspace.getWords().size())
throw new IllegalArgumentException(
"Cannot have more principle vectors than " +
- "word vectors: " + principleVectors);
- else if (principleVectors < 1)
+ "word vectors: " + numPrincipleVectors);
+ else if (numPrincipleVectors < 1)
throw new IllegalArgumentException(
"Must have at least one principle vector");
this.sspace = sspace;
principleVectorToNearestTerms = new HashMultiMap<DoubleVector,String>();
workQueue = new WorkQueue();
- computePrincipleVectors(principleVectors);
+ computePrincipleVectors(numPrincipleVectors);
}
/**
@@ -193,7 +213,7 @@ public void run() {
// which it is closest
for (int i = sta; i < end; ++i) {
DoubleVector v = termVectors.get(i);
- double highestSim = Double.NEGATIVE_INFINITY;
+ double highestSim = -Double.MAX_VALUE;
int pVec = -1;
for (int j = 0; j < principles.length; ++j) {
DoubleVector principle = principles[j];
@@ -246,12 +266,7 @@ public void run() {
}
/**
- * Finds the <i>k</i> most similar words in the semantic space according to
- * the cosine similarity, returning a mapping from their similarity to the
- * word itself.
- *
- * @return the most similar words, or {@code null} if the provided word was
- * not in the semantic space.
+ * {@inheritDoc}
*/
public SortedMultiMap<Double,String> getMostSimilar(
final String word, int numberOfSimilarWords) {
@@ -276,12 +291,7 @@ public SortedMultiMap<Double,String> getMostSimilar(
}
/**
- * Finds the <i>k</i> most similar words in the semantic space according to
- * the cosine similarity, returning a mapping from their similarity to the
- * word itself.
- *
- * @return the most similar words, or {@code null} if none of the provided
- * word were not in the semantic space.
+ * {@inheritDoc}
*/
public SortedMultiMap<Double,String> getMostSimilar(
Set<String> terms, int numberOfSimilarWords) {
@@ -323,13 +333,8 @@ public SortedMultiMap<Double,String> getMostSimilar(
return mostSim;
}
-
/**
- * Finds the <i>k</i> most similar words in the semantic space according to
- * the cosine similarity, returning a mapping from their similarity to the
- * word itself.
- *
- * @return the most similar words to the vector
+ * {@inheritDoc}
*/
public SortedMultiMap<Double,String> getMostSimilar(
final Vector v, int numberOfSimilarWords) {
@@ -434,5 +439,4 @@ private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(copy);
}
}
-
}
\ No newline at end of file
diff --git a/src/edu/ucla/sspace/util/ReflectionUtil.java b/src/edu/ucla/sspace/util/ReflectionUtil.java
index a3d4ffb7..583f3b2b 100644
--- a/src/edu/ucla/sspace/util/ReflectionUtil.java
+++ b/src/edu/ucla/sspace/util/ReflectionUtil.java
@@ -48,8 +48,4 @@ public static <T> T getObjectInstance(String className) {
throw new Error(e);
}
}
-
-// public static <T> T[] newArrayInstance(Class<T> c, int length) {
-// return Arrays.newInstance(c, length)
-// }
}
diff --git a/src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java b/src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java
index bcd6e9d3..6577e230 100644
--- a/src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java
+++ b/src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java
@@ -42,7 +42,11 @@
import gnu.trove.procedure.TIntProcedure;
/**
- *
+ * A {@link MultiMap} implementation for mapping {@code int} primitives as both
+ * keys and values using a hashing strategy. This class offers a noticeable
+ * performance improvement over the equivalent {@code
+ * HashMultiMap<Integer,Integer>} by operating and representing the keys
+ * and values only in their primitive state.
*/
public class IntIntHashMultiMap implements IntIntMultiMap {
diff --git a/src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java b/src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java
index 499a7527..f511b3df 100644
--- a/src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java
+++ b/src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java
@@ -35,7 +35,8 @@
/**
- *
+ * A {@link MultiMap} subinterface for mapping {@code int} primitives as both
+ * keys and values.
*/
public interface IntIntMultiMap extends MultiMap<Integer,Integer> {
diff --git a/test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java b/test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java
index 2d956032..bd88c5fc 100644
--- a/test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java
+++ b/test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java
@@ -38,29 +38,29 @@
public class BreadthFirstPathIteratorTest extends PathIteratorTestBase {
String conll =
- "Anarchism anarchism NN 1 2 SBJ\n" +
- "is be VBZ 2 0 ROOT\n" +
- "a a DT 3 5 NMOD\n" +
- "political political JJ 4 5 NMOD\n" +
- "philosophy philosophy NN 5 2 PRD\n" +
- "encompassing encompass VVG 6 5 NMOD\n" +
- "theories theory NNS 7 6 OBJ\n" +
- "and and CC 8 7 CC\n" +
- "attitudes attitude NNS 9 7 COORD\n" +
- "which which WDT 10 11 SBJ\n" +
- "consider consider VVP 11 9 NMOD\n" +
- "the the DT 12 13 NMOD\n" +
- "state state NN 13 15 SBJ\n" +
- "to t TO 14 15 VMOD\n" +
- "be be VB 15 11 OBJ\n" +
- "unnecessary unnecessary JJ 16 15 PRD\n" +
- ", , , 17 16 P\n" +
- "harmul harmful JJ 18 16 COORD\n" +
- ", , , 19 16 P\n" +
- "and/ ad/ JJ 20 16 COORD\n" +
- "or or CC 21 16 CC\n" +
- "undesirable undesirable JJ 22 16 COORD\n" +
- ". . SENT 23 2 P\n";
+ "Anarchism\tanarchism\tNN\t1\t2\tSBJ\n" +
+ "is\tbe\tVBZ\t2\t0\tROOT\n" +
+ "a\ta\tDT\t3\t5\tNMOD\n" +
+ "political\tpolitical\tJJ\t4\t5\tNMOD\n" +
+ "philosophy\tphilosophy\tNN\t5\t2\tPRD\n" +
+ "encompassing\tencompass\tVVG\t6\t5\tNMOD\n" +
+ "theories\ttheory\tNNS\t7\t6\tOBJ\n" +
+ "and\tand\tCC\t8\t7\tCC\n"+
+ "attitudes\tattitude\tNNS\t9\t7\tCOORD\n"+
+ "which\twhich\tWDT\t10\t11\tSBJ\n"+
+ "consider\tconsider\tVVP\t11\t9\tNMOD\n"+
+ "the\tthe\tDT\t12\t13\tNMOD\n"+
+ "state\tstate\tNN\t13\t15\tSBJ\n"+
+ "to\tt\tTO\t14\t15\tVMOD\n"+
+ "be\tbe\tVB\t15\t11\tOBJ\n"+
+ "unnecessary\tunnecessary\tJJ\t16\t15\tPRD\n"+
+ ",\t,\t,\t17\t16\tP\n"+
+ "harmul\tharmful\tJJ\t18\t16\tCOORD\n"+
+ ",\t,\t,\t19\t16\tP\n"+
+ "and/\tad/\tJJ\t20\t16\tCOORD\n"+
+ "or\tor\tCC\t21\t16\tCC\n"+
+ "undesirable\tundesirable\tJJ\t22\t16\tCOORD\n"+
+ ".\t.\tSENT\t23\t2\tP\n";
static final Map<String,Integer> PATH_START_COUNTS
= new TreeMap<String,Integer>();
diff --git a/test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java b/test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java
index f0667223..06e9ae30 100644
--- a/test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java
+++ b/test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java
@@ -24,6 +24,8 @@
import edu.ucla.sspace.text.StringDocument;
import edu.ucla.sspace.text.Document;
+import java.io.BufferedReader;
+
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
@@ -99,6 +101,8 @@ protected void evaluateRelations(DependencyTreeNode node,
// Check that all the neighbors are in the e
for (DependencyRelation rel : node.neighbors()) {
System.out.println("relation: " + rel);
+ if (!expectedRelations.contains(rel))
+ System.out.printf("FAIL: %s does not contain %s%n", expectedRelations, rel);
assertTrue(expectedRelations.contains(rel));
// Remove the relation from the list to double check that the
// neighbors are a list of duplicate relations.
@@ -120,7 +124,7 @@ protected void testFirstRoot(DependencyTreeNode[] relations, int index) {
DependencyRelation[] expectedRelations = new DependencyRelation[] {
new SimpleDependencyRelation(new SimpleDependencyTreeNode("is", "VBZ"),
"SBJ",
- new SimpleDependencyTreeNode("holt", "NNP")),
+ new SimpleDependencyTreeNode("Holt", "NNP")),
new SimpleDependencyRelation(new SimpleDependencyTreeNode("is", "VBZ"),
"PRD",
new SimpleDependencyTreeNode("columnist", "NN")),
@@ -145,7 +149,7 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) {
DependencyRelation[] expectedRelations = new DependencyRelation[] {
new SimpleDependencyRelation(new SimpleDependencyTreeNode("beskattning", "N"),
"AT",
- new SimpleDependencyTreeNode("individuell", "AJ")),
+ new SimpleDependencyTreeNode("Individuell", "AJ")),
new SimpleDependencyRelation(new SimpleDependencyTreeNode("beskattning", "N"),
"ET",
new SimpleDependencyTreeNode("av", "PR"))
@@ -157,29 +161,29 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) {
@Test public void testSingleExtraction() throws Exception {
DependencyExtractor extractor = new CoNLLDependencyExtractor();
- Document doc = new StringDocument(SINGLE_PARSE);
+ Document doc = new StringDocument(toTabs(SINGLE_PARSE));
DependencyTreeNode[] nodes = extractor.readNextTree(doc.reader());
assertEquals(12, nodes.length);
// Check the basics of the node.
- assertEquals("review", nodes[8].word());
+ assertEquals("Review", nodes[8].word());
assertEquals("NNP", nodes[8].pos());
// Test expected relation for each of the links for "Review".
DependencyRelation[] expectedRelations = new DependencyRelation[] {
- new SimpleDependencyRelation(new SimpleDependencyTreeNode("review", "NNP"),
+ new SimpleDependencyRelation(new SimpleDependencyTreeNode("Review", "NNP"),
"NMOD",
new SimpleDependencyTreeNode("the", "DT")),
- new SimpleDependencyRelation(new SimpleDependencyTreeNode("review", "NNP"),
+ new SimpleDependencyRelation(new SimpleDependencyTreeNode("Review", "NNP"),
"NMOD",
- new SimpleDependencyTreeNode("literary", "NNP")),
- new SimpleDependencyRelation(new SimpleDependencyTreeNode("review", "NNP"),
+ new SimpleDependencyTreeNode("Literary", "NNP")),
+ new SimpleDependencyRelation(new SimpleDependencyTreeNode("Review", "NNP"),
"ADV",
new SimpleDependencyTreeNode("in", "IN")),
new SimpleDependencyRelation(new SimpleDependencyTreeNode("for", "IN"),
"PMOD",
- new SimpleDependencyTreeNode("review", "NNP"))
+ new SimpleDependencyTreeNode("Review", "NNP"))
};
evaluateRelations(nodes[8], new LinkedList<DependencyRelation>(Arrays.asList(expectedRelations)));
@@ -187,14 +191,18 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) {
@Test public void testDoubleExtraction() throws Exception {
DependencyExtractor extractor = new CoNLLDependencyExtractor();
- Document doc = new StringDocument(DOUBLE_PARSE);
- DependencyTreeNode[] relations = extractor.readNextTree(doc.reader());
+ Document doc = new StringDocument("\n\n" +
+ toTabs(SINGLE_PARSE) +
+ "\n" +
+ toTabs(SECOND_PARSE));
+ BufferedReader reader = doc.reader();
+ DependencyTreeNode[] relations = extractor.readNextTree(reader);
assertTrue(relations != null);
assertEquals(12, relations.length);
testFirstRoot(relations, 2);
- relations = extractor.readNextTree(doc.reader());
+ relations = extractor.readNextTree(reader);
assertTrue(relations != null);
assertEquals(4, relations.length);
@@ -203,7 +211,7 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) {
@Test public void testRootNode() throws Exception {
DependencyExtractor extractor = new CoNLLDependencyExtractor();
- Document doc = new StringDocument(SINGLE_PARSE);
+ Document doc = new StringDocument(toTabs(SINGLE_PARSE));
DependencyTreeNode[] relations = extractor.readNextTree(doc.reader());
assertEquals(12, relations.length);
@@ -213,7 +221,7 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) {
@Test public void testConcatonatedTrees() throws Exception {
DependencyExtractor extractor = new CoNLLDependencyExtractor();
- Document doc = new StringDocument(CONCATONATED_PARSE);
+ Document doc = new StringDocument(toTabs(CONCATONATED_PARSE));
DependencyTreeNode[] relations = extractor.readNextTree(doc.reader());
assertEquals(16, relations.length);
@@ -223,11 +231,26 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) {
@Test public void testConcatonatedTreesZeroOffset() throws Exception {
DependencyExtractor extractor = new CoNLLDependencyExtractor();
- Document doc = new StringDocument(DOUBLE_ZERO_OFFSET_PARSE);
+ Document doc = new StringDocument(toTabs(DOUBLE_ZERO_OFFSET_PARSE));
DependencyTreeNode[] relations = extractor.readNextTree(doc.reader());
assertEquals(16, relations.length);
testFirstRoot(relations, 2);
testSecondRoot(relations, 13);
}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
}
diff --git a/test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java b/test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java
index 8f466cdc..74a1ebbe 100644
--- a/test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java
+++ b/test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java
@@ -24,6 +24,8 @@
import edu.ucla.sspace.text.StringDocument;
import edu.ucla.sspace.text.Document;
+import java.io.BufferedReader;
+
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
@@ -90,29 +92,29 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest {
@Test public void testSingleExtraction() throws Exception {
DependencyExtractor extractor = new WaCKyDependencyExtractor();
- Document doc = new StringDocument(SINGLE_PARSE);
+ Document doc = new StringDocument(toTabs(SINGLE_PARSE));
DependencyTreeNode[] nodes = extractor.readNextTree(doc.reader());
assertEquals(12, nodes.length);
// Check the basics of the node.
- assertEquals("review", nodes[8].word());
+ assertEquals("Review", nodes[8].word());
assertEquals("NNP", nodes[8].pos());
// Test expected relation for each of the links for "Review".
DependencyRelation[] expectedRelations = new DependencyRelation[] {
- new SimpleDependencyRelation(new SimpleDependencyTreeNode("review", "NNP"),
+ new SimpleDependencyRelation(new SimpleDependencyTreeNode("Review", "NNP"),
"NMOD",
new SimpleDependencyTreeNode("the", "DT")),
- new SimpleDependencyRelation(new SimpleDependencyTreeNode("review", "NNP"),
+ new SimpleDependencyRelation(new SimpleDependencyTreeNode("Review", "NNP"),
"NMOD",
- new SimpleDependencyTreeNode("literary", "NNP")),
- new SimpleDependencyRelation(new SimpleDependencyTreeNode("review", "NNP"),
+ new SimpleDependencyTreeNode("Literary", "NNP")),
+ new SimpleDependencyRelation(new SimpleDependencyTreeNode("Review", "NNP"),
"ADV",
new SimpleDependencyTreeNode("in", "IN")),
new SimpleDependencyRelation(new SimpleDependencyTreeNode("for", "IN"),
"PMOD",
- new SimpleDependencyTreeNode("review", "NNP"))
+ new SimpleDependencyTreeNode("Review", "NNP"))
};
evaluateRelations(nodes[8], new LinkedList<DependencyRelation>(Arrays.asList(expectedRelations)));
@@ -120,14 +122,15 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest {
@Test public void testDoubleExtraction() throws Exception {
DependencyExtractor extractor = new WaCKyDependencyExtractor();
- Document doc = new StringDocument(DOUBLE_PARSE);
- DependencyTreeNode[] relations = extractor.readNextTree(doc.reader());
+ Document doc = new StringDocument(toTabs(DOUBLE_PARSE));
+ BufferedReader reader = doc.reader();
+ DependencyTreeNode[] relations = extractor.readNextTree(reader);
assertTrue(relations != null);
assertEquals(12, relations.length);
testFirstRoot(relations, 2);
- relations = extractor.readNextTree(doc.reader());
+ relations = extractor.readNextTree(reader);
assertTrue(relations != null);
assertEquals(4, relations.length);
@@ -136,7 +139,7 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest {
@Test public void testRootNode() throws Exception {
DependencyExtractor extractor = new WaCKyDependencyExtractor();
- Document doc = new StringDocument(SINGLE_PARSE);
+ Document doc = new StringDocument(toTabs(SINGLE_PARSE));
DependencyTreeNode[] relations = extractor.readNextTree(doc.reader());
assertEquals(12, relations.length);
@@ -146,7 +149,7 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest {
@Test public void testConcatonatedTrees() throws Exception {
DependencyExtractor extractor = new WaCKyDependencyExtractor();
- Document doc = new StringDocument(CONCATONATED_PARSE);
+ Document doc = new StringDocument(toTabs(CONCATONATED_PARSE));
DependencyTreeNode[] relations = extractor.readNextTree(doc.reader());
assertEquals(16, relations.length);
@@ -156,11 +159,26 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest {
@Test public void testConcatonatedTreesZeroOffset() throws Exception {
DependencyExtractor extractor = new WaCKyDependencyExtractor();
- Document doc = new StringDocument(DOUBLE_ZERO_OFFSET_PARSE);
+ Document doc = new StringDocument(toTabs(DOUBLE_ZERO_OFFSET_PARSE));
DependencyTreeNode[] relations = extractor.readNextTree(doc.reader());
assertEquals(16, relations.length);
testFirstRoot(relations, 2);
testSecondRoot(relations, 13);
}
-}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
+}
\ No newline at end of file
diff --git a/test/edu/ucla/sspace/graph/DirectedMultigraphTests.java b/test/edu/ucla/sspace/graph/DirectedMultigraphTests.java
index eb6102f5..73424070 100644
--- a/test/edu/ucla/sspace/graph/DirectedMultigraphTests.java
+++ b/test/edu/ucla/sspace/graph/DirectedMultigraphTests.java
@@ -36,1182 +36,1182 @@
*/
public class DirectedMultigraphTests {
-// @Test public void testConstructor() {
-// Set<Integer> vertices = new HashSet<Integer>();
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// assertEquals(0, g.order());
-// assertEquals(0, g.size());
-// }
-
-// @Test(expected=NullPointerException.class) public void testConstructor2NullArg() {
-// Graph<Edge> g = new SparseUndirectedGraph((Graph<DirectedTypedEdge<String>>)null);
-// }
-
-// @Test public void testAdd() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// assertTrue(g.add(0));
-// assertEquals(1, g.order());
-// assertTrue(g.contains(0));
-// // second add should have no effect
-// assertFalse(g.add(0));
-// assertEquals(1, g.order());
-// assertTrue(g.contains(0));
-
-// assertTrue(g.add(1));
-// assertEquals(2, g.order());
-// assertTrue(g.contains(1));
-// }
-
-// @Test public void testEquals() {
-// DirectedMultigraph<String> g1 = new DirectedMultigraph<String>();
-// DirectedMultigraph<String> g2 = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// g2.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-// }
-// assertEquals(g1, g2);
-
-// g1 = new DirectedMultigraph<String>();
-// g2 = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// g2.add(new SimpleDirectedTypedEdge<String>("type-1",j, i));
-// }
-// }
-
-// assertFalse(g1.equals(g2));
-// assertFalse(g2.equals(g1));
-// }
-
-// @Test public void testEqualGeneric() {
-// DirectedMultigraph<String> g1 = new DirectedMultigraph<String>();
-// Graph<DirectedTypedEdge<String>> g2 = new GenericGraph<DirectedTypedEdge<String>>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// g2.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-// }
-// assertEquals(g1, g2);
-// }
-
-// @Test public void testContainsEdge() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 100; ++i)
-// for (int j = i + 1; j < 100; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-
-// for (int i = 0; i < 100; ++i) {
-// for (int j = i + 1; j < 100; ++j) {
-// g.contains(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// g.contains(new SimpleDirectedTypedEdge<String>("type-1",j, i));
-// g.contains(i, j);
-// g.contains(j, i);
-// }
-// }
-// }
-
-// @Test public void testAddEdge() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
-// assertEquals(2, g.order());
-// assertEquals(1, g.size());
-// assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
-
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 2));
-// assertEquals(3, g.order());
-// assertEquals(2, g.size());
-// assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 2)));
-
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",3, 4));
-// assertEquals(5, g.order());
-// assertEquals(3, g.size());
-// assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",3, 4)));
-// }
-
-// @Test public void testRemoveLesserVertexWithEdges() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// for (int i = 1; i < 100; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
-// g.add(e);
-// }
+ @Test public void testConstructor() {
+ Set<Integer> vertices = new HashSet<Integer>();
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ assertEquals(0, g.order());
+ assertEquals(0, g.size());
+ }
+
+ @Test(expected=NullPointerException.class) public void testConstructor2NullArg() {
+ Graph<Edge> g = new SparseUndirectedGraph((Graph<DirectedTypedEdge<String>>)null);
+ }
+
+ @Test public void testAdd() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ assertTrue(g.add(0));
+ assertEquals(1, g.order());
+ assertTrue(g.contains(0));
+ // second add should have no effect
+ assertFalse(g.add(0));
+ assertEquals(1, g.order());
+ assertTrue(g.contains(0));
+
+ assertTrue(g.add(1));
+ assertEquals(2, g.order());
+ assertTrue(g.contains(1));
+ }
+
+ @Test public void testEquals() {
+ DirectedMultigraph<String> g1 = new DirectedMultigraph<String>();
+ DirectedMultigraph<String> g2 = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ g2.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+ }
+ assertEquals(g1, g2);
+
+ g1 = new DirectedMultigraph<String>();
+ g2 = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ g2.add(new SimpleDirectedTypedEdge<String>("type-1",j, i));
+ }
+ }
+
+ assertFalse(g1.equals(g2));
+ assertFalse(g2.equals(g1));
+ }
+
+ @Test public void testEqualGeneric() {
+ DirectedMultigraph<String> g1 = new DirectedMultigraph<String>();
+ Graph<DirectedTypedEdge<String>> g2 = new GenericGraph<DirectedTypedEdge<String>>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ g2.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+ }
+ assertEquals(g1, g2);
+ }
+
+ @Test public void testContainsEdge() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 100; ++i)
+ for (int j = i + 1; j < 100; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+
+ for (int i = 0; i < 100; ++i) {
+ for (int j = i + 1; j < 100; ++j) {
+ g.contains(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ g.contains(new SimpleDirectedTypedEdge<String>("type-1",j, i));
+ g.contains(i, j);
+ g.contains(j, i);
+ }
+ }
+ }
+
+ @Test public void testAddEdge() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
+ assertEquals(2, g.order());
+ assertEquals(1, g.size());
+ assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
+
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 2));
+ assertEquals(3, g.order());
+ assertEquals(2, g.size());
+ assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 2)));
+
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",3, 4));
+ assertEquals(5, g.order());
+ assertEquals(3, g.size());
+ assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",3, 4)));
+ }
+
+ @Test public void testRemoveLesserVertexWithEdges() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ for (int i = 1; i < 100; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
+ g.add(e);
+ }
-// assertTrue(g.contains(0));
-// assertTrue(g.remove(0));
-// assertEquals(99, g.order());
-// assertEquals(0, g.size());
-// }
-
-// @Test public void testRemoveHigherVertexWithEdges() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// for (int i = 0; i < 99; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",100, i);
-// g.add(e);
-// }
+ assertTrue(g.contains(0));
+ assertTrue(g.remove(0));
+ assertEquals(99, g.order());
+ assertEquals(0, g.size());
+ }
+
+ @Test public void testRemoveHigherVertexWithEdges() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ for (int i = 0; i < 99; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",100, i);
+ g.add(e);
+ }
-// assertTrue(g.contains(100));
-// assertTrue(g.remove(100));
-// assertEquals(99, g.order());
-// assertEquals(0, g.size());
-// }
-
-
-// @Test public void testRemoveVertex() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// }
-
-// for (int i = 99; i >= 0; --i) {
-// assertTrue(g.remove(i));
-// assertEquals(i, g.order());
-// assertFalse(g.contains(i));
-// assertFalse(g.remove(i));
-// }
-// }
-
-// @Test public void testRemoveEdge() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// for (int i = 1; i < 100; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
-// g.add(e);
-// }
+ assertTrue(g.contains(100));
+ assertTrue(g.remove(100));
+ assertEquals(99, g.order());
+ assertEquals(0, g.size());
+ }
+
+
+ @Test public void testRemoveVertex() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ }
+
+ for (int i = 99; i >= 0; --i) {
+ assertTrue(g.remove(i));
+ assertEquals(i, g.order());
+ assertFalse(g.contains(i));
+ assertFalse(g.remove(i));
+ }
+ }
+
+ @Test public void testRemoveEdge() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ for (int i = 1; i < 100; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
+ g.add(e);
+ }
-// for (int i = 99; i > 0; --i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
-// assertTrue(g.remove(e));
-// assertEquals(i-1, g.size());
-// assertFalse(g.contains(e));
-// assertFalse(g.remove(e));
-// }
-// }
-
-// @Test public void testVertexIterator() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-// assertEquals(control.size(), g.order());
-// for (Integer i : g.vertices())
-// assertTrue(control.contains(i));
-// }
-
-// @Test public void testEdgeIterator() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
-// for (int i = 1; i <= 100; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
-// g.add(e);
-// control.add(e);
-// }
-
-// assertEquals(control.size(), g.size());
-// assertEquals(control.size(), g.edges().size());
-// int returned = 0;
-// for (Edge e : g.edges()) {
-// assertTrue(control.remove(e));
-// returned++;
-// }
-// assertEquals(g.size(), returned);
-// assertEquals(0, control.size());
-// }
-
-// @Test public void testEdgeIteratorSmall() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
-// for (int i = 1; i <= 5; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
-// assertTrue(g.add(e));
-// control.add(e);
-// }
-
-// assertEquals(control.size(), g.size());
-// assertEquals(control.size(), g.edges().size());
-// int returned = 0;
-// for (Edge e : g.edges()) {
-// System.out.println(e);
-// assertTrue(control.contains(e));
-// returned++;
-// }
-// assertEquals(control.size(), returned);
-// }
-
-// @Test public void testEdgeIteratorSmallReverse() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
-// for (int i = 1; i <= 5; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, 0);
-// g.add(e);
-// control.add(e);
-// }
-
-// assertEquals(control.size(), g.size());
-// assertEquals(control.size(), g.edges().size());
-// int returned = 0;
-// for (Edge e : g.edges()) {
-// System.out.println(e);
-// assertTrue(control.contains(e));
-// returned++;
-// }
-// assertEquals(control.size(), returned);
-// }
-
-
-// @Test public void testAdjacentEdges() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
-// for (int i = 1; i <= 100; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
-// g.add(e);
-// control.add(e);
-// }
+ for (int i = 99; i > 0; --i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
+ assertTrue(g.remove(e));
+ assertEquals(i-1, g.size());
+ assertFalse(g.contains(e));
+ assertFalse(g.remove(e));
+ }
+ }
+
+ @Test public void testVertexIterator() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+ assertEquals(control.size(), g.order());
+ for (Integer i : g.vertices())
+ assertTrue(control.contains(i));
+ }
+
+ @Test public void testEdgeIterator() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
+ for (int i = 1; i <= 100; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
+ g.add(e);
+ control.add(e);
+ }
+
+ assertEquals(control.size(), g.size());
+ assertEquals(control.size(), g.edges().size());
+ int returned = 0;
+ for (Edge e : g.edges()) {
+ assertTrue(control.remove(e));
+ returned++;
+ }
+ assertEquals(g.size(), returned);
+ assertEquals(0, control.size());
+ }
+
+ @Test public void testEdgeIteratorSmall() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
+ for (int i = 1; i <= 5; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
+ assertTrue(g.add(e));
+ control.add(e);
+ }
+
+ assertEquals(control.size(), g.size());
+ assertEquals(control.size(), g.edges().size());
+ int returned = 0;
+ for (Edge e : g.edges()) {
+ System.out.println(e);
+ assertTrue(control.contains(e));
+ returned++;
+ }
+ assertEquals(control.size(), returned);
+ }
+
+ @Test public void testEdgeIteratorSmallReverse() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
+ for (int i = 1; i <= 5; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, 0);
+ g.add(e);
+ control.add(e);
+ }
+
+ assertEquals(control.size(), g.size());
+ assertEquals(control.size(), g.edges().size());
+ int returned = 0;
+ for (Edge e : g.edges()) {
+ System.out.println(e);
+ assertTrue(control.contains(e));
+ returned++;
+ }
+ assertEquals(control.size(), returned);
+ }
+
+
+ @Test public void testAdjacentEdges() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
+ for (int i = 1; i <= 100; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
+ g.add(e);
+ control.add(e);
+ }
-// Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0);
-// assertEquals(control, test);
-// }
-
-// @Test public void testAdjacencyListSize() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
+ Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0);
+ assertEquals(control, test);
+ }
+
+ @Test public void testAdjacencyListSize() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
-// Set<DirectedTypedEdge<String>> adjList = g.getAdjacencyList(0);
-// assertEquals(9, adjList.size());
+ Set<DirectedTypedEdge<String>> adjList = g.getAdjacencyList(0);
+ assertEquals(9, adjList.size());
-// adjList = g.getAdjacencyList(1);
-// assertEquals(9, adjList.size());
+ adjList = g.getAdjacencyList(1);
+ assertEquals(9, adjList.size());
-// adjList = g.getAdjacencyList(2);
-// assertEquals(9, adjList.size());
+ adjList = g.getAdjacencyList(2);
+ assertEquals(9, adjList.size());
-// adjList = g.getAdjacencyList(3);
-// assertEquals(9, adjList.size());
+ adjList = g.getAdjacencyList(3);
+ assertEquals(9, adjList.size());
-// adjList = g.getAdjacencyList(5);
-// assertEquals(9, adjList.size());
-// }
+ adjList = g.getAdjacencyList(5);
+ assertEquals(9, adjList.size());
+ }
-// @Test public void testAdjacentEdgesRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
-// for (int i = 1; i <= 100; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
-// g.add(e);
-// control.add(e);
-// }
+ @Test public void testAdjacentEdgesRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
+ for (int i = 1; i <= 100; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
+ g.add(e);
+ control.add(e);
+ }
-// Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0);
-// assertEquals(control, test);
-
-// Edge removed = new SimpleDirectedTypedEdge<String>("type-1",0, 1);
-// assertTrue(test.remove(removed));
-// assertTrue(control.remove(removed));
-// assertEquals(control, test);
-// assertEquals(99, g.size());
-// }
-
-// @Test public void testAdjacentEdgesAdd() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
-// for (int i = 1; i <= 100; ++i) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
-// g.add(e);
-// control.add(e);
-// }
+ Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0);
+ assertEquals(control, test);
+
+ Edge removed = new SimpleDirectedTypedEdge<String>("type-1",0, 1);
+ assertTrue(test.remove(removed));
+ assertTrue(control.remove(removed));
+ assertEquals(control, test);
+ assertEquals(99, g.size());
+ }
+
+ @Test public void testAdjacentEdgesAdd() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
+ for (int i = 1; i <= 100; ++i) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i);
+ g.add(e);
+ control.add(e);
+ }
-// Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0);
-// assertEquals(control, test);
-
-// DirectedTypedEdge<String> added = new SimpleDirectedTypedEdge<String>("type-1",0, 101);
-// assertTrue(test.add(added));
-// assertTrue(control.add(added));
-// assertEquals(control, test);
-// assertEquals(101, g.size());
-// assertTrue(g.contains(added));
-// assertTrue(g.contains(101));
-// assertEquals(102, g.order());
-// }
-
-// @Test public void testClear() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// g.clear();
-// assertEquals(0, g.size());
-// assertEquals(0, g.order());
-// assertEquals(0, g.vertices().size());
-// assertEquals(0, g.edges().size());
+ Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0);
+ assertEquals(control, test);
+
+ DirectedTypedEdge<String> added = new SimpleDirectedTypedEdge<String>("type-1",0, 101);
+ assertTrue(test.add(added));
+ assertTrue(control.add(added));
+ assertEquals(control, test);
+ assertEquals(101, g.size());
+ assertTrue(g.contains(added));
+ assertTrue(g.contains(101));
+ assertEquals(102, g.order());
+ }
+
+ @Test public void testClear() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ g.clear();
+ assertEquals(0, g.size());
+ assertEquals(0, g.order());
+ assertEquals(0, g.vertices().size());
+ assertEquals(0, g.edges().size());
-// // Error checking case for double-clear
-// g.clear();
-// }
-
-// @Test public void testClearEdges() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// g.clearEdges();
-// assertEquals(0, g.size());
-// assertEquals(10, g.order());
-// assertEquals(10, g.vertices().size());
-// assertEquals(0, g.edges().size());
+ // Error checking case for double-clear
+ g.clear();
+ }
+
+ @Test public void testClearEdges() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ g.clearEdges();
+ assertEquals(0, g.size());
+ assertEquals(10, g.order());
+ assertEquals(10, g.vertices().size());
+ assertEquals(0, g.edges().size());
-// // Error checking case for double-clear
-// g.clearEdges();
-// }
-
-// @Test public void testToString() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i)
-// for (int j = i + 1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// g.toString();
-
-// // only vertices
-// g.clearEdges();
-// g.toString();
-
-// // empty graph
-// g.clear();
-// g.toString();
+ // Error checking case for double-clear
+ g.clearEdges();
+ }
+
+ @Test public void testToString() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i)
+ for (int j = i + 1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ g.toString();
+
+ // only vertices
+ g.clearEdges();
+ g.toString();
+
+ // empty graph
+ g.clear();
+ g.toString();
-// }
-
-// /******************************************************************
-// *
-// *
-// * VertexSet tests
-// *
-// *
-// ******************************************************************/
-
-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetAdd() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-
-// Set<Integer> vertices = g.vertices();
-// assertEquals(control.size(), vertices.size());
-// assertTrue(vertices.add(100));
-// assertTrue(g.contains(100));
-// assertEquals(101, vertices.size());
-// assertEquals(101, g.order());
+ }
+
+ /******************************************************************
+ *
+ *
+ * VertexSet tests
+ *
+ *
+ ******************************************************************/
+
+ @Test(expected=UnsupportedOperationException.class) public void testVertexSetAdd() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+
+ Set<Integer> vertices = g.vertices();
+ assertEquals(control.size(), vertices.size());
+ assertTrue(vertices.add(100));
+ assertTrue(g.contains(100));
+ assertEquals(101, vertices.size());
+ assertEquals(101, g.order());
-// // dupe
-// assertFalse(vertices.add(100));
-// assertEquals(101, vertices.size());
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetAddFromGraph() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-
-// Set<Integer> vertices = g.vertices();
-// assertEquals(control.size(), vertices.size());
-// assertTrue(g.add(100));
-// assertTrue(g.contains(100));
-// assertTrue(vertices.contains(100));
-// assertEquals(101, vertices.size());
-// assertEquals(101, g.order());
+ // dupe
+ assertFalse(vertices.add(100));
+ assertEquals(101, vertices.size());
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testVertexSetAddFromGraph() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+
+ Set<Integer> vertices = g.vertices();
+ assertEquals(control.size(), vertices.size());
+ assertTrue(g.add(100));
+ assertTrue(g.contains(100));
+ assertTrue(vertices.contains(100));
+ assertEquals(101, vertices.size());
+ assertEquals(101, g.order());
-// // dupe
-// assertFalse(vertices.add(100));
-// assertEquals(101, vertices.size());
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-
-// Set<Integer> vertices = g.vertices();
-// assertEquals(control.size(), vertices.size());
-// assertTrue(g.contains(99));
-// assertTrue(vertices.remove(99));
-// assertFalse(g.contains(99));
-// assertEquals(99, vertices.size());
-// assertEquals(99, g.order());
+ // dupe
+ assertFalse(vertices.add(100));
+ assertEquals(101, vertices.size());
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testVertexSetRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+
+ Set<Integer> vertices = g.vertices();
+ assertEquals(control.size(), vertices.size());
+ assertTrue(g.contains(99));
+ assertTrue(vertices.remove(99));
+ assertFalse(g.contains(99));
+ assertEquals(99, vertices.size());
+ assertEquals(99, g.order());
-// // dupe
-// assertFalse(vertices.remove(99));
-// assertEquals(99, vertices.size());
-// }
-
-// @Test public void testVertexSetRemoveFromGraph() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-
-// Set<Integer> vertices = g.vertices();
-// assertEquals(control.size(), vertices.size());
-// assertTrue(g.remove(99));
-
-// assertFalse(g.contains(99));
-// assertFalse(vertices.contains(99));
-// assertEquals(99, vertices.size());
-// assertEquals(99, g.order());
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-
-// Set<Integer> vertices = g.vertices();
-// assertEquals(control.size(), vertices.size());
-// Iterator<Integer> iter = vertices.iterator();
-// assertTrue(iter.hasNext());
-// Integer toRemove = iter.next();
-// assertTrue(g.contains(toRemove));
-// assertTrue(vertices.contains(toRemove));
-// iter.remove();
-// assertFalse(g.contains(toRemove));
-// assertFalse(vertices.contains(toRemove));
-// assertEquals(g.order(), vertices.size());
-// }
-
-// @Test(expected=NoSuchElementException.class) public void testVertexSetIteratorTooFar() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-
-// Set<Integer> vertices = g.vertices();
-// Iterator<Integer> iter = vertices.iterator();
-// int i = 0;
-// while (iter.hasNext()) {
-// i++;
-// iter.next();
-// }
-// assertEquals(vertices.size(), i);
-// iter.next();
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveTwice() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-
-// Set<Integer> vertices = g.vertices();
-// Iterator<Integer> iter = vertices.iterator();
-// assertTrue(iter.hasNext());
-// Integer toRemove = iter.next();
-// assertTrue(g.contains(toRemove));
-// assertTrue(vertices.contains(toRemove));
-// iter.remove();
-// iter.remove();
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveEarly() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<Integer> control = new HashSet<Integer>();
-// for (int i = 0; i < 100; ++i) {
-// g.add(i);
-// control.add(i);
-// }
-
-// Set<Integer> vertices = g.vertices();
-// Iterator<Integer> iter = vertices.iterator();
-// iter.remove();
-// }
+ // dupe
+ assertFalse(vertices.remove(99));
+ assertEquals(99, vertices.size());
+ }
+
+ @Test public void testVertexSetRemoveFromGraph() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+
+ Set<Integer> vertices = g.vertices();
+ assertEquals(control.size(), vertices.size());
+ assertTrue(g.remove(99));
+
+ assertFalse(g.contains(99));
+ assertFalse(vertices.contains(99));
+ assertEquals(99, vertices.size());
+ assertEquals(99, g.order());
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+
+ Set<Integer> vertices = g.vertices();
+ assertEquals(control.size(), vertices.size());
+ Iterator<Integer> iter = vertices.iterator();
+ assertTrue(iter.hasNext());
+ Integer toRemove = iter.next();
+ assertTrue(g.contains(toRemove));
+ assertTrue(vertices.contains(toRemove));
+ iter.remove();
+ assertFalse(g.contains(toRemove));
+ assertFalse(vertices.contains(toRemove));
+ assertEquals(g.order(), vertices.size());
+ }
+
+ @Test(expected=NoSuchElementException.class) public void testVertexSetIteratorTooFar() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+
+ Set<Integer> vertices = g.vertices();
+ Iterator<Integer> iter = vertices.iterator();
+ int i = 0;
+ while (iter.hasNext()) {
+ i++;
+ iter.next();
+ }
+ assertEquals(vertices.size(), i);
+ iter.next();
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveTwice() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+
+ Set<Integer> vertices = g.vertices();
+ Iterator<Integer> iter = vertices.iterator();
+ assertTrue(iter.hasNext());
+ Integer toRemove = iter.next();
+ assertTrue(g.contains(toRemove));
+ assertTrue(vertices.contains(toRemove));
+ iter.remove();
+ iter.remove();
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveEarly() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<Integer> control = new HashSet<Integer>();
+ for (int i = 0; i < 100; ++i) {
+ g.add(i);
+ control.add(i);
+ }
+
+ Set<Integer> vertices = g.vertices();
+ Iterator<Integer> iter = vertices.iterator();
+ iter.remove();
+ }
-// /******************************************************************
-// *
-// *
-// * EdgeView tests
-// *
-// *
-// ******************************************************************/
-
-// @Test public void testEdgeViewAdd() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> edges = g.edges();
-// assertEquals(g.size(), edges.size());
-// edges.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1));
-// assertEquals(2, g.order());
-// assertEquals(1, g.size());
-// assertEquals(1, edges.size());
-// assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
-// assertTrue(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
-// }
-
-// @Test public void testEdgeViewRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> edges = g.edges();
-// assertEquals(g.size(), edges.size());
-// edges.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1));
-// edges.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 1));
-// assertEquals(2, g.order());
-// assertEquals(0, g.size());
-// assertEquals(0, edges.size());
-// assertFalse(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
-// assertFalse(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
-// }
-
-// @Test public void testEdgeViewIterator() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> edges = g.edges();
-
-// Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
-// for (int i = 0; i < 100; i += 2) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, i+1);
-// g.add(e); // all disconnected
-// control.add(e);
-// }
+ /******************************************************************
+ *
+ *
+ * EdgeView tests
+ *
+ *
+ ******************************************************************/
+
+ @Test public void testEdgeViewAdd() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> edges = g.edges();
+ assertEquals(g.size(), edges.size());
+ edges.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1));
+ assertEquals(2, g.order());
+ assertEquals(1, g.size());
+ assertEquals(1, edges.size());
+ assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
+ assertTrue(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
+ }
+
+ @Test public void testEdgeViewRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> edges = g.edges();
+ assertEquals(g.size(), edges.size());
+ edges.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1));
+ edges.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 1));
+ assertEquals(2, g.order());
+ assertEquals(0, g.size());
+ assertEquals(0, edges.size());
+ assertFalse(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
+ assertFalse(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
+ }
+
+ @Test public void testEdgeViewIterator() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> edges = g.edges();
+
+ Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
+ for (int i = 0; i < 100; i += 2) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, i+1);
+ g.add(e); // all disconnected
+ control.add(e);
+ }
-// assertEquals(100, g.order());
-// assertEquals(50, g.size());
-// assertEquals(50, edges.size());
+ assertEquals(100, g.order());
+ assertEquals(50, g.size());
+ assertEquals(50, edges.size());
-// Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
-// for (DirectedTypedEdge<String> e : edges)
-// test.add(e);
-// assertEquals(control.size(), test.size());
-// for (Edge e : test)
-// assertTrue(control.contains(e));
-// }
-
-// @Test public void testEdgeViewIteratorRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> edges = g.edges();
-
-// Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
-// for (int i = 0; i < 10; i += 2) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, i+1);
-// g.add(e); // all disconnected
-// control.add(e);
-// }
+ Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
+ for (DirectedTypedEdge<String> e : edges)
+ test.add(e);
+ assertEquals(control.size(), test.size());
+ for (Edge e : test)
+ assertTrue(control.contains(e));
+ }
+
+ @Test public void testEdgeViewIteratorRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> edges = g.edges();
+
+ Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>();
+ for (int i = 0; i < 10; i += 2) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, i+1);
+ g.add(e); // all disconnected
+ control.add(e);
+ }
-// assertEquals(10, g.order());
-// assertEquals(5, g.size());
-// assertEquals(5, edges.size());
+ assertEquals(10, g.order());
+ assertEquals(5, g.size());
+ assertEquals(5, edges.size());
-// Iterator<DirectedTypedEdge<String>> iter = edges.iterator();
-// while (iter.hasNext()) {
-// iter.next();
-// iter.remove();
-// }
-// assertEquals(0, g.size());
-// assertFalse(g.edges().iterator().hasNext());
-// assertEquals(0, edges.size());
-// assertEquals(10, g.order());
-// }
-
-// /******************************************************************
-// *
-// *
-// * AdjacencyListView tests
-// *
-// *
-// ******************************************************************/
-
-// @Test public void testAdjacencyList() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i)
-// for (int j = i + 1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-
-// for (int i = 0; i < 10; ++i) {
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(i);
-// assertEquals(9, adjacencyList.size());
+ Iterator<DirectedTypedEdge<String>> iter = edges.iterator();
+ while (iter.hasNext()) {
+ iter.next();
+ iter.remove();
+ }
+ assertEquals(0, g.size());
+ assertFalse(g.edges().iterator().hasNext());
+ assertEquals(0, edges.size());
+ assertEquals(10, g.order());
+ }
+
+ /******************************************************************
+ *
+ *
+ * AdjacencyListView tests
+ *
+ *
+ ******************************************************************/
+
+ @Test public void testAdjacencyList() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i)
+ for (int j = i + 1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+
+ for (int i = 0; i < 10; ++i) {
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(i);
+ assertEquals(9, adjacencyList.size());
-// for (int j = 0; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// if (i >= j)
-// assertFalse(adjacencyList.contains(e));
-// else
-// assertTrue(adjacencyList.contains(e));
-// }
-// }
-// }
-
-// @Test public void testAdjacencyListRemoveEdge() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i)
-// for (int j = i + 1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
-// Edge e = new SimpleDirectedTypedEdge<String>("type-1",0, 1);
-// assertTrue(adjacencyList.contains(e));
-// assertTrue(adjacencyList.remove(e));
-// assertEquals(8, adjacencyList.size());
-// assertEquals( (10 * 9) / 2 - 1, g.size());
-// }
-
-// public void testAdjacencyListAddEdge() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i)
-// for (int j = i + 2; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-
-// assertEquals( (10 * 9) / 2 - 9, g.size());
-
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, 1);
-// assertFalse(adjacencyList.contains(e));
-// assertFalse(g.contains(e));
-
-// assertTrue(adjacencyList.add(e));
-// assertTrue(g.contains(e));
-
-// assertEquals(9, adjacencyList.size());
-// assertEquals( (10 * 9) / 2 - 8, g.size());
-// }
-
-// @Test public void testAdjacencyListIterator() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
-// assertEquals(9, adjacencyList.size());
-
-// Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
-// int i = 0;
-// while (it.hasNext())
-// assertTrue(test.add(it.next()));
-// assertEquals(9, test.size());
-// }
-
-// @Test public void testAdjacencyListNoVertex() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
-// assertEquals(0, adjacencyList.size());
-// }
-
-// @Test(expected=NoSuchElementException.class)
-// public void testAdjacencyListIteratorNextOffEnd() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
-// assertEquals(9, adjacencyList.size());
-
-// Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
-// int i = 0;
-// while (it.hasNext())
-// assertTrue(test.add(it.next()));
-// assertEquals(9, test.size());
-// it.next();
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
-// assertEquals(9, adjacencyList.size());
-
-// Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
-// assertTrue(it.hasNext());
-// Edge e = it.next();
-// it.remove();
-// assertFalse(adjacencyList.contains(e));
-// assertEquals(8, adjacencyList.size());
-// assertFalse(g.contains(e));
-// assertEquals( (10 * 9) / 2 - 1, g.size());
-// }
-
-// @Test(expected=UnsupportedOperationException.class)
-// public void testAdjacencyListIteratorRemoveFirst() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
-// assertEquals(9, adjacencyList.size());
-
-// Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
-// it.remove();
-// }
-
-// @Test(expected=UnsupportedOperationException.class)
-// public void testAdjacencyListIteratorRemoveTwice() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
-// Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
-// assertEquals(9, adjacencyList.size());
-
-// Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
-// assertTrue(it.hasNext());
-// it.next();
-// it.remove();
-// it.remove();
-// }
-
-// /******************************************************************
-// *
-// *
-// * AdjacentVerticesView tests
-// *
-// *
-// ******************************************************************/
-
-
-// @Test public void testAdjacentVertices() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<Integer> test = new HashSet<Integer>();
-// Set<Integer> adjacent = g.getNeighbors(0);
-// assertEquals(9, adjacent.size());
-// for (int i = 1; i < 10; ++i)
-// assertTrue(adjacent.contains(i));
-// assertFalse(adjacent.contains(0));
-// assertFalse(adjacent.contains(10));
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesAdd() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<Integer> test = new HashSet<Integer>();
-// Set<Integer> adjacent = g.getNeighbors(0);
-// adjacent.add(1);
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<Integer> test = new HashSet<Integer>();
-// Set<Integer> adjacent = g.getNeighbors(0);
-// adjacent.remove(1);
-// }
-
-// @Test public void testAdjacentVerticesIterator() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<Integer> test = new HashSet<Integer>();
-// Set<Integer> adjacent = g.getNeighbors(0);
-// Iterator<Integer> it = adjacent.iterator();
-// while (it.hasNext())
-// assertTrue(test.add(it.next()));
-// assertEquals(9, test.size());
-// }
-
-
-// @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesIteratorRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-// for (int i = 0; i < 10; ++i) {
-// for (int j = i + 1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// g.add(e);
-// }
-// }
-
-// Set<Integer> test = new HashSet<Integer>();
-// Set<Integer> adjacent = g.getNeighbors(0);
-// Iterator<Integer> it = adjacent.iterator();
-// assertTrue(it.hasNext());
-// it.next();
-// it.remove();
-// }
-
-// /******************************************************************
-// *
-// *
-// * Subgraph tests
-// *
-// *
-// ******************************************************************/
-
-// @Test public void testSubgraph() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals( (5 * 4) / 2, subgraph.size());
-// }
-
-// @Test public void testSubgraphContainsVertex() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals( (5 * 4) / 2, subgraph.size());
-// for (int i = 0; i < 5; ++i)
-// assertTrue(subgraph.contains(i));
-// for (int i = 5; i < 10; ++i) {
-// assertTrue(g.contains(i));
-// assertFalse(subgraph.contains(i));
-// }
-// }
-
-// @Test public void testSubgraphContainsEdge() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals( (5 * 4) / 2, subgraph.size());
-// for (int i = 0; i < 5; ++i) {
-// for (int j = i+1; j < 5; ++j) {
-// assertTrue(subgraph.contains(new SimpleDirectedTypedEdge<String>("type-1",i, j)));
-// }
-// }
-
-// for (int i = 5; i < 10; ++i) {
-// for (int j = i+1; j < 10; ++j) {
-// DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
-// assertTrue(g.contains(e));
-// assertFalse(subgraph.contains(e));
-// }
-// }
-// }
-
-// @Test public void testSubgraphAddEdge() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < i+2 && j < 10; ++j)
-// assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)));
-// }
-
-// assertEquals(9, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals(4, subgraph.size());
-
-// // Add an edge to a new vertex
-// assertTrue(subgraph.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 0)));
-// assertEquals(5, subgraph.size());
-// assertEquals(5, subgraph.order());
-// assertEquals(10, g.size());
-
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testSubgraphAddEdgeNewVertex() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals( (5 * 4) / 2, subgraph.size());
-
-// // Add an edge to a new vertex
-// assertTrue(subgraph.add(new SimpleDirectedTypedEdge<String>("type-1",0, 5)));
-// assertEquals( (5 * 4) / 2 + 1, subgraph.size());
-// assertEquals(6, subgraph.order());
-// assertEquals(11, g.order());
-// assertEquals( (9*10)/2 + 1, g.size());
-// }
-
-// @Test public void testSubgraphRemoveEdge() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals( (5 * 4) / 2, subgraph.size());
-
-// // Remove an existing edge
-// assertTrue(subgraph.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
-// assertEquals( (5 * 4) / 2 - 1, subgraph.size());
-// assertEquals(5, subgraph.order());
-// assertEquals(10, g.order());
-// assertEquals( (9*10)/2 - 1, g.size());
-
-// // Remove a non-existent edge, which should have no effect even though
-// // the edge is present in the backing graph
-// assertFalse(subgraph.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 6)));
-// assertEquals( (5 * 4) / 2 - 1, subgraph.size());
-// assertEquals(5, subgraph.order());
-// assertEquals(10, g.order());
-// assertEquals( (9*10)/2 - 1, g.size());
-// }
-
-
-// /******************************************************************
-// *
-// *
-// * SubgraphVertexView tests
-// *
-// *
-// ******************************************************************/
-
-
-// @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesAdd() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals( (5 * 4) / 2, subgraph.size());
-
-// Set<Integer> test = subgraph.vertices();
-// assertEquals(5, test.size());
-
-// // Add a vertex
-// assertTrue(test.add(5));
-// assertEquals(6, test.size());
-// assertEquals(6, subgraph.order());
-// assertEquals(11, g.order());
-// assertEquals( (5*4)/2, subgraph.size());
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals( (5 * 4) / 2, subgraph.size());
-
-// Set<Integer> test = subgraph.vertices();
-// assertEquals(5, test.size());
-
-// // Add a vertex
-// assertTrue(test.remove(0));
-// assertEquals(4, test.size());
-// assertEquals(4, subgraph.order());
-// assertEquals(9, g.order());
-// assertEquals( (4*3)/2, subgraph.size());
-// }
-
-// @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesIteratorRemove() {
-// DirectedMultigraph<String> g = new DirectedMultigraph<String>();
-
-// // fully connected
-// for (int i = 0; i < 10; i++) {
-// for (int j = i+1; j < 10; ++j)
-// g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
-// }
-
-// // (n * (n-1)) / 2
-// assertEquals( (10 * 9) / 2, g.size());
-// assertEquals(10, g.order());
-
-// Set<Integer> vertices = new LinkedHashSet<Integer>();
-// for (int i = 0; i < 5; ++i)
-// vertices.add(i);
-
-// DirectedMultigraph<String> subgraph = g.subgraph(vertices);
-// assertEquals(5, subgraph.order());
-// assertEquals( (5 * 4) / 2, subgraph.size());
-
-// Set<Integer> test = subgraph.vertices();
-// assertEquals(5, test.size());
-// Iterator<Integer> it = test.iterator();
-// assertTrue(it.hasNext());
-// // Remove the first vertex returned
-// it.next();
-// it.remove();
-
-// assertEquals(4, test.size());
-// assertEquals(4, subgraph.order());
-// assertEquals(9, g.order());
-// assertEquals( (4*3)/2, subgraph.size());
-// }
+ for (int j = 0; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ if (i >= j)
+ assertFalse(adjacencyList.contains(e));
+ else
+ assertTrue(adjacencyList.contains(e));
+ }
+ }
+ }
+
+ @Test public void testAdjacencyListRemoveEdge() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i)
+ for (int j = i + 1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
+ Edge e = new SimpleDirectedTypedEdge<String>("type-1",0, 1);
+ assertTrue(adjacencyList.contains(e));
+ assertTrue(adjacencyList.remove(e));
+ assertEquals(8, adjacencyList.size());
+ assertEquals( (10 * 9) / 2 - 1, g.size());
+ }
+
+ public void testAdjacencyListAddEdge() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i)
+ for (int j = i + 2; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+
+ assertEquals( (10 * 9) / 2 - 9, g.size());
+
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, 1);
+ assertFalse(adjacencyList.contains(e));
+ assertFalse(g.contains(e));
+
+ assertTrue(adjacencyList.add(e));
+ assertTrue(g.contains(e));
+
+ assertEquals(9, adjacencyList.size());
+ assertEquals( (10 * 9) / 2 - 8, g.size());
+ }
+
+ @Test public void testAdjacencyListIterator() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
+ assertEquals(9, adjacencyList.size());
+
+ Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
+ int i = 0;
+ while (it.hasNext())
+ assertTrue(test.add(it.next()));
+ assertEquals(9, test.size());
+ }
+
+ @Test public void testAdjacencyListNoVertex() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
+ assertEquals(0, adjacencyList.size());
+ }
+
+ @Test(expected=NoSuchElementException.class)
+ public void testAdjacencyListIteratorNextOffEnd() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
+ assertEquals(9, adjacencyList.size());
+
+ Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
+ int i = 0;
+ while (it.hasNext())
+ assertTrue(test.add(it.next()));
+ assertEquals(9, test.size());
+ it.next();
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
+ assertEquals(9, adjacencyList.size());
+
+ Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
+ assertTrue(it.hasNext());
+ Edge e = it.next();
+ it.remove();
+ assertFalse(adjacencyList.contains(e));
+ assertEquals(8, adjacencyList.size());
+ assertFalse(g.contains(e));
+ assertEquals( (10 * 9) / 2 - 1, g.size());
+ }
+
+ @Test(expected=UnsupportedOperationException.class)
+ public void testAdjacencyListIteratorRemoveFirst() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
+ assertEquals(9, adjacencyList.size());
+
+ Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
+ it.remove();
+ }
+
+ @Test(expected=UnsupportedOperationException.class)
+ public void testAdjacencyListIteratorRemoveTwice() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>();
+ Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0);
+ assertEquals(9, adjacencyList.size());
+
+ Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator();
+ assertTrue(it.hasNext());
+ it.next();
+ it.remove();
+ it.remove();
+ }
+
+ /******************************************************************
+ *
+ *
+ * AdjacentVerticesView tests
+ *
+ *
+ ******************************************************************/
+
+
+ @Test public void testAdjacentVertices() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<Integer> test = new HashSet<Integer>();
+ Set<Integer> adjacent = g.getNeighbors(0);
+ assertEquals(9, adjacent.size());
+ for (int i = 1; i < 10; ++i)
+ assertTrue(adjacent.contains(i));
+ assertFalse(adjacent.contains(0));
+ assertFalse(adjacent.contains(10));
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesAdd() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<Integer> test = new HashSet<Integer>();
+ Set<Integer> adjacent = g.getNeighbors(0);
+ adjacent.add(1);
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<Integer> test = new HashSet<Integer>();
+ Set<Integer> adjacent = g.getNeighbors(0);
+ adjacent.remove(1);
+ }
+
+ @Test public void testAdjacentVerticesIterator() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<Integer> test = new HashSet<Integer>();
+ Set<Integer> adjacent = g.getNeighbors(0);
+ Iterator<Integer> it = adjacent.iterator();
+ while (it.hasNext())
+ assertTrue(test.add(it.next()));
+ assertEquals(9, test.size());
+ }
+
+
+ @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesIteratorRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+ for (int i = 0; i < 10; ++i) {
+ for (int j = i + 1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ g.add(e);
+ }
+ }
+
+ Set<Integer> test = new HashSet<Integer>();
+ Set<Integer> adjacent = g.getNeighbors(0);
+ Iterator<Integer> it = adjacent.iterator();
+ assertTrue(it.hasNext());
+ it.next();
+ it.remove();
+ }
+
+ /******************************************************************
+ *
+ *
+ * Subgraph tests
+ *
+ *
+ ******************************************************************/
+
+ @Test public void testSubgraph() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals( (5 * 4) / 2, subgraph.size());
+ }
+
+ @Test public void testSubgraphContainsVertex() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals( (5 * 4) / 2, subgraph.size());
+ for (int i = 0; i < 5; ++i)
+ assertTrue(subgraph.contains(i));
+ for (int i = 5; i < 10; ++i) {
+ assertTrue(g.contains(i));
+ assertFalse(subgraph.contains(i));
+ }
+ }
+
+ @Test public void testSubgraphContainsEdge() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals( (5 * 4) / 2, subgraph.size());
+ for (int i = 0; i < 5; ++i) {
+ for (int j = i+1; j < 5; ++j) {
+ assertTrue(subgraph.contains(new SimpleDirectedTypedEdge<String>("type-1",i, j)));
+ }
+ }
+
+ for (int i = 5; i < 10; ++i) {
+ for (int j = i+1; j < 10; ++j) {
+ DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j);
+ assertTrue(g.contains(e));
+ assertFalse(subgraph.contains(e));
+ }
+ }
+ }
+
+ @Test public void testSubgraphAddEdge() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < i+2 && j < 10; ++j)
+ assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)));
+ }
+
+ assertEquals(9, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals(4, subgraph.size());
+
+ // Add an edge to a new vertex
+ assertTrue(subgraph.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 0)));
+ assertEquals(5, subgraph.size());
+ assertEquals(5, subgraph.order());
+ assertEquals(10, g.size());
+
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testSubgraphAddEdgeNewVertex() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals( (5 * 4) / 2, subgraph.size());
+
+ // Add an edge to a new vertex
+ assertTrue(subgraph.add(new SimpleDirectedTypedEdge<String>("type-1",0, 5)));
+ assertEquals( (5 * 4) / 2 + 1, subgraph.size());
+ assertEquals(6, subgraph.order());
+ assertEquals(11, g.order());
+ assertEquals( (9*10)/2 + 1, g.size());
+ }
+
+ @Test public void testSubgraphRemoveEdge() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals( (5 * 4) / 2, subgraph.size());
+
+ // Remove an existing edge
+ assertTrue(subgraph.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 1)));
+ assertEquals( (5 * 4) / 2 - 1, subgraph.size());
+ assertEquals(5, subgraph.order());
+ assertEquals(10, g.order());
+ assertEquals( (9*10)/2 - 1, g.size());
+
+ // Remove a non-existent edge, which should have no effect even though
+ // the edge is present in the backing graph
+ assertFalse(subgraph.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 6)));
+ assertEquals( (5 * 4) / 2 - 1, subgraph.size());
+ assertEquals(5, subgraph.order());
+ assertEquals(10, g.order());
+ assertEquals( (9*10)/2 - 1, g.size());
+ }
+
+
+ /******************************************************************
+ *
+ *
+ * SubgraphVertexView tests
+ *
+ *
+ ******************************************************************/
+
+
+ @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesAdd() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals( (5 * 4) / 2, subgraph.size());
+
+ Set<Integer> test = subgraph.vertices();
+ assertEquals(5, test.size());
+
+ // Add a vertex
+ assertTrue(test.add(5));
+ assertEquals(6, test.size());
+ assertEquals(6, subgraph.order());
+ assertEquals(11, g.order());
+ assertEquals( (5*4)/2, subgraph.size());
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals( (5 * 4) / 2, subgraph.size());
+
+ Set<Integer> test = subgraph.vertices();
+ assertEquals(5, test.size());
+
+ // Add a vertex
+ assertTrue(test.remove(0));
+ assertEquals(4, test.size());
+ assertEquals(4, subgraph.order());
+ assertEquals(9, g.order());
+ assertEquals( (4*3)/2, subgraph.size());
+ }
+
+ @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesIteratorRemove() {
+ DirectedMultigraph<String> g = new DirectedMultigraph<String>();
+
+ // fully connected
+ for (int i = 0; i < 10; i++) {
+ for (int j = i+1; j < 10; ++j)
+ g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j));
+ }
+
+ // (n * (n-1)) / 2
+ assertEquals( (10 * 9) / 2, g.size());
+ assertEquals(10, g.order());
+
+ Set<Integer> vertices = new LinkedHashSet<Integer>();
+ for (int i = 0; i < 5; ++i)
+ vertices.add(i);
+
+ DirectedMultigraph<String> subgraph = g.subgraph(vertices);
+ assertEquals(5, subgraph.order());
+ assertEquals( (5 * 4) / 2, subgraph.size());
+
+ Set<Integer> test = subgraph.vertices();
+ assertEquals(5, test.size());
+ Iterator<Integer> it = test.iterator();
+ assertTrue(it.hasNext());
+ // Remove the first vertex returned
+ it.next();
+ it.remove();
+
+ assertEquals(4, test.size());
+ assertEquals(4, subgraph.order());
+ assertEquals(9, g.order());
+ assertEquals( (4*3)/2, subgraph.size());
+ }
/******************************************************************
diff --git a/test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java b/test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java
index fd06a4b1..6a47fef7 100644
--- a/test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java
+++ b/test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java
@@ -26,6 +26,7 @@
import edu.ucla.sspace.text.CorpusReader;
import edu.ucla.sspace.text.Document;
+import java.io.BufferedReader;
import java.io.StringReader;
import java.util.Iterator;
@@ -41,22 +42,22 @@
public class PukWacDependencyCorpusReaderTest {
public static final String FIRST_SENTENCE =
- "1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
- "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
- "3 is _ VBZ VBZ _ 0 ROOT _ _\n";
+ toTabs("1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
+ "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
+ "3 is _ VBZ VBZ _ 0 ROOT _ _\n");
public static final String SECOND_SENTENCE =
- "4 a _ DT DT _ 5 NMOD _ _\n" +
- "5 columnist _ NN NN _ 3 PRD _ _\n" +
- "6 for _ IN IN _ 5 NMOD _ _\n" +
- "7 the _ DT DT _ 9 NMOD _ _\n" +
- "8 Literary _ NNP NNP _ 9 NMOD _ _\n";
-
+ toTabs("4 a _ DT DT _ 5 NMOD _ _\n" +
+ "5 columnist _ NN NN _ 3 PRD _ _\n" +
+ "6 for _ IN IN _ 5 NMOD _ _\n" +
+ "7 the _ DT DT _ 9 NMOD _ _\n" +
+ "8 Literary _ NNP NNP _ 9 NMOD _ _\n");
+
public static final String THIRD_SENTENCE =
- "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
- "10 in _ IN IN _ 9 ADV _ _\n" +
- "11 London _ NNP NNP _ 10 PMOD _ _\n" +
- "12 . _ . . _ 3 P _ _\n";
+ toTabs("9 Review _ NNP NNP _ 6 PMOD _ _\n" +
+ "10 in _ IN IN _ 9 ADV _ _\n" +
+ "11 London _ NNP NNP _ 10 PMOD _ _\n" +
+ "12 . _ . . _ 3 P _ _\n");
public static final String TEST_TEXT =
"<text>\n" +
@@ -87,8 +88,24 @@ public class PukWacDependencyCorpusReaderTest {
private static String readAll(Document doc) throws Exception {
StringBuilder sb = new StringBuilder();
- for (String line = null; (line = doc.reader().readLine()) != null; )
+ BufferedReader reader = doc.reader();
+ for (String line = null; (line = reader.readLine()) != null; )
sb.append(line).append("\n");
return sb.toString();
}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
}
diff --git a/test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java b/test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java
index 6aae6fb7..8c0e843a 100644
--- a/test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java
+++ b/test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java
@@ -70,7 +70,7 @@ public class DependencyContextExtractorTest {
MockWordsi wordsi = new MockWordsi(null, extractor);
extractor.processDocument(
- new BufferedReader(new StringReader(SINGLE_PARSE)),
+ new BufferedReader(new StringReader(toTabs(SINGLE_PARSE))),
wordsi);
assertTrue(wordsi.called);
}
@@ -178,4 +178,19 @@ public boolean acceptWord(String word) {
return word.equals("cat");
}
}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
}
diff --git a/test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java b/test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java
index 246d2542..33b1f431 100644
--- a/test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java
+++ b/test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java
@@ -46,18 +46,18 @@
public class OccurrenceDependencyContextGeneratorTest {
public static final String SINGLE_PARSE =
- "1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
- "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
- "3 is _ VBZ VBZ _ 0 ROOT _ _\n" +
- "4 a _ DT DT _ 5 NMOD _ _\n" +
- "5 columnist _ NN NN _ 3 PRD _ _\n" +
- "6 for _ IN IN _ 5 NMOD _ _\n" +
- "7 the _ DT DT _ 9 NMOD _ _\n" +
- "8 Literary _ NNP NNP _ 9 NMOD _ _\n" +
- "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
- "10 in _ IN IN _ 9 ADV _ _\n" +
- "11 London _ NNP NNP _ 10 PMOD _ _\n" +
- "12 . _ . . _ 3 P _ _";
+ toTabs("1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
+ "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
+ "3 is _ VBZ VBZ _ 0 ROOT _ _\n" +
+ "4 a _ DT DT _ 5 NMOD _ _\n" +
+ "5 columnist _ NN NN _ 3 PRD _ _\n" +
+ "6 for _ IN IN _ 5 NMOD _ _\n" +
+ "7 the _ DT DT _ 9 NMOD _ _\n" +
+ "8 Literary _ NNP NNP _ 9 NMOD _ _\n" +
+ "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
+ "10 in _ IN IN _ 9 ADV _ _\n" +
+ "11 London _ NNP NNP _ 10 PMOD _ _\n" +
+ "12 . _ . . _ 3 P _ _");
@Test public void testOccurrence() throws Exception {
DependencyExtractor extractor = new CoNLLDependencyExtractor();
@@ -82,22 +82,37 @@ public int getDimension(String key) {
return 0;
if (key.equals("is"))
return 1;
- if (key.equals("holt"))
+ if (key.equals("Holt"))
return 2;
- if (key.equals("mr."))
+ if (key.equals("Mr."))
return 3;
if (key.equals("for"))
return 4;
if (key.equals("the"))
return 5;
- if (key.equals("literary"))
+ if (key.equals("Literary"))
return 6;
- if (key.equals("review"))
+ if (key.equals("Review"))
return 7;
if (key.equals("in"))
return 8;
return -1;
}
}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
}
diff --git a/test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java b/test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java
index 9bd825fc..241e6ef3 100644
--- a/test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java
+++ b/test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java
@@ -49,18 +49,18 @@
public class OrderingDependencyContextGeneratorTest {
public static final String SINGLE_PARSE =
- "1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
- "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
- "3 is _ VBZ VBZ _ 0 ROOT _ _\n" +
- "4 a _ DT DT _ 5 NMOD _ _\n" +
- "5 columnist _ NN NN _ 3 PRD _ _\n" +
- "6 for _ IN IN _ 5 NMOD _ _\n" +
- "7 the _ DT DT _ 9 NMOD _ _\n" +
- "8 Literary _ NNP NNP _ 9 NMOD _ _\n" +
- "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
- "10 in _ IN IN _ 9 ADV _ _\n" +
- "11 London _ NNP NNP _ 10 PMOD _ _\n" +
- "12 . _ . . _ 3 P _ _";
+ toTabs("1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
+ "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
+ "3 is _ VBZ VBZ _ 0 ROOT _ _\n" +
+ "4 a _ DT DT _ 5 NMOD _ _\n" +
+ "5 columnist _ NN NN _ 3 PRD _ _\n" +
+ "6 for _ IN IN _ 5 NMOD _ _\n" +
+ "7 the _ DT DT _ 9 NMOD _ _\n" +
+ "8 Literary _ NNP NNP _ 9 NMOD _ _\n" +
+ "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
+ "10 in _ IN IN _ 9 ADV _ _\n" +
+ "11 London _ NNP NNP _ 10 PMOD _ _\n" +
+ "12 . _ . . _ 3 P _ _");
@Test public void testOrdering() throws Exception {
DependencyExtractor extractor = new CoNLLDependencyExtractor();
@@ -85,22 +85,37 @@ public int getDimension(String key) {
return 0;
if (key.equals("is--2"))
return 1;
- if (key.equals("holt--3"))
+ if (key.equals("Holt--3"))
return 2;
- if (key.equals("mr.--4"))
+ if (key.equals("Mr.--4"))
return 3;
if (key.equals("for-1"))
return 4;
if (key.equals("the-2"))
return 5;
- if (key.equals("literary-3"))
+ if (key.equals("Literary-3"))
return 6;
- if (key.equals("review-4"))
+ if (key.equals("Review-4"))
return 7;
if (key.equals("in-5"))
return 8;
return -1;
}
}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
}
diff --git a/test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java b/test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java
index 5da76df4..6fa81d67 100644
--- a/test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java
+++ b/test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java
@@ -49,18 +49,18 @@
public class PartOfSpeechDependencyContextGeneratorTest {
public static final String SINGLE_PARSE =
- "1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
- "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
- "3 is _ VBZ VBZ _ 0 ROOT _ _\n" +
- "4 a _ DT DT _ 5 NMOD _ _\n" +
- "5 columnist _ NN NN _ 3 PRD _ _\n" +
- "6 for _ IN IN _ 5 NMOD _ _\n" +
- "7 the _ DT DT _ 9 NMOD _ _\n" +
- "8 Literary _ NNP NNP _ 9 NMOD _ _\n" +
- "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
- "10 in _ IN IN _ 9 ADV _ _\n" +
- "11 London _ NNP NNP _ 10 PMOD _ _\n" +
- "12 . _ . . _ 3 P _ _";
+ toTabs("1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
+ "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
+ "3 is _ VBZ VBZ _ 0 ROOT _ _\n" +
+ "4 a _ DT DT _ 5 NMOD _ _\n" +
+ "5 columnist _ NN NN _ 3 PRD _ _\n" +
+ "6 for _ IN IN _ 5 NMOD _ _\n" +
+ "7 the _ DT DT _ 9 NMOD _ _\n" +
+ "8 Literary _ NNP NNP _ 9 NMOD _ _\n" +
+ "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
+ "10 in _ IN IN _ 9 ADV _ _\n" +
+ "11 London _ NNP NNP _ 10 PMOD _ _\n" +
+ "12 . _ . . _ 3 P _ _");
@Test public void testGenerate() throws Exception {
DependencyExtractor extractor = new CoNLLDependencyExtractor();
@@ -85,22 +85,37 @@ public int getDimension(String key) {
return 0;
if (key.equals("is-VBZ"))
return 1;
- if (key.equals("holt-NNP"))
+ if (key.equals("Holt-NNP"))
return 2;
- if (key.equals("mr.-NNP"))
+ if (key.equals("Mr.-NNP"))
return 3;
if (key.equals("for-IN"))
return 4;
if (key.equals("the-DT"))
return 5;
- if (key.equals("literary-NNP"))
+ if (key.equals("Literary-NNP"))
return 6;
- if (key.equals("review-NNP"))
+ if (key.equals("Review-NNP"))
return 7;
if (key.equals("in-IN"))
return 8;
return -1;
}
}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
}
diff --git a/test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java b/test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java
index fbbfa3ee..367ac49e 100644
--- a/test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java
+++ b/test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java
@@ -50,19 +50,19 @@
public class PseudoWordDependencyContextExtractorTest {
public static final String SINGLE_PARSE =
- "target: cat absolute_position: 4 relative_position: 4 prior_trees: 0 after_trees: 0\n" +
- "1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
- "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
- "3 is _ VBZ VBZ _ 0 ROOT _ _\n" +
- "4 a _ DT DT _ 5 NMOD _ _\n" +
- "5 cat _ NN NN _ 3 PRD _ _\n" +
- "6 for _ IN IN _ 5 NMOD _ _\n" +
- "7 the _ DT DT _ 9 NMOD _ _\n" +
- "8 Literary _ NNP NNP _ 9 NMOD _ _\n" +
- "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
- "10 in _ IN IN _ 9 ADV _ _\n" +
- "11 London _ NNP NNP _ 10 PMOD _ _\n" +
- "12 . _ . . _ 3 P _ _";
+ toTabs("target: cat absolute_position: 4 relative_position: 4 prior_trees: 0 after_trees: 0\n" +
+ "1 Mr. _ NNP NNP _ 2 NMOD _ _\n" +
+ "2 Holt _ NNP NNP _ 3 SBJ _ _\n" +
+ "3 is _ VBZ VBZ _ 0 ROOT _ _\n" +
+ "4 a _ DT DT _ 5 NMOD _ _\n" +
+ "5 cat _ NN NN _ 3 PRD _ _\n" +
+ "6 for _ IN IN _ 5 NMOD _ _\n" +
+ "7 the _ DT DT _ 9 NMOD _ _\n" +
+ "8 Literary _ NNP NNP _ 9 NMOD _ _\n" +
+ "9 Review _ NNP NNP _ 6 PMOD _ _\n" +
+ "10 in _ IN IN _ 9 ADV _ _\n" +
+ "11 London _ NNP NNP _ 10 PMOD _ _\n" +
+ "12 . _ . . _ 3 P _ _");
private SparseDoubleVector testVector;
@@ -149,4 +149,19 @@ public boolean acceptWord(String word) {
return word.equals("cat");
}
}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
}
diff --git a/test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java b/test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java
index 2b51f4e2..5fc4bd6d 100644
--- a/test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java
+++ b/test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java
@@ -74,7 +74,7 @@ public class SemEvalDependencyContextExtractorTest {
MockWordsi wordsi = new MockWordsi(null, extractor);
extractor.processDocument(
- new BufferedReader(new StringReader(SINGLE_PARSE)),
+ new BufferedReader(new StringReader(toTabs(SINGLE_PARSE))),
wordsi);
assertTrue(wordsi.called);
}
@@ -149,4 +149,19 @@ public boolean acceptWord(String word) {
return word.equals("cat");
}
}
+
+ static String toTabs(String doc) {
+ StringBuilder sb = new StringBuilder();
+ String[] arr = doc.split("\n");
+ for (String line : arr) {
+ String[] cols = line.split("\\s+");
+ for (int i = 0; i < cols.length; ++i) {
+ sb.append(cols[i]);
+ if (i + 1 < cols.length)
+ sb.append('\t');
+ }
+ sb.append('\n');
+ }
+ return sb.toString();
+ }
}
|
adb90c7f52be4c443a1050b2bfcbcb5cdf8542f5
|
hadoop
|
YARN-2821. Fixed a problem that DistributedShell AM- may hang if restarted. Contributed by Varun Vasudev (cherry picked from- commit 7438966586f1896ab3e8b067d47a4af28a894106)--
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index c97df938c81ad..16cb27b8361f7 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -375,6 +375,9 @@ Release 2.8.0 - UNRELEASED
YARN-3302. TestDockerContainerExecutor should run automatically if it can
detect docker in the usual place (Ravindra Kumar Naik via raviprak)
+ YARN-2821. Fixed a problem that DistributedShell AM may hang if restarted.
+ (Varun Vasudev via jianhe)
+
Release 2.7.1 - UNRELEASED
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
index 24f8bcc000e6e..6ac8bf134d2f5 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
@@ -116,6 +116,11 @@
<type>test-jar</type>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java
index b62c24cbd711f..b28c0c925c3d9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java
@@ -30,10 +30,12 @@
import java.nio.ByteBuffer;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -277,6 +279,10 @@ public static enum DSEntity {
private final String linux_bash_command = "bash";
private final String windows_command = "cmd /c";
+ @VisibleForTesting
+ protected final Set<ContainerId> launchedContainers =
+ Collections.newSetFromMap(new ConcurrentHashMap<ContainerId, Boolean>());
+
/**
* @param args Command line args
*/
@@ -601,8 +607,12 @@ public void run() throws YarnException, IOException, InterruptedException {
response.getContainersFromPreviousAttempts();
LOG.info(appAttemptID + " received " + previousAMRunningContainers.size()
+ " previous attempts' running containers on AM registration.");
+ for(Container container: previousAMRunningContainers) {
+ launchedContainers.add(container.getId());
+ }
numAllocatedContainers.addAndGet(previousAMRunningContainers.size());
+
int numTotalContainersToRequest =
numTotalContainers - previousAMRunningContainers.size();
// Setup ask for containers from RM
@@ -715,8 +725,9 @@ protected boolean finish() {
return success;
}
-
- private class RMCallbackHandler implements AMRMClientAsync.CallbackHandler {
+
+ @VisibleForTesting
+ class RMCallbackHandler implements AMRMClientAsync.CallbackHandler {
@SuppressWarnings("unchecked")
@Override
public void onContainersCompleted(List<ContainerStatus> completedContainers) {
@@ -731,6 +742,14 @@ public void onContainersCompleted(List<ContainerStatus> completedContainers) {
// non complete containers should not be here
assert (containerStatus.getState() == ContainerState.COMPLETE);
+ // ignore containers we know nothing about - probably from a previous
+ // attempt
+ if (!launchedContainers.contains(containerStatus.getContainerId())) {
+ LOG.info("Ignoring completed status of "
+ + containerStatus.getContainerId()
+ + "; unknown container(probably launched by previous attempt)");
+ continue;
+ }
// increment counters for completed/failed containers
int exitStatus = containerStatus.getExitStatus();
@@ -796,14 +815,13 @@ public void onContainersAllocated(List<Container> allocatedContainers) {
// + ", containerToken"
// +allocatedContainer.getContainerToken().getIdentifier().toString());
- LaunchContainerRunnable runnableLaunchContainer =
- new LaunchContainerRunnable(allocatedContainer, containerListener);
- Thread launchThread = new Thread(runnableLaunchContainer);
+ Thread launchThread = createLaunchContainerThread(allocatedContainer);
// launch and start the container on a separate thread to keep
// the main thread unblocked
// as all containers may not be allocated at one go.
launchThreads.add(launchThread);
+ launchedContainers.add(allocatedContainer.getId());
launchThread.start();
}
}
@@ -1150,4 +1168,30 @@ private static void publishApplicationAttemptEvent(
+ appAttemptId.toString(), e);
}
}
+
+ RMCallbackHandler getRMCallbackHandler() {
+ return new RMCallbackHandler();
+ }
+
+ @VisibleForTesting
+ void setAmRMClient(AMRMClientAsync client) {
+ this.amRMClient = client;
+ }
+
+ @VisibleForTesting
+ int getNumCompletedContainers() {
+ return numCompletedContainers.get();
+ }
+
+ @VisibleForTesting
+ boolean getDone() {
+ return done;
+ }
+
+ @VisibleForTesting
+ Thread createLaunchContainerThread(Container allocatedContainer) {
+ LaunchContainerRunnable runnableLaunchContainer =
+ new LaunchContainerRunnable(allocatedContainer, containerListener);
+ return new Thread(runnableLaunchContainer);
+ }
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSAppMaster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSAppMaster.java
index 11e840a8c90ad..0fed14d02cc00 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSAppMaster.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSAppMaster.java
@@ -20,13 +20,143 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.yarn.api.records.Container;
+import org.apache.hadoop.yarn.api.records.ContainerExitStatus;
+import org.apache.hadoop.yarn.api.records.ContainerId;
+import org.apache.hadoop.yarn.api.records.ContainerState;
+import org.apache.hadoop.yarn.api.records.ContainerStatus;
+import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.Priority;
+import org.apache.hadoop.yarn.api.records.Resource;
+import org.apache.hadoop.yarn.client.api.AMRMClient;
+import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync;
import org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.exceptions.YarnException;
+import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.junit.Assert;
import org.junit.Test;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A bunch of tests to make sure that the container allocations
+ * and releases occur correctly.
+ */
public class TestDSAppMaster {
+ static class TestAppMaster extends ApplicationMaster {
+ private int threadsLaunched = 0;
+
+ @Override
+ protected Thread createLaunchContainerThread(Container allocatedContainer) {
+ threadsLaunched++;
+ launchedContainers.add(allocatedContainer.getId());
+ return new Thread();
+ }
+
+ void setNumTotalContainers(int numTotalContainers) {
+ this.numTotalContainers = numTotalContainers;
+ }
+
+ int getAllocatedContainers() {
+ return this.numAllocatedContainers.get();
+ }
+
+ @Override
+ void startTimelineClient(final Configuration conf) throws YarnException,
+ IOException, InterruptedException {
+ timelineClient = null;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testDSAppMasterAllocateHandler() throws Exception {
+
+ TestAppMaster master = new TestAppMaster();
+ int targetContainers = 2;
+ AMRMClientAsync mockClient = Mockito.mock(AMRMClientAsync.class);
+ master.setAmRMClient(mockClient);
+ master.setNumTotalContainers(targetContainers);
+ Mockito.doNothing().when(mockClient)
+ .addContainerRequest(Matchers.any(AMRMClient.ContainerRequest.class));
+
+ ApplicationMaster.RMCallbackHandler handler = master.getRMCallbackHandler();
+
+ List<Container> containers = new ArrayList<>(1);
+ ContainerId id1 = BuilderUtils.newContainerId(1, 1, 1, 1);
+ containers.add(generateContainer(id1));
+
+ master.numRequestedContainers.set(targetContainers);
+
+ // first allocate a single container, everything should be fine
+ handler.onContainersAllocated(containers);
+ Assert.assertEquals("Wrong container allocation count", 1,
+ master.getAllocatedContainers());
+ Mockito.verifyZeroInteractions(mockClient);
+ Assert.assertEquals("Incorrect number of threads launched", 1,
+ master.threadsLaunched);
+
+ // now send 3 extra containers
+ containers.clear();
+ ContainerId id2 = BuilderUtils.newContainerId(1, 1, 1, 2);
+ containers.add(generateContainer(id2));
+ ContainerId id3 = BuilderUtils.newContainerId(1, 1, 1, 3);
+ containers.add(generateContainer(id3));
+ ContainerId id4 = BuilderUtils.newContainerId(1, 1, 1, 4);
+ containers.add(generateContainer(id4));
+ handler.onContainersAllocated(containers);
+ Assert.assertEquals("Wrong final container allocation count", 4,
+ master.getAllocatedContainers());
+
+ Assert.assertEquals("Incorrect number of threads launched", 4,
+ master.threadsLaunched);
+
+ // make sure we handle completion events correctly
+ List<ContainerStatus> status = new ArrayList<>();
+ status.add(generateContainerStatus(id1, ContainerExitStatus.SUCCESS));
+ status.add(generateContainerStatus(id2, ContainerExitStatus.SUCCESS));
+ status.add(generateContainerStatus(id3, ContainerExitStatus.ABORTED));
+ status.add(generateContainerStatus(id4, ContainerExitStatus.ABORTED));
+ handler.onContainersCompleted(status);
+
+ Assert.assertEquals("Unexpected number of completed containers",
+ targetContainers, master.getNumCompletedContainers());
+ Assert.assertTrue("Master didn't finish containers as expected",
+ master.getDone());
+
+ // test for events from containers we know nothing about
+ // these events should be ignored
+ status = new ArrayList<>();
+ ContainerId id5 = BuilderUtils.newContainerId(1, 1, 1, 5);
+ status.add(generateContainerStatus(id5, ContainerExitStatus.ABORTED));
+ Assert.assertEquals("Unexpected number of completed containers",
+ targetContainers, master.getNumCompletedContainers());
+ Assert.assertTrue("Master didn't finish containers as expected",
+ master.getDone());
+ status.add(generateContainerStatus(id5, ContainerExitStatus.SUCCESS));
+ Assert.assertEquals("Unexpected number of completed containers",
+ targetContainers, master.getNumCompletedContainers());
+ Assert.assertTrue("Master didn't finish containers as expected",
+ master.getDone());
+ }
+
+ private Container generateContainer(ContainerId cid) {
+ return Container.newInstance(cid, NodeId.newInstance("host", 5000),
+ "host:80", Resource.newInstance(1024, 1), Priority.newInstance(0), null);
+ }
+
+ private ContainerStatus
+ generateContainerStatus(ContainerId id, int exitStatus) {
+ return ContainerStatus.newInstance(id, ContainerState.COMPLETE, "",
+ exitStatus);
+ }
+
@Test
public void testTimelineClientInDSAppMaster() throws Exception {
ApplicationMaster appMaster = new ApplicationMaster();
|
73b54f4efe43dbe674621ba81c7ab7e04e1157c8
|
spring-framework
|
SPR-6466 - ContentNegotiatingViewResolver can not- handle View implementations returning null as content type--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
index 1ffbb93e744e..0ad603a851a3 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
@@ -350,12 +350,15 @@ public View resolveViewName(String viewName, Locale locale) throws Exception {
}
for (View candidateView : candidateViews) {
- MediaType viewMediaType = MediaType.parseMediaType(candidateView.getContentType());
- for (MediaType requestedMediaType : requestedMediaTypes) {
- if (requestedMediaType.includes(viewMediaType)) {
- if (!views.containsKey(requestedMediaType)) {
- views.put(requestedMediaType, candidateView);
- break;
+ String contentType = candidateView.getContentType();
+ if (StringUtils.hasText(contentType)) {
+ MediaType viewMediaType = MediaType.parseMediaType(contentType);
+ for (MediaType requestedMediaType : requestedMediaTypes) {
+ if (requestedMediaType.includes(viewMediaType)) {
+ if (!views.containsKey(requestedMediaType)) {
+ views.put(requestedMediaType, candidateView);
+ break;
+ }
}
}
}
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java
index 8c1ce84dd003..49d4a1869da4 100644
--- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java
@@ -280,4 +280,29 @@ public void resolveViewNameFilenameDefaultView() throws Exception {
verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3);
}
+ @Test
+ public void resolveViewContentTypeNull() throws Exception {
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test");
+ request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
+ RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
+
+ ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
+
+ View viewMock = createMock("application_xml", View.class);
+
+ String viewName = "view";
+ Locale locale = Locale.ENGLISH;
+
+ expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock);
+ expect(viewMock.getContentType()).andReturn(null);
+
+ replay(viewResolverMock, viewMock);
+
+ View result = viewResolver.resolveViewName(viewName, locale);
+ assertNull("Invalid view", result);
+
+ verify(viewResolverMock, viewMock);
+ }
+
}
|
426b094ec7683cd482b87ff7fe102a005ff1dac3
|
Delta Spike
|
DELTASPIKE-278 use '_' as category separator
This got done to unify this with the default JSF '_detail'
handling. So we moved from '.' as separator to '_'
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java
index 0cf3cb64e..1dce18176 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java
@@ -68,7 +68,7 @@ public interface Message extends Serializable
* which created the Message.
* While resolving the message we will
* first search for a messageTemplate with the given category by
- * just adding a dot '.' and the category String to the
+ * just adding a dot '_' and the category String to the
* {@link #getTemplate()}.
* If no such a template exists we will fallback to the version
* without the category String
@@ -80,7 +80,7 @@ public interface Message extends Serializable
* arbitrary {@link MessageContext}.
* While resolving the message we will
* first search for a messageTemplate with the given category by
- * just adding a dot '.' and the category String to the
+ * just adding a dot '_' and the category String to the
* {@link #getTemplate()}.
* If no such a template exists we will fallback to the version
* without the category String
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java
index 890cb40ab..d42e7cc1b 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java
@@ -18,25 +18,50 @@
*/
package org.apache.deltaspike.core.spi.scope.window;
-import org.apache.deltaspike.core.spi.AttributeAware;
-
/**
- * <p>We support the general notion of multiple 'windows'.
+ * <p>We support the general notion of multiple 'windows'
* That might be different parallel edit pages in a
* desktop application (think about different open documents
* in an editor) or multiple browser tabs in a
* web application.</p>
* <p>For web applications each browser tab or window will be
- * represented by an own {@link WindowContext}. All those
- * {@link WindowContext}s will be held in the users servlet
+ * represented by an own {@link WindowContext} slice. All those
+ * {@link WindowContext} slices will be held in the users servlet
* session as @SessionScoped bean.
* </p>
+ * <p>Every WindowContext is uniquely identified via a
+ * 'windowId'. Each Thread is associated with at most
+ * one single windowId at a time. The {@link WindowContext}
+ * is the interface which allows resolving the current <i>windowId</i>
+ * associated with this very Thread.</p>
*/
-public interface WindowContext extends AttributeAware
+public interface WindowContext
{
/**
- * @return the unique identifier for this window context
+ * @return the <i>windowId</i> associated with the very Thread or <code>null</code>.
+ */
+ String getCurrentWindowId();
+
+ /**
+ * Set the current windowId as the currently active for the very Thread.
+ * If no WindowContext exists with the very windowId we will create a new one.
+ * @param windowId
+ */
+ void activateWindowContext(String windowId);
+
+ /**
+ * close the WindowContext with the currently activated windowId for the very Thread.
+ * @return <code>true</code> if any did exist, <code>false</code> otherwise
+ */
+ boolean closeCurrentWindowContext();
+
+
+ /**
+ * Close all WindowContexts which are managed by the WindowContextManager.
+ * This is necessary when the session gets closed down.
+ * @return
*/
- String getWindowId();
+ void closeAllWindowContexts();
+
}
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContextManager.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContextManager.java
deleted file mode 100644
index c131c5c2f..000000000
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContextManager.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.deltaspike.core.spi.scope.window;
-
-/**
- * <p>We support the general notion of multiple 'windows'
- * That might be different parallel edit pages in a
- * desktop application (think about different open documents
- * in an editor) or multiple browser tabs in a
- * web application.</p>
- * <p>For web applications each browser tab or window will be
- * represented by an own {@link WindowContext}. All those
- * {@link WindowContext}s will be held in the users servlet
- * session as @SessionScoped bean.
- * </p>
- * <p>Every WindowContext is uniquely identified via a
- * 'windowId'. Each Thread is associated with at most
- * one single windowId at a time. The {@link WindowContextManager}
- * is the interface which allows resolving the current <i>windowId</i>
- * associated with this very Thread.</p>
- */
-public interface WindowContextManager
-{
- /**
- * @return the <i>windowId</i> associated with the very Thread or <code>null</code>.
- */
- String getCurrentWindowId();
-
- /**
- * Set the current windowId as the currently active for the very Thread.
- * If no WindowContext exists with the very windowId we will create a new one.
- * @param windowId
- */
- void activateWindowContext(String windowId);
-
- /**
- * @return the {@link WindowContext} associated with the very Thread or <code>null</code>.
- */
- WindowContext getCurrentWindowContext();
-
- /**
- * close the WindowContext with the currently activated windowId for the very Thread.
- * @return <code>true</code> if any did exist, <code>false</code> otherwise
- */
- boolean closeCurrentWindowContext();
-
-
- /**
- * Close all WindowContexts which are managed by the WindowContextManager.
- * This is necessary when the session gets closed down.
- * @return
- */
- void closeAllWindowContexts();
-
-
-}
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageResolver.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageResolver.java
index 779914d02..1cde0c879 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageResolver.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageResolver.java
@@ -74,7 +74,7 @@ public String getMessage(MessageContext messageContext, String messageTemplate,
{
try
{
- return messageBundle.getString(resourceKey + "." + category);
+ return messageBundle.getString(resourceKey + "_" + category);
}
catch (MissingResourceException e)
{
diff --git a/deltaspike/core/impl/src/test/resources/org/apache/deltaspike/test/core/api/message/TestMessages_en.properties b/deltaspike/core/impl/src/test/resources/org/apache/deltaspike/test/core/api/message/TestMessages_en.properties
index 34f671a46..5577657d8 100644
--- a/deltaspike/core/impl/src/test/resources/org/apache/deltaspike/test/core/api/message/TestMessages_en.properties
+++ b/deltaspike/core/impl/src/test/resources/org/apache/deltaspike/test/core/api/message/TestMessages_en.properties
@@ -21,4 +21,4 @@ welcome_to_deltaspike=Welcome to DeltaSpike
hello=test message to %s
categoryMessage=Value %s was set
-categoryMessage.longText=The value of the property has been set to %s.
+categoryMessage_longText=The value of the property has been set to %s.
|
06058e47d3b42f059340b6e3e4a1156c1fc76036
|
Mylyn Reviews
|
342870 TBR extension point f眉r task changeset mapping
Initial implementation of the extension point and generic implementation.
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.core/src/org/eclipse/mylyn/versions/tasks/core/IChangeSetMapping.java b/tbr/org.eclipse.mylyn.versions.tasks.core/src/org/eclipse/mylyn/versions/tasks/core/IChangeSetMapping.java
new file mode 100644
index 00000000..4acf89e2
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.core/src/org/eclipse/mylyn/versions/tasks/core/IChangeSetMapping.java
@@ -0,0 +1,16 @@
+package org.eclipse.mylyn.versions.tasks.core;
+
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+
+/**
+ *
+ * @author mattk
+ * @noextend
+ * @implement
+ */
+public interface IChangeSetMapping {
+ public ITask getTask();
+
+ public void addChangeSet(ChangeSet changeset);
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.classpath b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.classpath
new file mode 100644
index 00000000..64c5e31b
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.project b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.project
new file mode 100644
index 00000000..e990b987
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.mylyn.versions.tasks.mapper.generic</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.jdt.core.prefs b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 00000000..cc25307b
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+#Tue Feb 22 18:52:35 PST 2011
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.5
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.mylyn.tasks.ui.prefs b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.mylyn.tasks.ui.prefs
new file mode 100644
index 00000000..25ab2c05
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.mylyn.tasks.ui.prefs
@@ -0,0 +1,4 @@
+#Thu Mar 24 15:23:44 PDT 2011
+eclipse.preferences.version=1
+project.repository.kind=bugzilla
+project.repository.url=https\://bugs.eclipse.org/bugs
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.pde.core.prefs b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.pde.core.prefs
new file mode 100644
index 00000000..0cbec6da
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/.settings/org.eclipse.pde.core.prefs
@@ -0,0 +1,3 @@
+#Wed Mar 23 17:09:26 PDT 2011
+eclipse.preferences.version=1
+resolve.requirebundle=false
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..65a17072
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/META-INF/MANIFEST.MF
@@ -0,0 +1,15 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %Bundle-Name
+Bundle-SymbolicName: org.eclipse.mylyn.versions.tasks.mapper.generic;singleton:=true
+Bundle-Version: 0.1.0.qualifier
+Bundle-RequiredExecutionEnvironment: J2SE-1.5
+Require-Bundle: org.eclipse.mylyn.tasks.core;bundle-version="3.5.0",
+ org.eclipse.mylyn.versions.core;bundle-version="0.1.0",
+ org.eclipse.mylyn.versions.tasks.ui,
+ org.eclipse.core.runtime;bundle-version="3.7.0",
+ org.eclipse.core.resources;bundle-version="3.7.100",
+ org.eclipse.mylyn.tasks.ui;bundle-version="3.5.0",
+ org.eclipse.mylyn.versions.tasks.core;bundle-version="0.1.0"
+Export-Package: org.eclipse.mylyn.versions.tasks.mapper.generic;x-internal:=true
+Bundle-Vendor: %Bundle-Vendor
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/about.html b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/about.html
new file mode 100644
index 00000000..d774b07c
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/about.html
@@ -0,0 +1,27 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<html>
+<head>
+<title>About</title>
+<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1">
+</head>
+<body lang="EN-US">
+<h2>About This Content</h2>
+
+<p>June 25, 2008</p>
+<h3>License</h3>
+
+<p>The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise
+indicated below, the Content is provided to you under the terms and conditions of the
+Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is available
+at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>.
+For purposes of the EPL, "Program" will mean the Content.</p>
+
+<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is
+being redistributed by another party ("Redistributor") and different terms and conditions may
+apply to your use of any object code in the Content. Check the Redistributor's license that was
+provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise
+indicated below, the terms and conditions of the EPL still apply to any source code in the Content
+and such source code may be obtained at <a href="/">http://www.eclipse.org</a>.</p>
+
+</body>
+</html>
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/build.properties b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/build.properties
new file mode 100644
index 00000000..f0d40121
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/build.properties
@@ -0,0 +1,6 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ plugin.xml
+additional.bundles = org.eclipse.ui
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/plugin.properties b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/plugin.properties
new file mode 100644
index 00000000..eee282ab
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/plugin.properties
@@ -0,0 +1,12 @@
+###############################################################################
+# Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology 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:
+# Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+###############################################################################
+Bundle-Vendor = Eclipse Mylyn
+Bundle-Name = Mylyn Versions Framework Task Integration
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/plugin.xml b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/plugin.xml
new file mode 100644
index 00000000..2fc4c213
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/plugin.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+ <extension
+ id="org.eclipse.mylyn.versions.tasks.mapper.generic"
+ name="Generic Implementation"
+ point="org.eclipse.mylyn.versions.tasks.changesetmapping">
+ <changesetMapper
+ class="org.eclipse.mylyn.versions.tasks.mapper.generic.GenericTaskChangesetMapper">
+ </changesetMapper>
+ </extension>
+
+</plugin>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/pom.xml b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/pom.xml
new file mode 100644
index 00000000..8eec24c5
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/pom.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <artifactId>mylyn-reviews-tasks-parent</artifactId>
+ <groupId>org.eclipse.mylyn.reviews</groupId>
+ <version>0.7.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>org.eclipse.mylyn.versions.tasks.mapper.generic</artifactId>
+ <version>0.1.0-SNAPSHOT</version>
+ <packaging>eclipse-plugin</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.sonatype.tycho</groupId>
+ <artifactId>maven-osgi-source-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-pmd-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/EclipsePluginConfiguration.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/EclipsePluginConfiguration.java
new file mode 100644
index 00000000..13c848d2
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/EclipsePluginConfiguration.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.generic;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
+import org.eclipse.mylyn.tasks.core.TaskRepository;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class EclipsePluginConfiguration implements IConfiguration {
+
+ public List<IProject> getProjectsForTaskRepository(String connectorKind,
+ String repositoryUrl) {
+ List<IProject> projects = new ArrayList<IProject>();
+ for (IProject project : ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects()) {
+ TaskRepository repo = TasksUiPlugin.getDefault()
+ .getRepositoryForResource(project);
+ if (connectorKind.equals(repo.getConnectorKind())
+ && repositoryUrl.equals(repo.getRepositoryUrl())) {
+ projects.add(project);
+ }
+ }
+ return projects;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java
new file mode 100644
index 00000000..b9900d05
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapper.java
@@ -0,0 +1,98 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.generic;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+import org.eclipse.mylyn.versions.core.ScmCore;
+import org.eclipse.mylyn.versions.core.ScmRepository;
+import org.eclipse.mylyn.versions.core.spi.ScmConnector;
+import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping;
+import org.eclipse.mylyn.versions.tasks.ui.AbstractChangesetMappingProvider;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class GenericTaskChangesetMapper extends
+ AbstractChangesetMappingProvider {
+
+ private IConfiguration configuration;
+
+ public GenericTaskChangesetMapper() {
+ this.configuration = new EclipsePluginConfiguration();
+
+ }
+
+ public GenericTaskChangesetMapper(IConfiguration configuration) {
+ this.configuration = configuration;
+ }
+
+ public void getChangesetsForTask(IChangeSetMapping mapping,
+ IProgressMonitor monitor) throws CoreException {
+ ITask task = mapping.getTask();
+ if (task == null)
+ throw new IllegalArgumentException("task must not be null");
+
+ List<ScmRepository> repos = getRepositoriesFor(task);
+ for (ScmRepository repo : repos) {
+
+ List<ChangeSet> allChangeSets = repo.getConnector().getChangeSets(
+ repo, new NullProgressMonitor());
+ for (ChangeSet cs : allChangeSets) {
+ if (changeSetMatches(cs, task)) {
+ mapping.addChangeSet(cs);
+ }
+ }
+ }
+ }
+
+ private boolean changeSetMatches(ChangeSet cs, ITask task) {
+ // FIXME better detection
+ return cs.getMessage().contains(task.getTaskKey())
+ || cs.getMessage().contains(task.getUrl());
+ }
+
+ private List<ScmRepository> getRepositoriesFor(ITask task)
+ throws CoreException {
+
+ List<ScmRepository> repos = new ArrayList<ScmRepository>();
+
+ List<IProject> projects = configuration.getProjectsForTaskRepository(
+ task.getConnectorKind(), task.getRepositoryUrl());
+ for (IProject p : projects) {
+ ScmRepository repository = getRepositoryForProject(p);
+ repos.add(repository);
+ }
+ return repos;
+ }
+
+ private ScmRepository getRepositoryForProject(IProject p)
+ throws CoreException {
+ ScmConnector connector = ScmCore.getConnector(p);
+ ScmRepository repository = connector.getRepository(p,
+ new NullProgressMonitor());
+ return repository;
+ }
+
+ public int getScoreFor(ITask task) {
+ return 0;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IConfiguration.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IConfiguration.java
new file mode 100644
index 00000000..eca49106
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/IConfiguration.java
@@ -0,0 +1,28 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.mylyn.versions.tasks.mapper.generic;
+
+import java.util.List;
+
+import org.eclipse.core.resources.IProject;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public interface IConfiguration {
+
+ List<IProject> getProjectsForTaskRepository(String connectorKind,
+ String repositoryUrl);
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/TaskChangeSet.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/TaskChangeSet.java
new file mode 100644
index 00000000..c3c69a1a
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.generic/src/org/eclipse/mylyn/versions/tasks/mapper/generic/TaskChangeSet.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * 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:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.mapper.generic;
+
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+
+/**
+ *
+ * @author Kilian Matt
+ *
+ */
+public class TaskChangeSet {
+ private ChangeSet changeset;
+ private ITask task;
+
+ public TaskChangeSet(ITask task, ChangeSet cs) {
+ this.task = task;
+ this.changeset = cs;
+ }
+
+ public ChangeSet getChangeset() {
+ return changeset;
+ }
+
+ public ITask getTask() {
+ return task;
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
index db84438f..8b6ba783 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
@@ -10,7 +10,8 @@ Require-Bundle: org.eclipse.ui,
org.eclipse.ui.forms,
org.eclipse.mylyn.tasks.core;bundle-version="3.5.0",
org.eclipse.mylyn.versions.ui;bundle-version="0.1.0",
- org.eclipse.mylyn.versions.tasks.core;bundle-version="0.0.1"
+ org.eclipse.mylyn.versions.tasks.core;bundle-version="0.0.1",
+ org.eclipse.mylyn.commons.core;bundle-version="3.5.0"
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: J2SE-1.5
Export-Package: org.eclipse.mylyn.versions.tasks.ui;x-internal:=true
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml b/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
index 2d1fa5ed..5115a687 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
+ <extension-point id="org.eclipse.mylyn.versions.tasks.changesetmapping" name="Task changeset mapping provider" schema="schema/org.eclipse.mylyn.versions.tasks.changesetmapping.exsd"/>
<extension
point="org.eclipse.mylyn.tasks.ui.editors">
<pageFactory
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/schema/org.eclipse.mylyn.versions.tasks.changesetmapping.exsd b/tbr/org.eclipse.mylyn.versions.tasks.ui/schema/org.eclipse.mylyn.versions.tasks.changesetmapping.exsd
new file mode 100644
index 00000000..8c83f362
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/schema/org.eclipse.mylyn.versions.tasks.changesetmapping.exsd
@@ -0,0 +1,102 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.mylyn.versions.tasks.ui" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="org.eclipse.mylyn.versions.tasks.ui" id="org.eclipse.mylyn.versions.tasks.changesetmapping" name="Task changeset mapping provider"/>
+ </appinfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
+ <complexType>
+ <sequence>
+ <element ref="changesetMapper"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute translatable="true"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="changesetMapper">
+ <complexType>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn=":org.eclipse.mylyn.versions.tasks.ui.IChangesetMappingProvider"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="examples"/>
+ </appinfo>
+ <documentation>
+ [Enter extension point usage example here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="apiinfo"/>
+ </appinfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="implementation"/>
+ </appinfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+
+</schema>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java
new file mode 100644
index 00000000..6e971bd3
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java
@@ -0,0 +1,14 @@
+package org.eclipse.mylyn.versions.tasks.ui;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping;
+
+public abstract class AbstractChangesetMappingProvider {
+
+ public abstract void getChangesetsForTask(IChangeSetMapping mapping, IProgressMonitor monitor) throws CoreException ;
+
+ public abstract int getScoreFor(ITask task);
+}
+
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java
index cd5c8fb1..3272ccca 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java
@@ -15,6 +15,7 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.jface.action.ContributionManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
@@ -24,9 +25,7 @@
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
import org.eclipse.mylyn.versions.core.ChangeSet;
-import org.eclipse.mylyn.versions.core.ScmCore;
-import org.eclipse.mylyn.versions.core.ScmRepository;
-import org.eclipse.mylyn.versions.core.spi.ScmConnector;
+import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping;
import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
@@ -42,6 +41,7 @@
* @author Kilian Matt
*
*/
+@SuppressWarnings("restriction")
public class ChangesetPart extends AbstractTaskEditorPart {
public ChangesetPart() {
setPartName("Changeset");
@@ -82,29 +82,23 @@ public void createControl(Composite parent, FormToolkit toolkit) {
table.setContentProvider(ArrayContentProvider.getInstance());
table.setLabelProvider(new ITableLabelProvider() {
-
public void addListener(ILabelProviderListener listener) {
}
-
public void dispose() {
}
-
public boolean isLabelProperty(Object element, String property) {
return false;
}
-
public void removeListener(ILabelProviderListener listener) {
}
-
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
-
public String getColumnText(Object element, int columnIndex) {
TaskChangeSet cs = ((TaskChangeSet) element);
switch (columnIndex) {
@@ -133,37 +127,39 @@ public String getColumnText(Object element, int columnIndex) {
}
private List<TaskChangeSet> getInput() {
- List<ScmConnector> connectors = ScmCore.getAllRegisteredConnectors();
- for (ScmConnector c : connectors) {
- try {
- List<ScmRepository> repositories = c
- .getRepositories(new NullProgressMonitor());
- for (ScmRepository r : repositories) {
- ITask task = getModel().getTask();
- List<TaskChangeSet> changes = new ArrayList<TaskChangeSet>();
- List<ChangeSet> changeSets = c.getChangeSets(r,
- new NullProgressMonitor());
- if (changeSets == null)
- continue;
- for (ChangeSet cs : changeSets) {
- if (changeSetMatches(cs))
- changes.add(new TaskChangeSet(task, cs));
- }
- if (!changes.isEmpty())
- return changes;
- }
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ int score = Integer.MIN_VALUE;
+ AbstractChangesetMappingProvider bestProvider = null;
+ final ITask task = getModel().getTask();
+
+ for (AbstractChangesetMappingProvider mappingProvider : TaskChangesetUtil
+ .getMappingProviders()) {
+ if (score < mappingProvider.getScoreFor(task))
+ ;
+ {
+ bestProvider = mappingProvider;
}
-
}
- return null;
- }
+ final List<TaskChangeSet> changesets = new ArrayList<TaskChangeSet>();
+ try {
+
+ IChangeSetMapping changesetsMapping = new IChangeSetMapping() {
- private boolean changeSetMatches(ChangeSet cs) {
- return cs.getMessage().contains(getModel().getTask().getTaskKey())
- || cs.getMessage().contains(getModel().getTask().getUrl());
+ public ITask getTask() {
+ return task;
+ }
+
+ public void addChangeSet(ChangeSet changeset) {
+ changesets.add(new TaskChangeSet(task, changeset));
+ }
+ };
+ // FIXME progress monitor
+ bestProvider.getChangesetsForTask(changesetsMapping,
+ new NullProgressMonitor());
+ } catch (CoreException e) {
+ // FIXME Auto-generated catch block
+ e.printStackTrace();
+ }
+ return changesets;
}
}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/IChangeSets.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/IChangeSets.java
new file mode 100644
index 00000000..5423d5bd
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/IChangeSets.java
@@ -0,0 +1,4 @@
+package org.eclipse.mylyn.versions.tasks.ui;
+public class IChangeSets {
+
+}
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/TaskChangesetUtil.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/TaskChangesetUtil.java
new file mode 100644
index 00000000..4ff3bc6c
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/TaskChangesetUtil.java
@@ -0,0 +1,76 @@
+package org.eclipse.mylyn.versions.tasks.ui;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IExtensionRegistry;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.MultiStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.mylyn.commons.core.StatusHandler;
+import org.eclipse.osgi.util.NLS;
+
+public class TaskChangesetUtil {
+ private static final String PLUGIN_ID = "org.eclipse.mylyn.versions.tasks.ui";
+
+ private static List<AbstractChangesetMappingProvider> providers;
+
+ public static List<AbstractChangesetMappingProvider> getMappingProviders() {
+ if (providers != null)
+ return providers;
+
+ return providers = loadMappingProviders();
+ }
+
+ private synchronized static List<AbstractChangesetMappingProvider> loadMappingProviders() {
+ List<AbstractChangesetMappingProvider> providers = new ArrayList<AbstractChangesetMappingProvider>();
+
+ MultiStatus result = new MultiStatus(PLUGIN_ID, 0,
+ "Task Changeset Mapping Provider failed to load", null); //$NON-NLS-1$
+
+ IExtensionRegistry registry = Platform.getExtensionRegistry();
+ IExtensionPoint connectorsExtensionPoint = registry
+ .getExtensionPoint("org.eclipse.mylyn.versions.tasks.changesetmapping"); //$NON-NLS-1$
+ IExtension[] extensions = connectorsExtensionPoint.getExtensions();
+ for (IExtension extension : extensions) {
+ IConfigurationElement[] elements = extension
+ .getConfigurationElements();
+ for (IConfigurationElement element : elements) {
+ try {
+ Object object = element.createExecutableExtension("class"); //$NON-NLS-1$
+ if (object instanceof AbstractChangesetMappingProvider) {
+ providers
+ .add((AbstractChangesetMappingProvider) object);
+ } else {
+ result.add(new Status(
+ IStatus.ERROR,
+ PLUGIN_ID,
+ // FIXME error message
+ NLS.bind(
+ "Extension ''{0}'' does not extend expected class for extension contributed by {1}", //$NON-NLS-1$
+ object.getClass().getCanonicalName(),
+ element.getContributor().getName())));
+ }
+ } catch (Throwable e) {
+ result.add(new Status(
+ IStatus.ERROR,
+ PLUGIN_ID,
+ // FIXME error message
+ NLS.bind(
+ "Connector core failed to load for extension contributed by {0}", element.getContributor().getName()), e)); //$NON-NLS-1$
+ }
+ }
+ }
+
+ if (!result.isOK()) {
+ StatusHandler.log(result);
+ }
+
+ return providers;
+ }
+
+}
|
1f47d355234777b707191b9c8e813c0000ecf212
|
hadoop
|
YARN-2059. Added admin ACLs support to Timeline- Server. Contributed by Zhijie Shen. svn merge --ignore-ancestry -c 1597207- ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1597208 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index e34b930003f51..c74e777d400fc 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -87,6 +87,9 @@ Release 2.5.0 - UNRELEASED
YARN-2012. Fair Scheduler: allow default queue placement rule to take an
arbitrary queue (Ashwin Shankar via Sandy Ryza)
+ YARN-2059. Added admin ACLs support to Timeline Server. (Zhijie Shen via
+ vinodkv)
+
OPTIMIZATIONS
BUG FIXES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TimelineACLsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TimelineACLsManager.java
index 5bc8705222f88..8009b39c94f72 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TimelineACLsManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TimelineACLsManager.java
@@ -27,8 +27,8 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity;
-import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
+import org.apache.hadoop.yarn.security.AdminACLsManager;
import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.EntityIdentifier;
import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.TimelineStore.SystemFilter;
@@ -42,11 +42,10 @@ public class TimelineACLsManager {
private static final Log LOG = LogFactory.getLog(TimelineACLsManager.class);
- private boolean aclsEnabled;
+ private AdminACLsManager adminAclsManager;
public TimelineACLsManager(Configuration conf) {
- aclsEnabled = conf.getBoolean(YarnConfiguration.YARN_ACL_ENABLE,
- YarnConfiguration.DEFAULT_YARN_ACL_ENABLE);
+ this.adminAclsManager = new AdminACLsManager(conf);
}
public boolean checkAccess(UserGroupInformation callerUGI,
@@ -57,7 +56,7 @@ public boolean checkAccess(UserGroupInformation callerUGI,
+ new EntityIdentifier(entity.getEntityId(), entity.getEntityType()));
}
- if (!aclsEnabled) {
+ if (!adminAclsManager.areACLsEnabled()) {
return true;
}
@@ -70,10 +69,12 @@ public boolean checkAccess(UserGroupInformation callerUGI,
+ " is corrupted.");
}
String owner = values.iterator().next().toString();
- // TODO: Currently we just check the user is the timeline entity owner. In
- // the future, we need to check whether the user is admin or is in the
+ // TODO: Currently we just check the user is the admin or the timeline
+ // entity owner. In the future, we need to check whether the user is in the
// allowed user/group list
- if (callerUGI != null && callerUGI.getShortUserName().equals(owner)) {
+ if (callerUGI != null
+ && (adminAclsManager.isAdmin(callerUGI) ||
+ callerUGI.getShortUserName().equals(owner))) {
return true;
}
return false;
@@ -81,8 +82,11 @@ public boolean checkAccess(UserGroupInformation callerUGI,
@Private
@VisibleForTesting
- public void setACLsEnabled(boolean aclsEnabled) {
- this.aclsEnabled = aclsEnabled;
+ public AdminACLsManager
+ setAdminACLsManager(AdminACLsManager adminAclsManager) {
+ AdminACLsManager oldAdminACLsManager = this.adminAclsManager;
+ this.adminAclsManager = adminAclsManager;
+ return oldAdminACLsManager;
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TimelineWebServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TimelineWebServices.java
index 6041779b13a94..5d749fa090653 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TimelineWebServices.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TimelineWebServices.java
@@ -346,8 +346,9 @@ public TimelinePutResponse postEntities(
new EntityIdentifier(entity.getEntityId(), entity.getEntityType());
// check if there is existing entity
+ TimelineEntity existingEntity = null;
try {
- TimelineEntity existingEntity =
+ existingEntity =
store.getEntity(entityID.getId(), entityID.getType(),
EnumSet.of(Field.PRIMARY_FILTERS));
if (existingEntity != null
@@ -369,10 +370,14 @@ public TimelinePutResponse postEntities(
continue;
}
- // inject owner information for the access check
+ // inject owner information for the access check if this is the first
+ // time to post the entity, in case it's the admin who is updating
+ // the timeline data.
try {
- injectOwnerInfo(entity,
- callerUGI == null ? "" : callerUGI.getShortUserName());
+ if (existingEntity == null) {
+ injectOwnerInfo(entity,
+ callerUGI == null ? "" : callerUGI.getShortUserName());
+ }
} catch (YarnException e) {
// Skip the entity which messes up the primary filter and record the
// error
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TestTimelineACLsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TestTimelineACLsManager.java
index 2c536681aed25..39102b43badfa 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TestTimelineACLsManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/timeline/security/TestTimelineACLsManager.java
@@ -49,6 +49,7 @@ public void testYarnACLsNotEnabled() throws Exception {
public void testYarnACLsEnabled() throws Exception {
Configuration conf = new YarnConfiguration();
conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true);
+ conf.set(YarnConfiguration.YARN_ADMIN_ACL, "admin");
TimelineACLsManager timelineACLsManager =
new TimelineACLsManager(conf);
TimelineEntity entity = new TimelineEntity();
@@ -63,12 +64,17 @@ public void testYarnACLsEnabled() throws Exception {
"Other shouldn't be allowed to access",
timelineACLsManager.checkAccess(
UserGroupInformation.createRemoteUser("other"), entity));
+ Assert.assertTrue(
+ "Admin should be allowed to access",
+ timelineACLsManager.checkAccess(
+ UserGroupInformation.createRemoteUser("admin"), entity));
}
@Test
public void testCorruptedOwnerInfo() throws Exception {
Configuration conf = new YarnConfiguration();
conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true);
+ conf.set(YarnConfiguration.YARN_ADMIN_ACL, "owner");
TimelineACLsManager timelineACLsManager =
new TimelineACLsManager(conf);
TimelineEntity entity = new TimelineEntity();
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestTimelineWebServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestTimelineWebServices.java
index 9b0ae3761d26a..7e3e409940386 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestTimelineWebServices.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/TestTimelineWebServices.java
@@ -40,6 +40,7 @@
import org.apache.hadoop.yarn.api.records.timeline.TimelineEvents;
import org.apache.hadoop.yarn.api.records.timeline.TimelinePutResponse;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.security.AdminACLsManager;
import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.TestMemoryTimelineStore;
import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.TimelineStore;
import org.apache.hadoop.yarn.server.applicationhistoryservice.timeline.security.TimelineACLsManager;
@@ -64,6 +65,7 @@ public class TestTimelineWebServices extends JerseyTest {
private static TimelineStore store;
private static TimelineACLsManager timelineACLsManager;
+ private static AdminACLsManager adminACLsManager;
private static String remoteUser;
private long beforeTime;
@@ -83,6 +85,9 @@ protected void configureServlets() {
Configuration conf = new YarnConfiguration();
conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, false);
timelineACLsManager = new TimelineACLsManager(conf);
+ conf.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true);
+ conf.set(YarnConfiguration.YARN_ADMIN_ACL, "admin");
+ adminACLsManager = new AdminACLsManager(conf);
bind(TimelineACLsManager.class).toInstance(timelineACLsManager);
serve("/*").with(GuiceContainer.class);
filter("/*").through(TestFilter.class);
@@ -387,7 +392,8 @@ public void testPostEntities() throws Exception {
@Test
public void testPostEntitiesWithYarnACLsEnabled() throws Exception {
- timelineACLsManager.setACLsEnabled(true);
+ AdminACLsManager oldAdminACLsManager =
+ timelineACLsManager.setAdminACLsManager(adminACLsManager);
remoteUser = "tester";
try {
TimelineEntities entities = new TimelineEntities();
@@ -419,14 +425,15 @@ public void testPostEntitiesWithYarnACLsEnabled() throws Exception {
Assert.assertEquals(TimelinePutResponse.TimelinePutError.ACCESS_DENIED,
putResponse.getErrors().get(0).getErrorCode());
} finally {
- timelineACLsManager.setACLsEnabled(false);
+ timelineACLsManager.setAdminACLsManager(oldAdminACLsManager);
remoteUser = null;
}
}
@Test
public void testGetEntityWithYarnACLsEnabled() throws Exception {
- timelineACLsManager.setACLsEnabled(true);
+ AdminACLsManager oldAdminACLsManager =
+ timelineACLsManager.setAdminACLsManager(adminACLsManager);
remoteUser = "tester";
try {
TimelineEntities entities = new TimelineEntities();
@@ -481,14 +488,15 @@ public void testGetEntityWithYarnACLsEnabled() throws Exception {
assertEquals(ClientResponse.Status.NOT_FOUND,
response.getClientResponseStatus());
} finally {
- timelineACLsManager.setACLsEnabled(false);
+ timelineACLsManager.setAdminACLsManager(oldAdminACLsManager);
remoteUser = null;
}
}
@Test
public void testGetEntitiesWithYarnACLsEnabled() {
- timelineACLsManager.setACLsEnabled(true);
+ AdminACLsManager oldAdminACLsManager =
+ timelineACLsManager.setAdminACLsManager(adminACLsManager);
remoteUser = "tester";
try {
TimelineEntities entities = new TimelineEntities();
@@ -526,14 +534,15 @@ public void testGetEntitiesWithYarnACLsEnabled() {
assertEquals("test type 4", entities.getEntities().get(0).getEntityType());
assertEquals("test id 5", entities.getEntities().get(0).getEntityId());
} finally {
- timelineACLsManager.setACLsEnabled(false);
+ timelineACLsManager.setAdminACLsManager(oldAdminACLsManager);
remoteUser = null;
}
}
@Test
public void testGetEventsWithYarnACLsEnabled() {
- timelineACLsManager.setACLsEnabled(true);
+ AdminACLsManager oldAdminACLsManager =
+ timelineACLsManager.setAdminACLsManager(adminACLsManager);
remoteUser = "tester";
try {
TimelineEntities entities = new TimelineEntities();
@@ -579,7 +588,7 @@ public void testGetEventsWithYarnACLsEnabled() {
assertEquals(1, events.getAllEvents().size());
assertEquals("test id 6", events.getAllEvents().get(0).getEntityId());
} finally {
- timelineACLsManager.setACLsEnabled(false);
+ timelineACLsManager.setAdminACLsManager(oldAdminACLsManager);
remoteUser = null;
}
}
|
953a99c75cde29a18db58abde3fdee720fcddc4f
|
elasticsearch
|
fix a bug in new checksum mechanism that caused- for replicas not to retain the _checksums file. Also
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/common/lucene/Directories.java b/modules/elasticsearch/src/main/java/org/elasticsearch/common/lucene/Directories.java
index ffb8e217f1e02..71f405e1ced1a 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/common/lucene/Directories.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/common/lucene/Directories.java
@@ -41,29 +41,6 @@
*/
public class Directories {
- /**
- * Deletes all the files from a directory.
- *
- * @param directory The directory to delete all the files from
- * @throws IOException if an exception occurs during the delete process
- */
- public static void deleteFiles(Directory directory) throws IOException {
- String[] files = directory.listAll();
- IOException lastException = null;
- for (String file : files) {
- try {
- directory.deleteFile(file);
- } catch (FileNotFoundException e) {
- // ignore
- } catch (IOException e) {
- lastException = e;
- }
- }
- if (lastException != null) {
- throw lastException;
- }
- }
-
/**
* Returns the estimated size of a {@link Directory}.
*/
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/gateway/CommitPoint.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/gateway/CommitPoint.java
index f25b655e9f7cc..1791a50410ce8 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/gateway/CommitPoint.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/gateway/CommitPoint.java
@@ -62,10 +62,10 @@ public long length() {
}
public boolean isSame(StoreFileMetaData md) {
- if (checksum != null && md.checksum() != null) {
- return checksum.equals(md.checksum());
+ if (checksum == null || md.checksum() == null) {
+ return false;
}
- return length == md.length();
+ return length == md.length() && checksum.equals(md.checksum());
}
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java
index 869d527fec9d7..986222f56a39d 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java
@@ -93,7 +93,8 @@ public static class Actions {
this.translogSize = componentSettings.getAsBytesSize("translog_size", new ByteSizeValue(100, ByteSizeUnit.KB));
this.compress = componentSettings.getAsBoolean("compress", true);
- logger.debug("using concurrent_streams [{}], file_chunk_size [{}], translog_size [{}], translog_ops [{}], and compress [{}]", concurrentStreams, fileChunkSize, translogOps, translogSize, compress);
+ logger.debug("using concurrent_streams [{}], file_chunk_size [{}], translog_size [{}], translog_ops [{}], and compress [{}]",
+ concurrentStreams, fileChunkSize, translogSize, translogOps, compress);
transportService.registerHandler(Actions.START_RECOVERY, new StartRecoveryTransportRequestHandler());
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/StoreFileMetaData.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/StoreFileMetaData.java
index cafd3aa200c6a..c1b7815b5e9ae 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/StoreFileMetaData.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/StoreFileMetaData.java
@@ -66,10 +66,10 @@ public long length() {
}
public boolean isSame(StoreFileMetaData other) {
- if (checksum != null && other.checksum != null) {
- return checksum.equals(other.checksum);
+ if (checksum == null || other.checksum == null) {
+ return false;
}
- return length == other.length;
+ return length == other.length && checksum.equals(other.checksum);
}
public static StoreFileMetaData readStoreFileMetaData(StreamInput in) throws IOException {
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java
index 981c057aaff28..a516379bcc36b 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java
@@ -46,6 +46,8 @@
*/
public abstract class AbstractStore extends AbstractIndexShardComponent implements Store {
+ static final String CHECKSUMS_PREFIX = "_checksums-";
+
protected final IndexStore indexStore;
private volatile ImmutableMap<String, StoreFileMetaData> filesMetadata = ImmutableMap.of();
@@ -90,7 +92,24 @@ public StoreFileMetaData metaData(String name) throws IOException {
}
@Override public void deleteContent() throws IOException {
- Directories.deleteFiles(directory());
+ String[] files = directory().listAll();
+ IOException lastException = null;
+ for (String file : files) {
+ if (file.startsWith(CHECKSUMS_PREFIX)) {
+ ((StoreDirectory) directory()).deleteFileChecksum(file);
+ } else {
+ try {
+ directory().deleteFile(file);
+ } catch (FileNotFoundException e) {
+ // ignore
+ } catch (IOException e) {
+ lastException = e;
+ }
+ }
+ }
+ if (lastException != null) {
+ throw lastException;
+ }
}
@Override public void fullDelete() throws IOException {
@@ -104,10 +123,10 @@ public StoreFileMetaData metaData(String name) throws IOException {
public static Map<String, String> readChecksums(Directory dir) throws IOException {
long lastFound = -1;
for (String name : dir.listAll()) {
- if (!name.startsWith("_checksums-")) {
+ if (!name.startsWith(CHECKSUMS_PREFIX)) {
continue;
}
- long current = Long.parseLong(name.substring("_checksums-".length()));
+ long current = Long.parseLong(name.substring(CHECKSUMS_PREFIX.length()));
if (current > lastFound) {
lastFound = current;
}
@@ -115,7 +134,7 @@ public static Map<String, String> readChecksums(Directory dir) throws IOExceptio
if (lastFound == -1) {
return ImmutableMap.of();
}
- IndexInput indexInput = dir.openInput("_checksums-" + lastFound);
+ IndexInput indexInput = dir.openInput(CHECKSUMS_PREFIX + lastFound);
try {
indexInput.readInt(); // version
return indexInput.readStringStringMap();
@@ -129,7 +148,7 @@ public void writeChecksums() throws IOException {
}
private void writeChecksums(StoreDirectory dir) throws IOException {
- String checksumName = "_checksums-" + System.currentTimeMillis();
+ String checksumName = CHECKSUMS_PREFIX + System.currentTimeMillis();
ImmutableMap<String, StoreFileMetaData> files = list();
synchronized (mutex) {
Map<String, String> checksums = new HashMap<String, String>();
@@ -144,9 +163,9 @@ private void writeChecksums(StoreDirectory dir) throws IOException {
output.close();
}
for (StoreFileMetaData metaData : files.values()) {
- if (metaData.name().startsWith("_checksums") && !checksumName.equals(metaData.name())) {
+ if (metaData.name().startsWith(CHECKSUMS_PREFIX) && !checksumName.equals(metaData.name())) {
try {
- directory().deleteFile(metaData.name());
+ dir.deleteFileChecksum(metaData.name());
} catch (Exception e) {
// ignore
}
@@ -255,7 +274,19 @@ public Directory delegate() {
}
}
+ public void deleteFileChecksum(String name) throws IOException {
+ delegate.deleteFile(name);
+ synchronized (mutex) {
+ filesMetadata = MapBuilder.newMapBuilder(filesMetadata).remove(name).immutableMap();
+ files = filesMetadata.keySet().toArray(new String[filesMetadata.size()]);
+ }
+ }
+
@Override public void deleteFile(String name) throws IOException {
+ // we don't allow to delete the checksums files, only using the deleteChecksum method
+ if (name.startsWith(CHECKSUMS_PREFIX)) {
+ return;
+ }
delegate.deleteFile(name);
synchronized (mutex) {
filesMetadata = MapBuilder.newMapBuilder(filesMetadata).remove(name).immutableMap();
|
6626b44286943b4721df3345479cf5cf3ec8e2b2
|
internetarchive$heritrix3
|
generics warnings fixes
This commit does not change any functionality, just
alters generics to reduce warnings in Eclipse.
|
p
|
https://github.com/internetarchive/heritrix3
|
diff --git a/commons/src/main/java/org/apache/commons/httpclient/Cookie.java b/commons/src/main/java/org/apache/commons/httpclient/Cookie.java
index 5f0650984..1db473a85 100644
--- a/commons/src/main/java/org/apache/commons/httpclient/Cookie.java
+++ b/commons/src/main/java/org/apache/commons/httpclient/Cookie.java
@@ -61,8 +61,8 @@
*
* @version $Revision$ $Date$
*/
-@SuppressWarnings({"serial","unchecked"}) // <- HERITRIX CHANGE
-public class Cookie extends NameValuePair implements Serializable, Comparator {
+@SuppressWarnings({"serial"}) // <- HERITRIX CHANGE
+public class Cookie extends NameValuePair implements Serializable, Comparator<Cookie> {
// ----------------------------------------------------------- Constructors
@@ -415,6 +415,7 @@ public int hashCode() {
* @param obj The object to compare against.
* @return true if the two objects are equal.
*/
+ @Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (this == obj) return true;
@@ -454,7 +455,8 @@ public String toExternalForm() {
* @param o2 The second object to be compared
* @return See {@link java.util.Comparator#compare(Object,Object)}
*/
- public int compare(Object o1, Object o2) {
+ @Override
+ public int compare(Cookie o1, Cookie o2) {
LOG.trace("enter Cookie.compare(Object, Object)");
if (!(o1 instanceof Cookie)) {
diff --git a/commons/src/main/java/org/apache/commons/httpclient/HttpConnection.java b/commons/src/main/java/org/apache/commons/httpclient/HttpConnection.java
index c9e86a615..d9c2cf134 100644
--- a/commons/src/main/java/org/apache/commons/httpclient/HttpConnection.java
+++ b/commons/src/main/java/org/apache/commons/httpclient/HttpConnection.java
@@ -91,7 +91,6 @@
*
* @version $Revision$ $Date$
*/
-@SuppressWarnings("unchecked") // <- HERITRIX CHANGE
public class HttpConnection {
// ----------------------------------------------------------- Constructors
@@ -1162,7 +1161,7 @@ public void shutdownOutput() {
// Socket.shutdownOutput is a JDK 1.3
// method. We'll use reflection in case
// we're running in an older VM
- Class[] paramsClasses = new Class[0];
+ Class<?>[] paramsClasses = new Class[0];
Method shutdownOutput =
socket.getClass().getMethod("shutdownOutput", paramsClasses);
Object[] params = new Object[0];
diff --git a/commons/src/main/java/org/apache/commons/httpclient/HttpMethodBase.java b/commons/src/main/java/org/apache/commons/httpclient/HttpMethodBase.java
index fe8be4b01..cda1b9d20 100644
--- a/commons/src/main/java/org/apache/commons/httpclient/HttpMethodBase.java
+++ b/commons/src/main/java/org/apache/commons/httpclient/HttpMethodBase.java
@@ -94,7 +94,7 @@
*
* @version $Revision$ $Date$
*/
-@SuppressWarnings({"deprecation","unchecked"}) // <- // IA/HERITRIX change
+@SuppressWarnings({"deprecation"}) // <- // IA/HERITRIX change
public abstract class HttpMethodBase implements HttpMethod {
// -------------------------------------------------------------- Constants
@@ -1145,8 +1145,9 @@ private CookieSpec getCookieSpec(final HttpState state) {
} else {
this.cookiespec = CookiePolicy.getSpecByPolicy(i);
}
- this.cookiespec.setValidDateFormats(
- (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS));
+ @SuppressWarnings("unchecked")
+ Collection<String> val = (Collection<String>)this.params.getParameter(HttpMethodParams.DATE_PATTERNS);
+ this.cookiespec.setValidDateFormats(val);
}
return this.cookiespec;
}
diff --git a/commons/src/main/java/org/apache/commons/httpclient/HttpParser.java b/commons/src/main/java/org/apache/commons/httpclient/HttpParser.java
index 7ae07c974..a67636552 100644
--- a/commons/src/main/java/org/apache/commons/httpclient/HttpParser.java
+++ b/commons/src/main/java/org/apache/commons/httpclient/HttpParser.java
@@ -47,7 +47,6 @@
*
* @since 2.0beta1
*/
-@SuppressWarnings("unchecked") // <- IA/HERITRIX CHANGE
public class HttpParser {
/** Log object for this class. */
@@ -159,7 +158,7 @@ public static String readLine(InputStream inputStream) throws IOException {
public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException {
LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)");
- ArrayList headers = new ArrayList();
+ ArrayList<Header> headers = new ArrayList<Header>();
String name = null;
StringBuffer value = null;
for (; ;) {
diff --git a/commons/src/main/java/org/apache/commons/httpclient/HttpState.java b/commons/src/main/java/org/apache/commons/httpclient/HttpState.java
index 031ac5f14..5b95cb26f 100644
--- a/commons/src/main/java/org/apache/commons/httpclient/HttpState.java
+++ b/commons/src/main/java/org/apache/commons/httpclient/HttpState.java
@@ -30,23 +30,21 @@
package org.apache.commons.httpclient;
import java.util.ArrayList;
-import java.util.Collection; // <- IA/HERITRIX CHANGE
+import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
-import java.util.Map;
-import java.util.List;
import java.util.Iterator;
-import java.util.SortedMap; // <- IA/HERITRIX CHANGE
-import java.util.TreeMap; // <- IA/HERITRIX CHANGE
+import java.util.Map;
+import java.util.SortedMap;
import java.util.concurrent.ConcurrentSkipListMap;
-import org.apache.commons.httpclient.cookie.CookieSpec;
+import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;
-import org.apache.commons.httpclient.auth.AuthScope;
+import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import com.sleepycat.collections.StoredIterator; // <- IA/HERITRIX CHANGE
+import com.sleepycat.collections.StoredIterator;
/**
* <p>
@@ -67,7 +65,6 @@
* @version $Revision$ $Date$
*
*/
-@SuppressWarnings({"unchecked","unused"}) // <- IA/HERITRIX CHANGE
public class HttpState {
// ----------------------------------------------------- Instance Variables
@@ -76,13 +73,13 @@ public class HttpState {
* Map of {@link Credentials credentials} by realm that this
* HTTP state contains.
*/
- private HashMap credMap = new HashMap();
+ private HashMap<AuthScope, Credentials> credMap = new HashMap<AuthScope, Credentials>();
/**
* Map of {@link Credentials proxy credentials} by realm that this
* HTTP state contains
*/
- private HashMap proxyCred = new HashMap();
+ private HashMap<AuthScope, Credentials> proxyCred = new HashMap<AuthScope, Credentials>();
// BEGIN IA/HERITRIX CHANGES
// /**
@@ -92,7 +89,7 @@ public class HttpState {
/**
* SortedMap of {@link Cookie cookies} that this HTTP state contains.
*/
- private SortedMap cookiesMap = new ConcurrentSkipListMap();
+ private SortedMap<String, Cookie> cookiesMap = new ConcurrentSkipListMap<String, Cookie>();
// END IA/HERITRIX CHANGES
private boolean preemptive = false;
@@ -200,8 +197,8 @@ public synchronized Cookie[] getCookies() {
// BEGIN IA/HERITRIX CHANGES
// PRIOR IMPL & COMPARISON HARNESS LEFT COMMENTED OUT FOR TEMPORARY REFERENCE
// Cookie[] arrayListAnswer = (Cookie[]) (cookiesArrayList.toArray(new Cookie[cookiesArrayList.size()]));
- ArrayList arrayableCookies = new ArrayList();
- Iterator iter = cookiesMap.values().iterator();
+ ArrayList<Cookie> arrayableCookies = new ArrayList<Cookie>();
+ Iterator<Cookie> iter = cookiesMap.values().iterator();
while(iter.hasNext()) {
arrayableCookies.add(iter.next());
}
@@ -226,7 +223,7 @@ public synchronized Cookie[] getCookies() {
*
* @return sorter map of {@link Cookie cookies}
*/
- public SortedMap getCookiesMap() {
+ public SortedMap<String, Cookie> getCookiesMap() {
return cookiesMap;
}
@@ -236,7 +233,7 @@ public SortedMap getCookiesMap() {
*
* @param map alternate sorted map to use to store cookies
*/
- public void setCookiesMap(SortedMap map) {
+ public void setCookiesMap(SortedMap<String, Cookie> map) {
this.cookiesMap = map;
}
// END IA/HERITRIX ADDITIONS
@@ -321,9 +318,9 @@ public synchronized boolean purgeExpiredCookies(Date date) {
// }
// }
boolean removed = false;
- Iterator it = cookiesMap.values().iterator();
+ Iterator<Cookie> it = cookiesMap.values().iterator();
while (it.hasNext()) {
- if (((Cookie) (it.next())).isExpired(date)) {
+ if (it.next().isExpired(date)) {
it.remove();
removed = true;
}
@@ -457,15 +454,15 @@ public synchronized void setCredentials(final AuthScope authscope, final Credent
* @return the credentials
*
*/
- private static Credentials matchCredentials(final HashMap map, final AuthScope authscope) {
+ private static Credentials matchCredentials(final HashMap<AuthScope, Credentials> map, final AuthScope authscope) {
// see if we get a direct hit
- Credentials creds = (Credentials)map.get(authscope);
+ Credentials creds = map.get(authscope);
if (creds == null) {
// Nope.
// Do a full scan
int bestMatchFactor = -1;
AuthScope bestMatch = null;
- Iterator items = map.keySet().iterator();
+ Iterator<AuthScope> items = map.keySet().iterator();
while (items.hasNext()) {
AuthScope current = (AuthScope)items.next();
int factor = authscope.match(current);
@@ -649,12 +646,12 @@ public synchronized String toString() {
* @param credMap The credentials.
* @return The string representation.
*/
- private static String getCredentialsStringRepresentation(final Map credMap) {
+ private static String getCredentialsStringRepresentation(final Map<AuthScope, Credentials> credMap) {
StringBuffer sbResult = new StringBuffer();
- Iterator iter = credMap.keySet().iterator();
+ Iterator<AuthScope> iter = credMap.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
- Credentials cred = (Credentials) credMap.get(key);
+ Credentials cred = credMap.get(key);
if (sbResult.length() > 0) {
sbResult.append(", ");
}
@@ -670,11 +667,11 @@ private static String getCredentialsStringRepresentation(final Map credMap) {
* @param cookies The cookies
* @return The string representation.
*/
- private static String getCookiesStringRepresentation(final Collection cookies) { // <- IA/HERITRIX CHANGE
+ private static String getCookiesStringRepresentation(final Collection<Cookie> cookies) { // <- IA/HERITRIX CHANGE
StringBuffer sbResult = new StringBuffer();
- Iterator iter = cookies.iterator();
+ Iterator<Cookie> iter = cookies.iterator();
while (iter.hasNext()) {
- Cookie ck = (Cookie) iter.next();
+ Cookie ck = iter.next();
if (sbResult.length() > 0) {
sbResult.append("#");
}
diff --git a/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpec.java b/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpec.java
index 5b14bff4e..46be9ff8c 100644
--- a/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpec.java
+++ b/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpec.java
@@ -51,7 +51,6 @@
*
* @since 2.0
*/
-@SuppressWarnings("unchecked") // <- IA/HERITRIX CHANGE
public interface CookieSpec {
/** Path delimiter */
@@ -140,7 +139,7 @@ void validate(String host, int port, String path, boolean secure,
*
* @param datepatterns collection of date patterns
*/
- void setValidDateFormats(Collection datepatterns);
+ void setValidDateFormats(Collection<String> datepatterns);
/**
* Returns the {@link Collection} of date patterns used for parsing. The String patterns are compatible
@@ -148,7 +147,7 @@ void validate(String host, int port, String path, boolean secure,
*
* @return collection of date patterns
*/
- Collection getValidDateFormats();
+ Collection<String> getValidDateFormats();
/**
* Determines if a Cookie matches a location.
@@ -195,7 +194,7 @@ Cookie[] match(String host, int port, String path, boolean secure,
*
* @param host the host to which the request is being submitted
* @param port the port to which the request is being submitted
- * (currenlty ignored)
+ * (currently ignored)
* @param path the path to which the request is being submitted
* @param secure <tt>true</tt> if the request is using a secure protocol
* @param cookies SortedMap of <tt>Cookie</tt>s to be matched
@@ -203,7 +202,7 @@ Cookie[] match(String host, int port, String path, boolean secure,
* @return <tt>true</tt> if the cookie should be submitted with a request
* with given attributes, <tt>false</tt> otherwise.
*/
- Cookie[] match(String domain, int port, String path, boolean secure, SortedMap cookiesMap);
+ Cookie[] match(String domain, int port, String path, boolean secure, SortedMap<String, Cookie> cookiesMap);
// END IA/HERITRIX CHANGES
/**
diff --git a/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java b/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java
index 406e8ed34..170ab06f0 100644
--- a/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java
+++ b/commons/src/main/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java
@@ -65,14 +65,13 @@
*
* @since 2.0
*/
-@SuppressWarnings("unchecked") // <- IA/HERITRIX CHANGE
public class CookieSpecBase implements CookieSpec {
/** Log object */
protected static final Log LOG = LogFactory.getLog(CookieSpec.class);
/** Valid date patterns */
- private Collection datepatterns = null;
+ private Collection<String> datepatterns = null;
/** Default constructor */
public CookieSpecBase() {
@@ -346,11 +345,13 @@ public void parseAttribute(
}
- public Collection getValidDateFormats() {
+ @Override
+ public Collection<String> getValidDateFormats() {
return this.datepatterns;
}
- public void setValidDateFormats(final Collection datepatterns) {
+ @Override
+ public void setValidDateFormats(final Collection<String> datepatterns) {
this.datepatterns = datepatterns;
}
@@ -580,7 +581,7 @@ public Cookie[] match(String host, int port, String path,
if (cookies == null) {
return null;
}
- List matching = new LinkedList();
+ List<Cookie> matching = new LinkedList<Cookie>();
for (int i = 0; i < cookies.length; i++) {
if (match(host, port, path, secure, cookies[i])) {
addInPathOrder(matching, cookies[i]);
@@ -606,9 +607,9 @@ public Cookie[] match(String host, int port, String path,
* @param cookies SortedMap of <tt>Cookie</tt>s to be matched
* @return an array of <tt>Cookie</tt>s matching the criterium
*/
-
+ @Override
public Cookie[] match(String host, int port, String path,
- boolean secure, final SortedMap cookies) {
+ boolean secure, final SortedMap<String, Cookie> cookies) {
LOG.trace("enter CookieSpecBase.match("
+ "String, int, String, boolean, SortedMap)");
@@ -616,7 +617,7 @@ public Cookie[] match(String host, int port, String path,
if (cookies == null) {
return null;
}
- List matching = new LinkedList();
+ List<Cookie> matching = new LinkedList<Cookie>();
InternetDomainName domain;
try {
domain = InternetDomainName.fromLenient(host);
@@ -626,7 +627,7 @@ public Cookie[] match(String host, int port, String path,
String candidate = (domain!=null) ? domain.name() : host;
while(candidate!=null) {
- Iterator iter = cookies.subMap(candidate,
+ Iterator<Cookie> iter = cookies.subMap(candidate,
candidate + Cookie.DOMAIN_OVERBOUNDS).values().iterator();
while (iter.hasNext()) {
Cookie cookie = (Cookie) (iter.next());
@@ -656,7 +657,7 @@ public Cookie[] match(String host, int port, String path,
* @param list - the list to add the cookie to
* @param addCookie - the Cookie to add to list
*/
- private static void addInPathOrder(List list, Cookie addCookie) {
+ private static void addInPathOrder(List<Cookie> list, Cookie addCookie) {
int i = 0;
for (i = 0; i < list.size(); i++) {
diff --git a/commons/src/main/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java b/commons/src/main/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java
index 82e1a105b..8da6f6f92 100644
--- a/commons/src/main/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java
+++ b/commons/src/main/java/org/apache/commons/httpclient/cookie/IgnoreCookiesSpec.java
@@ -42,7 +42,6 @@
*
* @since 3.0
*/
-@SuppressWarnings("unchecked") // <- IA/HERITRIX CHANGE
public class IgnoreCookiesSpec implements CookieSpec {
/**
@@ -63,14 +62,16 @@ public Cookie[] parse(String host, int port, String path, boolean secure, String
/**
* @return <code>null</code>
*/
- public Collection getValidDateFormats() {
+ @Override
+ public Collection<String> getValidDateFormats() {
return null;
}
/**
* Does nothing.
*/
- public void setValidDateFormats(Collection datepatterns) {
+ @Override
+ public void setValidDateFormats(Collection<String> datepatterns) {
}
/**
@@ -152,8 +153,9 @@ public boolean pathMatch(final String path, final String topmostPath) {
}
// BEGIN IA/HERITRIX ADDITION
+ @Override
public Cookie[] match(String domain, int port, String path, boolean secure,
- SortedMap cookiesMap) {
+ SortedMap<String, Cookie> cookiesMap) {
return new Cookie[0];
}
// END IA/HERITRIX CHANGE
diff --git a/commons/src/main/java/org/archive/bdb/AutoKryo.java b/commons/src/main/java/org/archive/bdb/AutoKryo.java
index 1306beec8..f12879601 100644
--- a/commons/src/main/java/org/archive/bdb/AutoKryo.java
+++ b/commons/src/main/java/org/archive/bdb/AutoKryo.java
@@ -26,15 +26,15 @@
*/
@SuppressWarnings("unchecked")
public class AutoKryo extends Kryo {
- protected ArrayList<Class> registeredClasses = new ArrayList<Class>();
+ protected ArrayList<Class<?>> registeredClasses = new ArrayList<Class<?>>();
@Override
- protected void handleUnregisteredClass(Class type) {
+ protected void handleUnregisteredClass(@SuppressWarnings("rawtypes") Class type) {
System.err.println("UNREGISTERED FOR KRYO "+type+" in "+registeredClasses.get(0));
super.handleUnregisteredClass(type);
}
- public void autoregister(Class type) {
+ public void autoregister(Class<?> type) {
if (registeredClasses.contains(type)) {
return;
}
@@ -43,7 +43,7 @@ public void autoregister(Class type) {
invokeStatic(
"autoregisterTo",
type,
- new Class[]{ ((Class)AutoKryo.class), },
+ new Class[]{ ((Class<?>)AutoKryo.class), },
new Object[] { this, });
} catch (Exception e) {
register(type);
@@ -88,7 +88,7 @@ public <T> T newInstance(Class<T> type) {
throw ex;
}
- protected Object invokeStatic(String method, Class clazz, Class[] types, Object[] args) throws Exception {
+ protected Object invokeStatic(String method, Class<?> clazz, Class<?>[] types, Object[] args) throws Exception {
return clazz.getMethod(method, types).invoke(null, args);
}
}
diff --git a/commons/src/main/java/org/archive/bdb/KryoBinding.java b/commons/src/main/java/org/archive/bdb/KryoBinding.java
index 70002973a..51e547a7d 100644
--- a/commons/src/main/java/org/archive/bdb/KryoBinding.java
+++ b/commons/src/main/java/org/archive/bdb/KryoBinding.java
@@ -51,8 +51,7 @@ protected WeakReference<ObjectBuffer> initialValue() {
* @param baseClass is the base class for serialized objects stored using
* this binding
*/
- @SuppressWarnings("unchecked")
- public KryoBinding(Class baseClass) {
+ public KryoBinding(Class<K> baseClass) {
this.baseClass = baseClass;
kryo.autoregister(baseClass);
// TODO: reevaluate if explicit registration should be required
diff --git a/commons/src/main/java/org/archive/io/Arc2Warc.java b/commons/src/main/java/org/archive/io/Arc2Warc.java
index 5cd99c959..eedd848f3 100644
--- a/commons/src/main/java/org/archive/io/Arc2Warc.java
+++ b/commons/src/main/java/org/archive/io/Arc2Warc.java
@@ -199,7 +199,7 @@ public static void main(String [] args)
"Force overwrite of target file."));
PosixParser parser = new PosixParser();
CommandLine cmdline = parser.parse(options, args, false);
- List cmdlineArgs = cmdline.getArgList();
+ List<String> cmdlineArgs = cmdline.getArgList();
Option [] cmdlineOptions = cmdline.getOptions();
HelpFormatter formatter = new HelpFormatter();
@@ -230,7 +230,7 @@ public static void main(String [] args)
if (cmdlineArgs.size() != 2) {
usage(formatter, options, 0);
}
- (new Arc2Warc()).transform(new File(cmdlineArgs.get(0).toString()),
- new File(cmdlineArgs.get(1).toString()), force);
+ (new Arc2Warc()).transform(new File(cmdlineArgs.get(0)),
+ new File(cmdlineArgs.get(1)), force);
}
}
diff --git a/commons/src/main/java/org/archive/io/Warc2Arc.java b/commons/src/main/java/org/archive/io/Warc2Arc.java
index eb611ceaa..3cd1142f7 100644
--- a/commons/src/main/java/org/archive/io/Warc2Arc.java
+++ b/commons/src/main/java/org/archive/io/Warc2Arc.java
@@ -173,7 +173,6 @@ protected boolean isARCType(final String mimetype) {
* @throws IOException
* @throws java.text.ParseException
*/
- @SuppressWarnings("unchecked")
public static void main(String [] args)
throws ParseException, IOException, java.text.ParseException {
Options options = new Options();
@@ -187,7 +186,8 @@ public static void main(String [] args)
"Suffix to use on created ARC files, else uses default."));
PosixParser parser = new PosixParser();
CommandLine cmdline = parser.parse(options, args, false);
- List cmdlineArgs = cmdline.getArgList();
+ @SuppressWarnings("unchecked")
+ List<String> cmdlineArgs = cmdline.getArgList();
Option [] cmdlineOptions = cmdline.getOptions();
HelpFormatter formatter = new HelpFormatter();
diff --git a/commons/src/main/java/org/archive/io/arc/ARCReader.java b/commons/src/main/java/org/archive/io/arc/ARCReader.java
index fcb6c15ba..7f85cc2a8 100644
--- a/commons/src/main/java/org/archive/io/arc/ARCReader.java
+++ b/commons/src/main/java/org/archive/io/arc/ARCReader.java
@@ -453,7 +453,7 @@ public static void main(String [] args)
options.addOption(new Option("p","parse", false, "Parse headers."));
PosixParser parser = new PosixParser();
CommandLine cmdline = parser.parse(options, args, false);
- List cmdlineArgs = cmdline.getArgList();
+ List<String> cmdlineArgs = cmdline.getArgList();
Option [] cmdlineOptions = cmdline.getOptions();
HelpFormatter formatter = new HelpFormatter();
@@ -529,8 +529,7 @@ public static void main(String [] args)
arc.setParseHttpHeaders(parse);
outputRecord(arc, format);
} else {
- for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) {
- String urlOrPath = (String)i.next();
+ for (String urlOrPath : cmdlineArgs) {
try {
ARCReader r = ARCReaderFactory.get(urlOrPath);
r.setStrict(strict);
diff --git a/commons/src/main/java/org/archive/io/warc/WARCReader.java b/commons/src/main/java/org/archive/io/warc/WARCReader.java
index 3794a23d8..98a7e0248 100644
--- a/commons/src/main/java/org/archive/io/warc/WARCReader.java
+++ b/commons/src/main/java/org/archive/io/warc/WARCReader.java
@@ -192,13 +192,13 @@ public static void createCDXIndexFile(String urlOrPath)
* @throws IOException
* @throws java.text.ParseException
*/
- @SuppressWarnings("unchecked")
public static void main(String [] args)
throws ParseException, IOException, java.text.ParseException {
Options options = getOptions();
PosixParser parser = new PosixParser();
CommandLine cmdline = parser.parse(options, args, false);
- List cmdlineArgs = cmdline.getArgList();
+ @SuppressWarnings("unchecked")
+ List<String> cmdlineArgs = cmdline.getArgList();
Option [] cmdlineOptions = cmdline.getOptions();
HelpFormatter formatter = new HelpFormatter();
@@ -264,7 +264,7 @@ public static void main(String [] args)
r.setStrict(strict);
outputRecord(r, format);
} else {
- for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) {
+ for (Iterator<String> i = cmdlineArgs.iterator(); i.hasNext();) {
String urlOrPath = (String)i.next();
try {
WARCReader r = WARCReaderFactory.get(urlOrPath);
diff --git a/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java b/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java
index 7e5301410..11c5faf7f 100644
--- a/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java
+++ b/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java
@@ -63,8 +63,7 @@ public BeanFieldsPatternValidator(Class<?> clazz, String ... fieldsPatterns) {
}
}
- @SuppressWarnings("unchecked")
- public boolean supports(Class cls) {
+ public boolean supports(Class<?> cls) {
return this.clazz.isAssignableFrom(cls);
}
diff --git a/commons/src/main/java/org/archive/spring/ConfigFileEditor.java b/commons/src/main/java/org/archive/spring/ConfigFileEditor.java
index 7bb897bab..c55daa792 100644
--- a/commons/src/main/java/org/archive/spring/ConfigFileEditor.java
+++ b/commons/src/main/java/org/archive/spring/ConfigFileEditor.java
@@ -23,8 +23,9 @@
* PropertyEditor allowing Strings to become ConfigFile instances.
*
*/
-public class ConfigFileEditor<T> extends ConfigPathEditor {
+public class ConfigFileEditor extends ConfigPathEditor {
+ @Override
public Object getValue() {
ConfigFile c = new ConfigFile(null,value.toString());
return c;
diff --git a/commons/src/main/java/org/archive/spring/ConfigPathEditor.java b/commons/src/main/java/org/archive/spring/ConfigPathEditor.java
index 03b63ca1a..531b3adce 100644
--- a/commons/src/main/java/org/archive/spring/ConfigPathEditor.java
+++ b/commons/src/main/java/org/archive/spring/ConfigPathEditor.java
@@ -29,63 +29,75 @@
* PropertyEditor allowing Strings to become ConfigPath instances.
*
*/
-public class ConfigPathEditor<T> implements PropertyEditor {
+public class ConfigPathEditor implements PropertyEditor {
protected Object value;
+ @Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
// TODO Auto-generated method stub
}
+ @Override
public String getAsText() {
// TODO Auto-generated method stub
return null;
}
+ @Override
public Component getCustomEditor() {
// TODO Auto-generated method stub
return null;
}
+ @Override
public String getJavaInitializationString() {
// TODO Auto-generated method stub
return null;
}
+ @Override
public String[] getTags() {
// TODO Auto-generated method stub
return null;
}
+ @Override
public Object getValue() {
ConfigPath c = new ConfigPath(null,value.toString());
//c.put(value);
return c;
}
+ @Override
public boolean isPaintable() {
// TODO Auto-generated method stub
return false;
}
+ @Override
public void paintValue(Graphics gfx, Rectangle box) {
// TODO Auto-generated method stub
}
+ @Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
// TODO Auto-generated method stub
}
+ @Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(text);
}
+ @Override
public void setValue(Object value) {
this.value = value;
}
+ @Override
public boolean supportsCustomEditor() {
// TODO Auto-generated method stub
return false;
diff --git a/commons/src/main/java/org/archive/util/ArchiveUtils.java b/commons/src/main/java/org/archive/util/ArchiveUtils.java
index 614cae76b..fce854d1f 100644
--- a/commons/src/main/java/org/archive/util/ArchiveUtils.java
+++ b/commons/src/main/java/org/archive/util/ArchiveUtils.java
@@ -749,13 +749,12 @@ public static String shortReportLine(Reporter rep) {
* @param obj Object to prettify
* @return prettified String
*/
- @SuppressWarnings("unchecked")
public static String prettyString(Object obj) {
// these things have to checked and casted unfortunately
if (obj instanceof Object[]) {
return prettyString((Object[]) obj);
} else if (obj instanceof Map) {
- return prettyString((Map) obj);
+ return prettyString((Map<?, ?>) obj);
} else {
return "<"+obj+">";
}
@@ -767,8 +766,7 @@ public static String prettyString(Object obj) {
* @param Map
* @return prettified (in curly brackets) string of Map contents
*/
- @SuppressWarnings("unchecked")
- public static String prettyString(Map map) {
+ public static String prettyString(Map<?, ?> map) {
StringBuilder builder = new StringBuilder();
builder.append("{ ");
boolean needsComma = false;
diff --git a/commons/src/main/java/org/archive/util/ObjectIdentityBdbCache.java b/commons/src/main/java/org/archive/util/ObjectIdentityBdbCache.java
index 0a6d1099d..a4fc257fc 100644
--- a/commons/src/main/java/org/archive/util/ObjectIdentityBdbCache.java
+++ b/commons/src/main/java/org/archive/util/ObjectIdentityBdbCache.java
@@ -151,7 +151,6 @@ public ObjectIdentityBdbCache() {
* @param classCatalog
* @throws DatabaseException
*/
- @SuppressWarnings("unchecked")
public void initialize(final Environment env, String dbName,
final Class valueClass, final StoredClassCatalog classCatalog)
throws DatabaseException {
@@ -523,10 +522,9 @@ final public V doctoredGet() {
private static class SoftEntry<V> extends SoftReference<V> {
PhantomEntry<V> phantom;
- @SuppressWarnings("unchecked")
public SoftEntry(String key, V referent, ReferenceQueue<V> q) {
super(referent, q);
- this.phantom = new PhantomEntry(key, referent); // unchecked cast
+ this.phantom = new PhantomEntry<V>(key, referent);
}
public V get() {
diff --git a/commons/src/main/java/org/archive/util/ObjectIdentityBdbManualCache.java b/commons/src/main/java/org/archive/util/ObjectIdentityBdbManualCache.java
index 70cd213c9..84504e79d 100644
--- a/commons/src/main/java/org/archive/util/ObjectIdentityBdbManualCache.java
+++ b/commons/src/main/java/org/archive/util/ObjectIdentityBdbManualCache.java
@@ -124,7 +124,6 @@ public ObjectIdentityBdbManualCache() {
* @param classCatalog
* @throws DatabaseException
*/
- @SuppressWarnings("unchecked")
public void initialize(final Environment env, String dbName,
final Class valueClass, final StoredClassCatalog classCatalog)
throws DatabaseException {
diff --git a/commons/src/main/java/org/archive/util/PrefixFinder.java b/commons/src/main/java/org/archive/util/PrefixFinder.java
index 098a8b5b7..9d22b4c1f 100644
--- a/commons/src/main/java/org/archive/util/PrefixFinder.java
+++ b/commons/src/main/java/org/archive/util/PrefixFinder.java
@@ -76,18 +76,17 @@ public static List<String> find(SortedSet<String> set, String input) {
}
- @SuppressWarnings("unchecked")
protected static SortedSet<String> headSetInclusive(SortedSet<String> set, String input) {
// use NavigableSet inclusive version if available
if(set instanceof NavigableSet) {
- return ((NavigableSet)set).headSet(input, true);
+ return ((NavigableSet<String>)set).headSet(input, true);
}
// use Stored*Set inclusive version if available
if(set instanceof StoredSortedKeySet) {
- return ((StoredSortedKeySet)set).headSet(input, true);
+ return ((StoredSortedKeySet<String>)set).headSet(input, true);
}
if(set instanceof StoredSortedValueSet) {
- return ((StoredSortedValueSet)set).headSet(input, true);
+ return ((StoredSortedValueSet<String>)set).headSet(input, true);
}
// Use synthetic "one above" trick
// NOTE: because '\0' sorts in the middle in "java modified UTF-8",
@@ -125,15 +124,14 @@ public static List<String> findKeys(SortedMap<String,?> map, String input) {
}
- @SuppressWarnings("unchecked")
private static SortedMap<String, ?> headMapInclusive(SortedMap<String, ?> map, String input) {
// use NavigableMap inclusive version if available
if(map instanceof NavigableMap) {
- return ((NavigableMap)map).headMap(input, true);
+ return ((NavigableMap<String, ?>)map).headMap(input, true);
}
// use StoredSortedMap inclusive version if available
if(map instanceof StoredSortedMap) {
- return ((StoredSortedMap)map).headMap(input, true);
+ return ((StoredSortedMap<String, ?>)map).headMap(input, true);
}
// Use synthetic "one above" trick
// NOTE: because '\0' sorts in the middle in "java modified UTF-8",
diff --git a/commons/src/main/java/st/ata/util/FPGenerator.java b/commons/src/main/java/st/ata/util/FPGenerator.java
index e742e4c38..20a8702d3 100644
--- a/commons/src/main/java/st/ata/util/FPGenerator.java
+++ b/commons/src/main/java/st/ata/util/FPGenerator.java
@@ -42,9 +42,7 @@
and use <code>reduce</code> to reduce to a fingerprint after the loop.
*/
-
// Tested by: TestFPGenerator
-@SuppressWarnings("unchecked")
public final class FPGenerator {
/** Return a fingerprint generator. The fingerprints generated
@@ -64,7 +62,7 @@ public static FPGenerator make(long polynomial, int degree) {
}
return fpgen;
}
- private static final Hashtable generators = new Hashtable(10);
+ private static final Hashtable<Long, FPGenerator> generators = new Hashtable<Long, FPGenerator>(10);
private static final long zero = 0;
private static final long one = 0x8000000000000000L;
diff --git a/commons/src/test/java/org/archive/settings/file/PrefixFinderTest.java b/commons/src/test/java/org/archive/settings/file/PrefixFinderTest.java
index e8563b695..035149fb6 100644
--- a/commons/src/test/java/org/archive/settings/file/PrefixFinderTest.java
+++ b/commons/src/test/java/org/archive/settings/file/PrefixFinderTest.java
@@ -74,7 +74,6 @@ public void testSortedMap() {
testUrlsNoMatch(map);
}
- @SuppressWarnings("unchecked")
public void testStoredSortedMap() throws Exception {
EnvironmentConfig config = new EnvironmentConfig();
config.setAllowCreate(true);
@@ -89,7 +88,7 @@ public void testStoredSortedMap() throws Exception {
dbConfig.setDeferredWrite(true);
Database db = bdbEnvironment.openDatabase(null, "test", dbConfig);
- StoredSortedMap ssm = new StoredSortedMap(db, new StringBinding(), new StringBinding(), true);
+ StoredSortedMap<String, String> ssm = new StoredSortedMap<String, String>(db, new StringBinding(), new StringBinding(), true);
testUrlsNoMatch(ssm);
db.close();
bdbEnvironment.close();
diff --git a/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java b/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java
index 765b7bb55..7c258d39b 100644
--- a/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java
+++ b/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java
@@ -25,8 +25,7 @@
public class CheckpointValidator implements Validator {
@Override
- @SuppressWarnings("unchecked")
- public boolean supports(Class cls) {
+ public boolean supports(Class<?> cls) {
return Checkpoint.class.isAssignableFrom(cls);
}
diff --git a/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java b/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java
index 0c8901452..fc6f249b1 100644
--- a/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java
+++ b/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java
@@ -33,7 +33,7 @@
*
* @contributor gojomo
*/
-public class CrawlLimitEnforcer implements ApplicationListener {
+public class CrawlLimitEnforcer implements ApplicationListener<ApplicationEvent> {
/**
* Maximum number of bytes to download. Once this number is exceeded
@@ -80,6 +80,7 @@ public void setCrawlController(CrawlController controller) {
this.controller = controller;
}
+ @Override
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof StatSnapshotEvent) {
CrawlStatSnapshot snapshot = ((StatSnapshotEvent)event).getSnapshot();
diff --git a/engine/src/main/java/org/archive/crawler/frontier/AbstractFrontier.java b/engine/src/main/java/org/archive/crawler/frontier/AbstractFrontier.java
index c9df326ed..3b1cba657 100644
--- a/engine/src/main/java/org/archive/crawler/frontier/AbstractFrontier.java
+++ b/engine/src/main/java/org/archive/crawler/frontier/AbstractFrontier.java
@@ -88,7 +88,7 @@ public abstract class AbstractFrontier
HasKeyedProperties,
ExtractorParameters,
CrawlUriReceiver,
- ApplicationListener {
+ ApplicationListener<ApplicationEvent> {
private static final long serialVersionUID = 555881755284996860L;
private static final Logger logger = Logger
.getLogger(AbstractFrontier.class.getName());
@@ -1130,6 +1130,7 @@ public String shortReportLine() {
return ArchiveUtils.shortReportLine(this);
}
+ @Override
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof CrawlStateEvent) {
CrawlStateEvent event1 = (CrawlStateEvent)event;
diff --git a/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java b/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java
index 7031b99e9..b54ea9ed7 100644
--- a/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java
+++ b/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java
@@ -96,7 +96,6 @@ public static void main(String[] args) throws DatabaseException, IOException {
* @throws UnsupportedEncodingException
* @throws IOException
*/
- @SuppressWarnings("unchecked")
private static void main2args(String[] args) throws DatabaseException,
FileNotFoundException, UnsupportedEncodingException, IOException {
File source = new File(args[0]);
@@ -110,16 +109,16 @@ private static void main2args(String[] args) throws DatabaseException,
null,
PersistProcessor.URI_HISTORY_DBNAME,
PersistProcessor.HISTORY_DB_CONFIG.toDatabaseConfig());
- StoredSortedMap historyMap = new StoredSortedMap(historyDB,
- new StringBinding(), new SerialBinding(classCatalog,
- Map.class), true);
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ StoredSortedMap<String, Object> historyMap = new StoredSortedMap<String, Object>(historyDB,
+ new StringBinding(), new SerialBinding(classCatalog, Map.class), true);
int count = 0;
if(source.isFile()) {
// scan log, writing to database
BufferedReader br = ArchiveUtils.getBufferedReader(source);
- Iterator iter = new LineReadingIterator(br);
+ Iterator<String> iter = new LineReadingIterator(br);
while(iter.hasNext()) {
String line = (String) iter.next();
String[] splits = line.split("\\s");
@@ -130,9 +129,10 @@ private static void main2args(String[] args) throws DatabaseException,
}
String key = PersistProcessor.persistKeyFor(uri);
int precedence = Integer.parseInt(splits[1]);
- Map<String,Object> map = (Map<String,Object>)historyMap.get(key);
+ @SuppressWarnings("unchecked")
+ Map<String, Object> map = (Map<String, Object>)historyMap.get(key);
if (map==null) {
- map = new HashMap<String,Object>();
+ map = new HashMap<String, Object>();
}
map.put(A_PRECALC_PRECEDENCE, precedence);
historyMap.put(key,map);
diff --git a/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java b/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java
index f4362eada..3dc107678 100644
--- a/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java
+++ b/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java
@@ -66,29 +66,27 @@ public void setBdbModule(BdbModule bdb) {
this.bdb = bdb;
}
- @SuppressWarnings("unchecked")
- protected StoredSortedMap store;
+ protected StoredSortedMap<String, ?> store;
protected Database historyDb;
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({ "unchecked", "rawtypes" })
public void start() {
if(isRunning()) {
return;
- }
+ }
+ store = null;
String dbName = PersistProcessor.URI_HISTORY_DBNAME;
- StoredSortedMap historyMap;
try {
StoredClassCatalog classCatalog = bdb.getClassCatalog();
BdbModule.BdbConfig dbConfig = PersistProcessor.HISTORY_DB_CONFIG;
- historyDb = bdb.openDatabase(dbName, dbConfig, true);
- historyMap = new StoredSortedMap(historyDb,
- new StringBinding(), new SerialBinding(classCatalog,
- Map.class), true);
+ historyDb = bdb.openDatabase(dbName, dbConfig, true);
+ SerialBinding sb = new SerialBinding(classCatalog, Map.class);
+ StoredSortedMap historyMap = new StoredSortedMap(historyDb, new StringBinding(), sb, true);
+ store = historyMap;
} catch (DatabaseException e) {
throw new RuntimeException(e);
}
- store = historyMap;
}
public boolean isRunning() {
@@ -141,11 +139,10 @@ protected int calculatePrecedence(CrawlURI curi) {
* double-loading
* @param curi CrawlURI to receive prior state data
*/
- @SuppressWarnings("unchecked")
protected void mergePrior(CrawlURI curi) {
- Map<String, Map> prior = null;
String key = PersistProcessor.persistKeyFor(curi);
- prior = (Map<String,Map>) store.get(key);
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ Map<String,Map> prior = (Map<String, Map>) store.get(key);
if(prior!=null) {
// merge in keys
curi.getData().putAll(prior);
diff --git a/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java b/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java
index 7afa3e129..ec13f78d5 100644
--- a/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java
+++ b/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java
@@ -31,7 +31,7 @@
*
* @contributor Kristinn Sigurðsson
*/
-public class DiskSpaceMonitor implements ApplicationListener {
+public class DiskSpaceMonitor implements ApplicationListener<ApplicationEvent> {
private static final Logger logger = Logger.getLogger(DiskSpaceMonitor.class.getName());
protected List<String> monitorPaths = new ArrayList<String>();
diff --git a/engine/src/main/java/org/archive/crawler/restlet/JobRelatedResource.java b/engine/src/main/java/org/archive/crawler/restlet/JobRelatedResource.java
index aa1bab8c2..c5d9efcc8 100644
--- a/engine/src/main/java/org/archive/crawler/restlet/JobRelatedResource.java
+++ b/engine/src/main/java/org/archive/crawler/restlet/JobRelatedResource.java
@@ -23,7 +23,6 @@
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.PrintWriter;
-import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
@@ -177,7 +176,7 @@ protected void writeNestedNames(PrintWriter pw, Object obj, String prefix, Set<O
}
}
if(obj instanceof Iterable) {
- for (Object next : (Iterable)obj) {
+ for (Object next : (Iterable<Object>)obj) {
writeNestedNames(pw, next, prefix, alreadyWritten);
}
}
@@ -411,7 +410,6 @@ private IdentityHashMap<Object, String> getBeanToNameMap() {
* @param alreadyWritten Set of objects to not redundantly write
* @param beanPathPrefix beanPath prefix to apply to sub fields browse links
*/
- @SuppressWarnings("unchecked")
protected void writeObject(PrintWriter pw, String field, Object object, HashSet<Object> alreadyWritten, String beanPathPrefix) {
String key = getBeanToNameMap().get(object);
String close = "";
@@ -497,14 +495,15 @@ protected void writeObject(PrintWriter pw, String field, Object object, HashSet<
writeObject(pw, i+"", list.get(i), alreadyWritten, beanPathPrefix);
}
} else if(object instanceof Iterable) {
- for (Object next : (Iterable)object) {
+ @SuppressWarnings("unchecked")
+ Iterable<Object> itbl = (Iterable<Object>)object;
+ for (Object next : itbl) {
writeObject(pw, "#", next, alreadyWritten, null);
}
}
if(object instanceof Map) {
- for (Object next : ((Map)object).entrySet()) {
+ for (Map.Entry<?, ?> entry : ((Map<?, ?>)object).entrySet()) {
// TODO: protect against giant maps?
- Map.Entry<?, ?> entry = (Map.Entry<?, ?>)next;
if(beanPath!=null) {
beanPathPrefix = beanPath+"[";
}
diff --git a/engine/src/main/java/org/archive/crawler/spring/SheetOverlaysManager.java b/engine/src/main/java/org/archive/crawler/spring/SheetOverlaysManager.java
index 80775e19a..c25bfaeb7 100644
--- a/engine/src/main/java/org/archive/crawler/spring/SheetOverlaysManager.java
+++ b/engine/src/main/java/org/archive/crawler/spring/SheetOverlaysManager.java
@@ -53,7 +53,7 @@
* @contributor gojomo
*/
public class SheetOverlaysManager implements
-BeanFactoryAware, OverlayMapsSource, ApplicationListener {
+BeanFactoryAware, OverlayMapsSource, ApplicationListener<ApplicationEvent> {
private static final Logger logger = Logger.getLogger(SheetOverlaysManager.class.getName());
@@ -186,6 +186,7 @@ public Map<String, Object> getOverlayMap(String name) {
* properties.
* @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
*/
+ @Override
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof ContextRefreshedEvent) {
for(Sheet s: sheetsByName.values()) {
diff --git a/modules/src/main/java/org/archive/modules/CrawlURI.java b/modules/src/main/java/org/archive/modules/CrawlURI.java
index cfc01bf49..c923195cb 100644
--- a/modules/src/main/java/org/archive/modules/CrawlURI.java
+++ b/modules/src/main/java/org/archive/modules/CrawlURI.java
@@ -891,7 +891,7 @@ public Map<String,Object> getPersistentDataMap() {
*/
public Set<Credential> getCredentials() {
@SuppressWarnings("unchecked")
- Set<Credential> r = (Set)getData().get(A_CREDENTIALS_KEY);
+ Set<Credential> r = (Set<Credential>)getData().get(A_CREDENTIALS_KEY);
if (r == null) {
r = new HashSet<Credential>();
getData().put(A_CREDENTIALS_KEY, r);
@@ -1250,7 +1250,7 @@ public FetchType getFetchType() {
public Collection<Throwable> getNonFatalFailures() {
@SuppressWarnings("unchecked")
- List<Throwable> list = (List)getData().get(A_NONFATAL_ERRORS);
+ List<Throwable> list = (List<Throwable>)getData().get(A_NONFATAL_ERRORS);
if (list == null) {
list = new ArrayList<Throwable>();
getData().put(A_NONFATAL_ERRORS, list);
@@ -1505,7 +1505,7 @@ public void makeHeritable(String key) {
*/
public void makeNonHeritable(String key) {
@SuppressWarnings("unchecked")
- HashSet heritableKeys = (HashSet)data.get(A_HERITABLE_KEYS);
+ HashSet<String> heritableKeys = (HashSet<String>)data.get(A_HERITABLE_KEYS);
if(heritableKeys == null) {
return;
}
diff --git a/modules/src/main/java/org/archive/modules/canonicalize/StripSessionCFIDs.java b/modules/src/main/java/org/archive/modules/canonicalize/StripSessionCFIDs.java
index 529e8a62b..c3332dc3d 100644
--- a/modules/src/main/java/org/archive/modules/canonicalize/StripSessionCFIDs.java
+++ b/modules/src/main/java/org/archive/modules/canonicalize/StripSessionCFIDs.java
@@ -18,7 +18,6 @@
*/
package org.archive.modules.canonicalize;
-import java.util.regex.Pattern;
/**
* Strip cold fusion session ids.
diff --git a/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java b/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java
index ec3ad1193..692759993 100644
--- a/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java
+++ b/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java
@@ -18,8 +18,6 @@
*/
package org.archive.modules.canonicalize;
-import java.util.regex.Pattern;
-
/**
* Strip known session ids.
* @author stack
diff --git a/modules/src/main/java/org/archive/modules/extractor/CustomSWFTags.java b/modules/src/main/java/org/archive/modules/extractor/CustomSWFTags.java
index b0f61ada5..987a23edc 100644
--- a/modules/src/main/java/org/archive/modules/extractor/CustomSWFTags.java
+++ b/modules/src/main/java/org/archive/modules/extractor/CustomSWFTags.java
@@ -34,7 +34,6 @@
*
* @author Igor Ranitovic
*/
-@SuppressWarnings("unchecked")
public class CustomSWFTags extends SWFTagTypesImpl {
protected SWFActions actions;
@@ -43,18 +42,21 @@ public CustomSWFTags(SWFActions a) {
actions = a;
}
- public SWFActions tagDefineButton(int id, Vector buttonRecords)
+ @Override
+ public SWFActions tagDefineButton(int id, @SuppressWarnings("rawtypes") Vector buttonRecords)
throws IOException {
return actions;
}
+ @Override
public SWFActions tagDefineButton2(int id, boolean trackAsMenu,
- Vector buttonRecord2s) throws IOException {
+ @SuppressWarnings("rawtypes") Vector buttonRecord2s) throws IOException {
return actions;
}
+ @Override
public SWFActions tagDoAction() throws IOException {
return actions;
}
@@ -63,10 +65,12 @@ public SWFActions tagDoInActions(int spriteId) throws IOException {
return actions;
}
+ @Override
public SWFTagTypes tagDefineSprite(int id) throws IOException {
return this;
}
+ @Override
public SWFActions tagPlaceObject2(boolean isMove, int clipDepth,
int depth, int charId, Matrix matrix, AlphaTransform cxform,
int ratio, String name, int clipActionFlags) throws IOException {
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java
index 994b0a1d6..133b152e7 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java
@@ -58,7 +58,6 @@ public class ExtractorJS extends ContentExtractor {
private static final long serialVersionUID = 2L;
- @SuppressWarnings("unused")
private static Logger LOGGER =
Logger.getLogger("org.archive.crawler.extractor.ExtractorJS");
diff --git a/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java b/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java
index 3fcbed636..5b782da32 100644
--- a/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java
+++ b/modules/src/main/java/org/archive/modules/extractor/JerichoExtractorHTML.java
@@ -49,7 +49,6 @@
import au.id.jericho.lib.html.FormControl;
import au.id.jericho.lib.html.FormControlType;
import au.id.jericho.lib.html.FormField;
-import au.id.jericho.lib.html.FormFields;
import au.id.jericho.lib.html.HTMLElementName;
import au.id.jericho.lib.html.Source;
import au.id.jericho.lib.html.StartTagType;
@@ -94,7 +93,7 @@ public JerichoExtractorHTML(String name) {
"parser, the Jericho HTML Parser, reads the whole " +
"document into memory for " +
"parsing - thus this extractor has an inherent OOME risk. " +
- "This OOME risk can be reduced/eleminated by limiting the " +
+ "This OOME risk can be reduced/eliminated by limiting the " +
"size of documents to be parsed (i.e. using " +
"NotExceedsDocumentLengthTresholdDecideRule). ");
}*/
@@ -105,8 +104,7 @@ public JerichoExtractorHTML() {
private static List<Attribute> findOnAttributes(Attributes attributes) {
List<Attribute> result = new LinkedList<Attribute>();
- for (Iterator attrIter = attributes.iterator(); attrIter.hasNext();) {
- Attribute attr = (Attribute) attrIter.next();
+ for (Attribute attr : (Iterable<Attribute>)attributes) {
if (attr.getKey().startsWith("on"))
result.add(attr);
}
@@ -118,7 +116,7 @@ protected void processGeneralTag(CrawlURI curi, Element element,
Attributes attributes) {
Attribute attr;
String attrValue;
- List attrList;
+ List<Attribute> attrList;
String elementName = element.getName();
// Just in case it's an OBJECT or APPLET tag
@@ -163,7 +161,7 @@ protected void processGeneralTag(CrawlURI curi, Element element,
}
// ON_
if ((attrList = findOnAttributes(attributes)).size() != 0) {
- for (Iterator attrIter = attrList.iterator(); attrIter.hasNext();) {
+ for (Iterator<Attribute> attrIter = attrList.iterator(); attrIter.hasNext();) {
attr = (Attribute) attrIter.next();
CharSequence valueSegment = attr.getValueSegment();
if (valueSegment != null)
@@ -370,21 +368,14 @@ protected void processForm(CrawlURI curi, Element element) {
numberOfFormsProcessed.incrementAndGet();
// get all form fields
- FormFields formFields = element.findFormFields();
- for (Iterator fieldsIter = formFields.iterator(); fieldsIter.hasNext();) {
- // for each form field
- FormField formField = (FormField) fieldsIter.next();
-
+ for (FormField formField : (Iterable<FormField>)element.findFormFields()) {
// for each form control
- for (Iterator controlIter = formField.getFormControls().iterator();
- controlIter.hasNext();) {
- FormControl formControl = (FormControl) controlIter.next();
-
+ for (FormControl formControl : (Iterable<FormControl>)formField.getFormControls()) {
// get name of control element (and URLEncode it)
String controlName = formControl.getName();
// retrieve list of values - submit needs special handling
- Collection controlValues;
+ Collection<String> controlValues;
if (!(formControl.getFormControlType() ==
FormControlType.SUBMIT)) {
controlValues = formControl.getValues();
@@ -394,9 +385,7 @@ protected void processForm(CrawlURI curi, Element element) {
if (controlValues.size() > 0) {
// for each value set
- for (Iterator valueIter = controlValues.iterator();
- valueIter.hasNext();) {
- String value = (String) valueIter.next();
+ for (String value : controlValues) {
queryURL += "&" + controlName + "=" + value;
}
} else {
@@ -430,10 +419,8 @@ protected void processForm(CrawlURI curi, Element element) {
*/
protected void extract(CrawlURI curi, CharSequence cs) {
Source source = new Source(cs);
- List elements = source.findAllElements(StartTagType.NORMAL);
- for (Iterator elementIter = elements.iterator();
- elementIter.hasNext();) {
- Element element = (Element) elementIter.next();
+ List<Element> elements = source.findAllElements(StartTagType.NORMAL);
+ for (Element element : elements) {
String elementName = element.getName();
Attributes attributes;
if (elementName.equals(HTMLElementName.META)) {
diff --git a/modules/src/main/java/org/archive/modules/extractor/PDFParser.java b/modules/src/main/java/org/archive/modules/extractor/PDFParser.java
index 9a44d59b8..8aa07cde0 100644
--- a/modules/src/main/java/org/archive/modules/extractor/PDFParser.java
+++ b/modules/src/main/java/org/archive/modules/extractor/PDFParser.java
@@ -199,7 +199,6 @@ protected void extractURIs(PdfObject entity){
PdfDictionary dictionary= (PdfDictionary)entity;
- @SuppressWarnings("unchecked")
Set<PdfName> allkeys = dictionary.getKeys();
for (PdfName key: allkeys) {
PdfObject value = dictionary.get(key);
@@ -219,11 +218,8 @@ protected void extractURIs(PdfObject entity){
}else if(entity.isArray()){
PdfArray array = (PdfArray)entity;
- ArrayList arrayObjects = array.getArrayList();
- Iterator objectList = arrayObjects.iterator();
-
- while(objectList.hasNext()){
- this.extractURIs( (PdfObject)objectList.next());
+ for (PdfObject pdfObject : (Iterable<PdfObject>)array.getArrayList()) {
+ this.extractURIs(pdfObject);
}
// deal with indirect references
diff --git a/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java b/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java
index c339b0f44..a92fe1ea9 100644
--- a/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java
+++ b/modules/src/main/java/org/archive/modules/fetcher/FetchHTTP.java
@@ -743,14 +743,14 @@ protected void readResponseBody(HttpState state,
* @param curi CrawlURI
* @param rec HttpRecorder
*/
- @SuppressWarnings("unchecked")
protected void setSizes(CrawlURI curi, Recorder rec) {
// set reporting size
curi.setContentSize(rec.getRecordedInput().getSize());
// special handling for 304-not modified
if (curi.getFetchStatus() == HttpStatus.SC_NOT_MODIFIED
&& curi.containsDataKey(A_FETCH_HISTORY)) {
- Map history[] = (Map[])curi.getData().get(A_FETCH_HISTORY);
+ @SuppressWarnings("unchecked")
+ Map<String, ?> history[] = (Map[])curi.getData().get(A_FETCH_HISTORY);
if (history[0] != null
&& history[0]
.containsKey(A_REFERENCE_LENGTH)) {
@@ -1024,12 +1024,12 @@ protected HostConfiguration configureMethod(CrawlURI curi,
* @param sourceHeader header to consult in URI history
* @param targetHeader header to set if possible
*/
- @SuppressWarnings("unchecked")
protected void setConditionalGetHeader(CrawlURI curi, HttpMethod method,
boolean conditional, String sourceHeader, String targetHeader) {
if (conditional) {
try {
- Map[] history = (Map[])curi.getData().get(A_FETCH_HISTORY);
+ @SuppressWarnings("unchecked")
+ Map<String, ?>[] history = (Map[])curi.getData().get(A_FETCH_HISTORY);
int previousStatus = (Integer) history[0].get(A_STATUS);
if(previousStatus<=0) {
// do not reuse headers from any broken fetch
@@ -1261,7 +1261,6 @@ protected void handle401(final HttpMethod method, final CrawlURI curi) {
* CrawlURI that got a 401.
* @return Returns first wholesome authscheme found else null.
*/
- @SuppressWarnings("unchecked")
protected AuthScheme getAuthScheme(final HttpMethod method,
final CrawlURI curi) {
Header[] headers = method.getResponseHeaders("WWW-Authenticate");
@@ -1271,9 +1270,11 @@ protected AuthScheme getAuthScheme(final HttpMethod method,
return null;
}
- Map authschemes = null;
+ Map<String, String> authschemes = null;
try {
- authschemes = AuthChallengeParser.parseChallenges(headers);
+ @SuppressWarnings("unchecked")
+ Map<String, String> parsedChallenges = AuthChallengeParser.parseChallenges(headers);
+ authschemes = parsedChallenges;
} catch (MalformedChallengeException e) {
logger.fine("Failed challenge parse: " + e.getMessage());
}
@@ -1285,7 +1286,7 @@ protected AuthScheme getAuthScheme(final HttpMethod method,
AuthScheme result = null;
// Use the first auth found.
- for (Iterator i = authschemes.keySet().iterator(); result == null
+ for (Iterator<String> i = authschemes.keySet().iterator(); result == null
&& i.hasNext();) {
String key = (String) i.next();
String challenge = (String) authschemes.get(key);
@@ -1377,7 +1378,6 @@ public void stop() {
super.stop();
// At the end save cookies to the file specified in the order file.
if (cookieStorage != null) {
- @SuppressWarnings("unchecked")
Map<String, Cookie> map = http.getState().getCookiesMap();
cookieStorage.saveCookiesMap(map);
cookieStorage.stop();
diff --git a/modules/src/main/java/org/archive/modules/recrawl/FetchHistoryProcessor.java b/modules/src/main/java/org/archive/modules/recrawl/FetchHistoryProcessor.java
index c3282b0cf..24bb50743 100644
--- a/modules/src/main/java/org/archive/modules/recrawl/FetchHistoryProcessor.java
+++ b/modules/src/main/java/org/archive/modules/recrawl/FetchHistoryProcessor.java
@@ -57,7 +57,6 @@ public void setHistoryLength(int length) {
public FetchHistoryProcessor() {
}
- @SuppressWarnings("unchecked")
@Override
protected void innerProcess(CrawlURI puri) throws InterruptedException {
CrawlURI curi = (CrawlURI) puri;
@@ -92,12 +91,14 @@ protected void innerProcess(CrawlURI puri) throws InterruptedException {
// get or create proper-sized history array
int targetHistoryLength = getHistoryLength();
- HashMap[] history =
- (HashMap[]) (curi.containsDataKey(A_FETCH_HISTORY)
+ @SuppressWarnings("unchecked")
+ HashMap<String, ?>[] history =
+ (HashMap<String, ?>[]) (curi.containsDataKey(A_FETCH_HISTORY)
? curi.getData().get(A_FETCH_HISTORY)
: new HashMap[targetHistoryLength]);
if(history.length != targetHistoryLength) {
- HashMap[] newHistory = new HashMap[targetHistoryLength];
+ @SuppressWarnings("unchecked")
+ HashMap<String, ?>[] newHistory = new HashMap[targetHistoryLength];
System.arraycopy(
history,0,
newHistory,0,
diff --git a/modules/src/main/java/org/archive/modules/recrawl/PersistLoadProcessor.java b/modules/src/main/java/org/archive/modules/recrawl/PersistLoadProcessor.java
index b9220fcd1..2dc2f8c4e 100644
--- a/modules/src/main/java/org/archive/modules/recrawl/PersistLoadProcessor.java
+++ b/modules/src/main/java/org/archive/modules/recrawl/PersistLoadProcessor.java
@@ -80,10 +80,10 @@ public void setPreloadSourceUrl(String preloadSourceUrl) {
this.preloadSourceUrl = preloadSourceUrl;
}
- @SuppressWarnings("unchecked")
@Override
protected void innerProcess(CrawlURI curi) throws InterruptedException {
String pkey = persistKeyFor(curi);
+ @SuppressWarnings("unchecked")
Map<String, Object> prior =
(Map<String,Object>) store.get(pkey);
if(prior!=null) {
diff --git a/modules/src/main/java/org/archive/modules/writer/MirrorWriterProcessor.java b/modules/src/main/java/org/archive/modules/writer/MirrorWriterProcessor.java
index 0ae482e24..5080fad10 100644
--- a/modules/src/main/java/org/archive/modules/writer/MirrorWriterProcessor.java
+++ b/modules/src/main/java/org/archive/modules/writer/MirrorWriterProcessor.java
@@ -85,7 +85,6 @@
@author Howard Lee Gayle
*/
-@SuppressWarnings("unchecked")
public class MirrorWriterProcessor extends Processor {
private static final long serialVersionUID = 3L;
private static final Logger logger =
@@ -462,7 +461,7 @@ private URIToFileReturn dirPath(String baseDir, String host, int port,
If not, the last element is removed.
@param list the list
*/
- private void ensurePairs(List list) {
+ private void ensurePairs(List<?> list) {
if (1 == (list.size() % 2)) {
list.remove(list.size() - 1);
}
@@ -513,7 +512,7 @@ private URIToFileReturn uriToFile(String baseDir, CrawlURI curi)
if ((null != ctm) && (ctm.size() > 1)) {
ensurePairs(ctm);
String contentType = curi.getContentType().toLowerCase();
- Iterator i = ctm.iterator();
+ Iterator<String> i = ctm.iterator();
for (boolean more = true; more && i.hasNext();) {
String ct = (String) i.next();
String suf = (String) i.next();
@@ -542,7 +541,7 @@ private URIToFileReturn uriToFile(String baseDir, CrawlURI curi)
ensurePairs(cm);
characterMap = new HashMap<String,String>(cm.size());
// Above will be half full.
- for (Iterator i = cm.iterator(); i.hasNext();) {
+ for (Iterator<String> i = cm.iterator(); i.hasNext();) {
String s1 = (String) i.next();
String s2 = (String) i.next();
if ((null != s1) && (1 == s1.length()) && (null != s2)
@@ -628,15 +627,15 @@ file system path segment (component)
@throws IOException
if a needed directory could not be created
@throws IOException
- if a needed directory is not writeable
+ if a needed directory is not writable
@throws IOException
if a non-directory file exists with the same path as a needed directory
*/
private URIToFileReturn uriToFile(CrawlURI curi, String host, int port,
String uriPath, String query, String suffix, String baseDir,
int maxSegLen, int maxPathLen, boolean caseSensitive,
- String dirFile, Map characterMap, String dotBegin, String dotEnd,
- String tooLongDir, boolean suffixAtEnd, Set underscoreSet)
+ String dirFile, Map<String, String> characterMap, String dotBegin, String dotEnd,
+ String tooLongDir, boolean suffixAtEnd, Set<String> underscoreSet)
throws IOException {
assert (null == host) || (0 != host.length());
assert 0 != uriPath.length();
@@ -904,7 +903,7 @@ This class represents one directory segment (component) of a URI path.
*/
class DirSegment extends PathSegment {
/** If a segment name is in this set, prepend an underscore.*/
- private Set underscoreSet;
+ private Set<String> underscoreSet;
/**
Creates a DirSegment.
@@ -937,8 +936,8 @@ file system path segment (component)
maxSegLen is too small.
*/
DirSegment(String uriPath, int beginIndex, int endIndex, int maxSegLen,
- boolean caseSensitive, CrawlURI curi, Map characterMap,
- String dotBegin, String dotEnd, Set underscoreSet) {
+ boolean caseSensitive, CrawlURI curi, Map<String, String> characterMap,
+ String dotBegin, String dotEnd, Set<String> underscoreSet) {
super(maxSegLen, caseSensitive, curi);
mainPart = new LumpyString(uriPath, beginIndex, endIndex,
(null == dotEnd) ? 0 : dotEnd.length(),
@@ -1126,7 +1125,7 @@ file system path segment (component)
maxSegLen is too small.
*/
EndSegment(String uriPath, int beginIndex, int endIndex, int maxSegLen,
- boolean caseSensitive, CrawlURI curi, Map characterMap,
+ boolean caseSensitive, CrawlURI curi, Map<String, String> characterMap,
String dotBegin, String query, String suffix,
int maxPathLen, boolean suffixAtEnd) {
super(maxSegLen - 1, caseSensitive, curi);
@@ -1413,7 +1412,7 @@ class LumpyString {
dotBegin is non-null but empty.
*/
LumpyString(String str, int beginIndex, int endIndex, int padding,
- int maxLen, Map characterMap, String dotBegin) {
+ int maxLen, Map<String, String> characterMap, String dotBegin) {
if (beginIndex < 0) {
throw new IllegalArgumentException("beginIndex < 0: "
+ beginIndex);
diff --git a/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java b/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java
index 09dd6d1d1..dcd5d4fca 100644
--- a/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java
+++ b/modules/src/main/java/org/archive/modules/writer/WriterPoolProcessor.java
@@ -62,7 +62,6 @@
public abstract class WriterPoolProcessor extends Processor
implements Lifecycle, Checkpointable, WriterPoolSettings {
private static final long serialVersionUID = 1L;
- @SuppressWarnings("unused")
private static final Logger logger =
Logger.getLogger(WriterPoolProcessor.class.getName());
|
8d056194e11076f0da84e62f63f86d2abcbcbb60
|
hbase
|
HBASE-4861 Fix some misspells and extraneous- characters in logs; set some to TRACE--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1205732 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/src/main/java/org/apache/hadoop/hbase/HRegionInfo.java b/src/main/java/org/apache/hadoop/hbase/HRegionInfo.java
index 0536b6e24aea..0c1fa3fe4c21 100644
--- a/src/main/java/org/apache/hadoop/hbase/HRegionInfo.java
+++ b/src/main/java/org/apache/hadoop/hbase/HRegionInfo.java
@@ -655,9 +655,8 @@ public boolean isSplitParent() {
*/
@Override
public String toString() {
- return "REGION => {" + HConstants.NAME + " => '" +
+ return "{" + HConstants.NAME + " => '" +
this.regionNameStr
- + "', TableName => '" + Bytes.toStringBinary(this.tableName)
+ "', STARTKEY => '" +
Bytes.toStringBinary(this.startKey) + "', ENDKEY => '" +
Bytes.toStringBinary(this.endKey) +
diff --git a/src/main/java/org/apache/hadoop/hbase/catalog/MetaEditor.java b/src/main/java/org/apache/hadoop/hbase/catalog/MetaEditor.java
index dc1e872be17a..19fee5c4acdc 100644
--- a/src/main/java/org/apache/hadoop/hbase/catalog/MetaEditor.java
+++ b/src/main/java/org/apache/hadoop/hbase/catalog/MetaEditor.java
@@ -289,8 +289,9 @@ public static void deleteDaughtersReferencesInParent(CatalogTracker catalogTrack
delete.deleteColumns(HConstants.CATALOG_FAMILY, HConstants.SPLITA_QUALIFIER);
delete.deleteColumns(HConstants.CATALOG_FAMILY, HConstants.SPLITB_QUALIFIER);
deleteMetaTable(catalogTracker, delete);
- LOG.info("Deleted daughters references, qualifier=" + Bytes.toStringBinary(HConstants.SPLITA_QUALIFIER) + " and qualifier="
- + Bytes.toStringBinary(HConstants.SPLITA_QUALIFIER) + ", from parent " + parent.getRegionNameAsString());
+ LOG.info("Deleted daughters references, qualifier=" + Bytes.toStringBinary(HConstants.SPLITA_QUALIFIER) +
+ " and qualifier=" + Bytes.toStringBinary(HConstants.SPLITB_QUALIFIER) +
+ ", from parent " + parent.getRegionNameAsString());
}
public static HRegionInfo getHRegionInfo(
@@ -317,4 +318,4 @@ private static Put addLocation(final Put p, final ServerName sn) {
Bytes.toBytes(sn.getStartcode()));
return p;
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java b/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
index e4de22ad9d84..6af1f82092aa 100644
--- a/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
+++ b/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java
@@ -1816,7 +1816,7 @@ public void close() {
} else {
close(true);
}
- LOG.debug("The connection to " + this.zooKeeper + " has been closed.");
+ if (LOG.isTraceEnabled()) LOG.debug("" + this.zooKeeper + " closed.");
}
/**
diff --git a/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileBlockIndex.java b/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileBlockIndex.java
index 8cf220b5052f..3f6ccb6fece3 100644
--- a/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileBlockIndex.java
+++ b/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileBlockIndex.java
@@ -746,8 +746,8 @@ public long writeIndexBlocks(FSDataOutputStream out) throws IOException {
totalBlockUncompressedSize +=
blockWriter.getUncompressedSizeWithoutHeader();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Wrote a " + numLevels + "-level index with root level at pos "
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Wrote a " + numLevels + "-level index with root level at pos "
+ out.getPos() + ", " + rootChunk.getNumEntries()
+ " root-level entries, " + totalNumEntries + " total entries, "
+ StringUtils.humanReadableInt(this.totalBlockOnDiskSize) +
@@ -782,9 +782,11 @@ public void writeSingleLevelIndex(DataOutput out, String description)
rootChunk = curInlineChunk;
curInlineChunk = new BlockIndexChunk();
- LOG.info("Wrote a single-level " + description + " index with "
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Wrote a single-level " + description + " index with "
+ rootChunk.getNumEntries() + " entries, " + rootChunk.getRootSize()
+ " bytes");
+ }
rootChunk.writeRoot(out);
}
diff --git a/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileReaderV2.java b/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileReaderV2.java
index 1bae2615ab69..c1f304e9df63 100644
--- a/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileReaderV2.java
+++ b/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileReaderV2.java
@@ -331,8 +331,10 @@ public void close(boolean evictOnClose) throws IOException {
if (evictOnClose && cacheConf.isBlockCacheEnabled()) {
int numEvicted = cacheConf.getBlockCache().evictBlocksByPrefix(name
+ HFile.CACHE_KEY_SEPARATOR);
- LOG.debug("On close, file=" + name + " evicted=" + numEvicted
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("On close, file=" + name + " evicted=" + numEvicted
+ " block(s)");
+ }
}
if (closeIStream && istream != null) {
istream.close();
diff --git a/src/main/java/org/apache/hadoop/hbase/master/handler/SplitRegionHandler.java b/src/main/java/org/apache/hadoop/hbase/master/handler/SplitRegionHandler.java
index f3812344137c..2d544dd155f9 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/handler/SplitRegionHandler.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/handler/SplitRegionHandler.java
@@ -110,7 +110,7 @@ public void process() {
parent.getEncodedName() + ")", e);
}
}
- LOG.info("Handled SPLIT report); parent=" +
+ LOG.info("Handled SPLIT event; parent=" +
this.parent.getRegionNameAsString() +
" daughter a=" + this.daughters.get(0).getRegionNameAsString() +
"daughter b=" + this.daughters.get(1).getRegionNameAsString());
diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
index 6f37b84bc637..94a8c1d46f43 100644
--- a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -1580,7 +1580,6 @@ public void postOpenDeployTasks(final HRegion r, final CatalogTracker ct,
// Add to online regions if all above was successful.
addToOnlineRegions(r);
- LOG.info("addToOnlineRegions is done" + r.getRegionInfo());
// Update ZK, ROOT or META
if (r.getRegionInfo().isRootRegion()) {
RootLocationEditor.setRootLocation(getZooKeeper(),
@@ -1598,7 +1597,7 @@ public void postOpenDeployTasks(final HRegion r, final CatalogTracker ct,
this.serverNameFromMasterPOV);
}
}
- LOG.info("Done with post open deploy taks for region=" +
+ LOG.info("Done with post open deploy task for region=" +
r.getRegionNameAsString() + ", daughter=" + daughter);
}
diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/SplitTransaction.java b/src/main/java/org/apache/hadoop/hbase/regionserver/SplitTransaction.java
index 0cc2f63a6b8c..08b7de316320 100644
--- a/src/main/java/org/apache/hadoop/hbase/regionserver/SplitTransaction.java
+++ b/src/main/java/org/apache/hadoop/hbase/regionserver/SplitTransaction.java
@@ -393,7 +393,7 @@ private static long getDaughterRegionIdTimestamp(final HRegionInfo hri) {
// that it's possible for the master to miss an event.
do {
if (spins % 10 == 0) {
- LOG.info("Still waiting on the master to process the split for " +
+ LOG.debug("Still waiting on the master to process the split for " +
this.parent.getRegionInfo().getEncodedName());
}
Thread.sleep(100);
diff --git a/src/main/java/org/apache/hadoop/hbase/util/BloomFilterFactory.java b/src/main/java/org/apache/hadoop/hbase/util/BloomFilterFactory.java
index 79c72208291f..418bd16ae9c1 100644
--- a/src/main/java/org/apache/hadoop/hbase/util/BloomFilterFactory.java
+++ b/src/main/java/org/apache/hadoop/hbase/util/BloomFilterFactory.java
@@ -173,12 +173,12 @@ public static BloomFilterWriter createGeneralBloomAtWrite(Configuration conf,
CacheConfig cacheConf, BloomType bloomType, int maxKeys,
HFile.Writer writer) {
if (!isGeneralBloomEnabled(conf)) {
- LOG.debug("Bloom filters are disabled by configuration for "
+ LOG.trace("Bloom filters are disabled by configuration for "
+ writer.getPath()
+ (conf == null ? " (configuration is null)" : ""));
return null;
} else if (bloomType == BloomType.NONE) {
- LOG.debug("Bloom filter is turned off for the column family");
+ LOG.trace("Bloom filter is turned off for the column family");
return null;
}
|
9eb049791037ecb65da18b562ff57804fbd6e942
|
ReactiveX-RxJava
|
Performance refactoring: OperatorSubscribeFunction--- migrated Func1 to OperatorSubscribeFunction for internal operator implementations-- do not wrap with AtomicObserver when it's a trusted operator--https://github.com/Netflix/RxJava/issues/104-
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/observables/Observable.java b/rxjava-core/src/main/java/rx/observables/Observable.java
index adcef9f5a9..79ad9fa84d 100644
--- a/rxjava-core/src/main/java/rx/observables/Observable.java
+++ b/rxjava-core/src/main/java/rx/observables/Observable.java
@@ -46,6 +46,7 @@
import rx.observables.operations.OperationToObservableList;
import rx.observables.operations.OperationToObservableSortedList;
import rx.observables.operations.OperationZip;
+import rx.observables.operations.OperatorSubscribeFunction;
import rx.util.AtomicObservableSubscription;
import rx.util.AtomicObserver;
import rx.util.functions.Action0;
@@ -74,7 +75,7 @@ public class Observable<T> {
private final Func1<Observer<T>, Subscription> onSubscribe;
- public Observable(Func1<Observer<T>, Subscription> onSubscribe) {
+ protected Observable(Func1<Observer<T>, Subscription> onSubscribe) {
this.onSubscribe = onSubscribe;
}
@@ -104,16 +105,23 @@ public Observable(Func1<Observer<T>, Subscription> onSubscribe) {
* to stop receiving notifications before the provider has finished sending them
*/
public Subscription subscribe(Observer<T> observer) {
- /*
- * Wrap the observer and subscription in Atomic* wrappers to:
- *
- * - ensure correct behavior of onNext, onCompleted and onError.
- * - allow the Observer to have access to the subscription in asynchronous execution for checking if unsubscribed occurred without onComplete/onError.
- * - handle both synchronous and asynchronous subscribe() execution flows
- */
- final AtomicObservableSubscription subscription = new AtomicObservableSubscription();
- final Observer<T> atomicObserver = new AtomicObserver<T>(observer, subscription);
- return subscription.wrap(onSubscribe.call(atomicObserver));
+ if (onSubscribe instanceof OperatorSubscribeFunction) {
+ /*
+ * This means it's a 'trusted' operator so we won't wrap it.
+ */
+ return onSubscribe.call(observer);
+ } else {
+ /*
+ * Wrap the observer and subscription in Atomic* wrappers to:
+ *
+ * - ensure correct behavior of onNext, onCompleted and onError.
+ * - allow the Observer to have access to the subscription in asynchronous execution for checking if unsubscribed occurred without onComplete/onError.
+ * - handle both synchronous and asynchronous subscribe() execution flows
+ */
+ final AtomicObservableSubscription subscription = new AtomicObservableSubscription();
+ final Observer<T> atomicObserver = new AtomicObserver<T>(observer, subscription);
+ return subscription.wrap(onSubscribe.call(atomicObserver));
+ }
};
@SuppressWarnings({ "rawtypes", "unchecked" })
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationCombineLatest.java b/rxjava-core/src/main/java/rx/observables/operations/OperationCombineLatest.java
index c1444e7e9b..d689a07bc0 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationCombineLatest.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationCombineLatest.java
@@ -103,7 +103,7 @@ public void onNext(Object args) {
*
* @param <R>
*/
- private static class Aggregator<R> implements Func1<Observer<R>, Subscription> {
+ private static class Aggregator<R> implements OperatorSubscribeFunction<R> {
private final FuncN<R> combineLatestFunction;
private Observer<R> Observer;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationFilter.java b/rxjava-core/src/main/java/rx/observables/operations/OperationFilter.java
index b26ef84b24..119635cc2d 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationFilter.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationFilter.java
@@ -24,6 +24,7 @@
import rx.observables.Observable;
import rx.observables.Observer;
import rx.observables.Subscription;
+import rx.util.AtomicObservableSubscription;
import rx.util.functions.Func1;
public final class OperationFilter<T> {
@@ -32,10 +33,11 @@ public static <T> Func1<Observer<T>, Subscription> filter(Observable<T> that, Fu
return new Filter<T>(that, predicate);
}
- private static class Filter<T> implements Func1<Observer<T>, Subscription> {
+ private static class Filter<T> implements OperatorSubscribeFunction<T> {
private final Observable<T> that;
private final Func1<T, Boolean> predicate;
+ private final AtomicObservableSubscription subscription = new AtomicObservableSubscription();
public Filter(Observable<T> that, Func1<T, Boolean> predicate) {
this.that = that;
@@ -43,7 +45,7 @@ public Filter(Observable<T> that, Func1<T, Boolean> predicate) {
}
public Subscription call(final Observer<T> observer) {
- return that.subscribe(new Observer<T>() {
+ return subscription.wrap(that.subscribe(new Observer<T>() {
public void onNext(T value) {
try {
if ((boolean) predicate.call(value)) {
@@ -51,7 +53,8 @@ public void onNext(T value) {
}
} catch (Exception ex) {
observer.onError(ex);
- // TODO is there a way to tell 'that' to unsubscribe if we have an error?
+ // this will work if the sequence is asynchronous, it will have no effect on a synchronous observable
+ subscription.unsubscribe();
}
}
@@ -62,7 +65,7 @@ public void onError(Exception ex) {
public void onCompleted() {
observer.onCompleted();
}
- });
+ }));
}
}
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationLast.java b/rxjava-core/src/main/java/rx/observables/operations/OperationLast.java
index 4bdd125f1d..465ee7b391 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationLast.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationLast.java
@@ -40,7 +40,7 @@ public static <T> Func1<Observer<T>, Subscription> last(Observable<T> observable
return new Last<T>(observable);
}
- private static class Last<T> implements Func1<Observer<T>, Subscription> {
+ private static class Last<T> implements OperatorSubscribeFunction<T> {
private final AtomicReference<T> lastValue = new AtomicReference<T>();
private final Observable<T> that;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationMap.java b/rxjava-core/src/main/java/rx/observables/operations/OperationMap.java
index c1a689814c..0f19468b9a 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationMap.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationMap.java
@@ -79,7 +79,7 @@ public static <T, R> Func1<Observer<R>, Subscription> mapMany(Observable<T> sequ
* @param <R>
* the type of the output sequence.
*/
- private static class MapObservable<T, R> implements Func1<Observer<R>, Subscription> {
+ private static class MapObservable<T, R> implements OperatorSubscribeFunction<R> {
public MapObservable(Observable<T> sequence, Func1<T, R> func) {
this.sequence = sequence;
this.func = func;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationMaterialize.java b/rxjava-core/src/main/java/rx/observables/operations/OperationMaterialize.java
index 8c81d46ba5..f941c31edc 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationMaterialize.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationMaterialize.java
@@ -49,7 +49,7 @@ public static <T> Func1<Observer<Notification<T>>, Subscription> materialize(fin
return new MaterializeObservable<T>(sequence);
}
- private static class MaterializeObservable<T> implements Func1<Observer<Notification<T>>, Subscription> {
+ private static class MaterializeObservable<T> implements OperatorSubscribeFunction<Notification<T>> {
private final Observable<T> sequence;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationMerge.java b/rxjava-core/src/main/java/rx/observables/operations/OperationMerge.java
index 21d3791950..10f701abb2 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationMerge.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationMerge.java
@@ -46,7 +46,7 @@ public final class OperationMerge {
*/
public static <T> Func1<Observer<T>, Subscription> merge(final Observable<Observable<T>> o) {
// wrap in a Func so that if a chain is built up, then asynchronously subscribed to twice we will have 2 instances of Take<T> rather than 1 handing both, which is not thread-safe.
- return new Func1<Observer<T>, Subscription>() {
+ return new OperatorSubscribeFunction<T>() {
@Override
public Subscription call(Observer<T> observer) {
@@ -56,7 +56,7 @@ public Subscription call(Observer<T> observer) {
}
public static <T> Func1<Observer<T>, Subscription> merge(final Observable<T>... sequences) {
- return merge(Observable.create(new Func1<Observer<Observable<T>>, Subscription>() {
+ return merge(Observable.create(new OperatorSubscribeFunction<Observable<T>>() {
private volatile boolean unsubscribed = false;
@Override
@@ -85,7 +85,7 @@ public void unsubscribe() {
}
public static <T> Func1<Observer<T>, Subscription> merge(final List<Observable<T>> sequences) {
- return merge(Observable.create(new Func1<Observer<Observable<T>>, Subscription>() {
+ return merge(Observable.create(new OperatorSubscribeFunction<Observable<T>>() {
private volatile boolean unsubscribed = false;
@@ -126,7 +126,7 @@ public void unsubscribe() {
*
* @param <T>
*/
- private static final class MergeObservable<T> implements Func1<Observer<T>, Subscription> {
+ private static final class MergeObservable<T> implements OperatorSubscribeFunction<T> {
private final Observable<Observable<T>> sequences;
private final MergeSubscription ourSubscription = new MergeSubscription();
private AtomicBoolean stopped = new AtomicBoolean(false);
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationMergeDelayError.java b/rxjava-core/src/main/java/rx/observables/operations/OperationMergeDelayError.java
index cc7d15c80a..11d0ddd662 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationMergeDelayError.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationMergeDelayError.java
@@ -58,7 +58,7 @@ public final class OperationMergeDelayError {
*/
public static <T> Func1<Observer<T>, Subscription> mergeDelayError(final Observable<Observable<T>> sequences) {
// wrap in a Func so that if a chain is built up, then asynchronously subscribed to twice we will have 2 instances of Take<T> rather than 1 handing both, which is not thread-safe.
- return new Func1<Observer<T>, Subscription>() {
+ return new OperatorSubscribeFunction<T>() {
@Override
public Subscription call(Observer<T> observer) {
@@ -68,7 +68,7 @@ public Subscription call(Observer<T> observer) {
}
public static <T> Func1<Observer<T>, Subscription> mergeDelayError(final Observable<T>... sequences) {
- return mergeDelayError(Observable.create(new Func1<Observer<Observable<T>>, Subscription>() {
+ return mergeDelayError(Observable.create(new OperatorSubscribeFunction<Observable<T>>() {
private volatile boolean unsubscribed = false;
@Override
@@ -97,7 +97,7 @@ public void unsubscribe() {
}
public static <T> Func1<Observer<T>, Subscription> mergeDelayError(final List<Observable<T>> sequences) {
- return mergeDelayError(Observable.create(new Func1<Observer<Observable<T>>, Subscription>() {
+ return mergeDelayError(Observable.create(new OperatorSubscribeFunction<Observable<T>>() {
private volatile boolean unsubscribed = false;
@@ -138,7 +138,7 @@ public void unsubscribe() {
*
* @param <T>
*/
- private static final class MergeDelayErrorObservable<T> implements Func1<Observer<T>, Subscription> {
+ private static final class MergeDelayErrorObservable<T> implements OperatorSubscribeFunction<T> {
private final Observable<Observable<T>> sequences;
private final MergeSubscription ourSubscription = new MergeSubscription();
private AtomicBoolean stopped = new AtomicBoolean(false);
@@ -848,7 +848,6 @@ private static class CaptureObserver implements Observer<String> {
@Override
public void onCompleted() {
- // TODO Auto-generated method stub
}
@@ -859,7 +858,6 @@ public void onError(Exception e) {
@Override
public void onNext(String args) {
- // TODO Auto-generated method stub
}
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaFunction.java b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaFunction.java
index 06d6bbdf05..d041b9b0b7 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaFunction.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaFunction.java
@@ -38,7 +38,7 @@ public static <T> Func1<Observer<T>, Subscription> onErrorResumeNextViaFunction(
return new OnErrorResumeNextViaFunction<T>(originalSequence, resumeFunction);
}
- private static class OnErrorResumeNextViaFunction<T> implements Func1<Observer<T>, Subscription> {
+ private static class OnErrorResumeNextViaFunction<T> implements OperatorSubscribeFunction<T> {
private final Func1<Exception, Observable<T>> resumeFunction;
private final Observable<T> originalSequence;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaObservable.java b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaObservable.java
index c7da6bdee2..33fe9ee227 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaObservable.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaObservable.java
@@ -36,7 +36,7 @@ public static <T> Func1<Observer<T>, Subscription> onErrorResumeNextViaObservabl
return new OnErrorResumeNextViaObservable<T>(originalSequence, resumeSequence);
}
- private static class OnErrorResumeNextViaObservable<T> implements Func1<Observer<T>, Subscription> {
+ private static class OnErrorResumeNextViaObservable<T> implements OperatorSubscribeFunction<T> {
private final Observable<T> resumeSequence;
private final Observable<T> originalSequence;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorReturn.java b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorReturn.java
index 7f76433c10..8b8a988c3b 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorReturn.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorReturn.java
@@ -41,7 +41,7 @@ public static <T> Func1<Observer<T>, Subscription> onErrorReturn(Observable<T> o
return new OnErrorReturn<T>(originalSequence, resumeFunction);
}
- private static class OnErrorReturn<T> implements Func1<Observer<T>, Subscription> {
+ private static class OnErrorReturn<T> implements OperatorSubscribeFunction<T> {
private final Func1<Exception, T> resumeFunction;
private final Observable<T> originalSequence;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationScan.java b/rxjava-core/src/main/java/rx/observables/operations/OperationScan.java
index e7c09b0f83..7752bb2549 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationScan.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationScan.java
@@ -25,6 +25,7 @@
import rx.observables.Observable;
import rx.observables.Observer;
import rx.observables.Subscription;
+import rx.util.AtomicObservableSubscription;
import rx.util.functions.Func1;
import rx.util.functions.Func2;
@@ -61,10 +62,11 @@ public static <T> Func1<Observer<T>, Subscription> scan(Observable<T> sequence,
return new Accumulator<T>(sequence, null, accumulator);
}
- private static class Accumulator<T> implements Func1<Observer<T>, Subscription> {
+ private static class Accumulator<T> implements OperatorSubscribeFunction<T> {
private final Observable<T> sequence;
private final T initialValue;
private Func2<T, T, T> accumlatorFunction;
+ private final AtomicObservableSubscription subscription = new AtomicObservableSubscription();
private Accumulator(Observable<T> sequence, T initialValue, Func2<T, T, T> accumulator) {
this.sequence = sequence;
@@ -74,7 +76,7 @@ private Accumulator(Observable<T> sequence, T initialValue, Func2<T, T, T> accum
public Subscription call(final Observer<T> observer) {
- return sequence.subscribe(new Observer<T>() {
+ return subscription.wrap(sequence.subscribe(new Observer<T>() {
private T acc = initialValue;
private boolean hasSentInitialValue = false;
@@ -108,7 +110,8 @@ public synchronized void onNext(T value) {
observer.onNext(acc);
} catch (Exception ex) {
observer.onError(ex);
- // TODO is there a correct way to unsubscribe from the sequence?
+ // this will work if the sequence is asynchronous, it will have no effect on a synchronous observable
+ subscription.unsubscribe();
}
}
@@ -124,7 +127,7 @@ public synchronized void onCompleted() {
}
observer.onCompleted();
}
- });
+ }));
}
}
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationSkip.java b/rxjava-core/src/main/java/rx/observables/operations/OperationSkip.java
index 35c470af1e..15d4e76cf0 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationSkip.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationSkip.java
@@ -62,7 +62,7 @@ public Subscription call(Observer<T> observer) {
*
* @param <T>
*/
- private static class Skip<T> implements Func1<Observer<T>, Subscription> {
+ private static class Skip<T> implements OperatorSubscribeFunction<T> {
private final int num;
private final Observable<T> items;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationSynchronize.java b/rxjava-core/src/main/java/rx/observables/operations/OperationSynchronize.java
index 6258c7703f..b6d3ad36c3 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationSynchronize.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationSynchronize.java
@@ -58,7 +58,7 @@ public static <T> Func1<Observer<T>, Subscription> synchronize(Observable<T> obs
return new Synchronize<T>(observable);
}
- private static class Synchronize<T> implements Func1<Observer<T>, Subscription> {
+ private static class Synchronize<T> implements OperatorSubscribeFunction<T> {
public Synchronize(Observable<T> innerObservable) {
this.innerObservable = innerObservable;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationTake.java b/rxjava-core/src/main/java/rx/observables/operations/OperationTake.java
index 676887d8fb..7d6bed7b71 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationTake.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationTake.java
@@ -26,6 +26,7 @@
import rx.observables.Observable;
import rx.observables.Observer;
import rx.observables.Subscription;
+import rx.util.AtomicObservableSubscription;
import rx.util.functions.Func1;
/**
@@ -44,7 +45,7 @@ public final class OperationTake {
*/
public static <T> Func1<Observer<T>, Subscription> take(final Observable<T> items, final int num) {
// wrap in a Watchbable so that if a chain is built up, then asynchronously subscribed to twice we will have 2 instances of Take<T> rather than 1 handing both, which is not thread-safe.
- return new Func1<Observer<T>, Subscription>() {
+ return new OperatorSubscribeFunction<T>() {
@Override
public Subscription call(Observer<T> observer) {
@@ -65,9 +66,10 @@ public Subscription call(Observer<T> observer) {
*
* @param <T>
*/
- private static class Take<T> implements Func1<Observer<T>, Subscription> {
+ private static class Take<T> implements OperatorSubscribeFunction<T> {
private final int num;
private final Observable<T> items;
+ private final AtomicObservableSubscription subscription = new AtomicObservableSubscription();
Take(final Observable<T> items, final int num) {
this.num = num;
@@ -75,7 +77,7 @@ private static class Take<T> implements Func1<Observer<T>, Subscription> {
}
public Subscription call(Observer<T> observer) {
- return items.subscribe(new ItemObserver(observer));
+ return subscription.wrap(items.subscribe(new ItemObserver(observer)));
}
/**
@@ -105,8 +107,8 @@ public void onNext(T args) {
if (counter.getAndIncrement() < num) {
observer.onNext(args);
} else {
- observer.onCompleted();
- // TODO do we need to unsubscribe here?
+ // this will work if the sequence is asynchronous, it will have no effect on a synchronous observable
+ subscription.unsubscribe();
}
}
@@ -168,8 +170,7 @@ public void testUnsubscribeAfterTake() {
verify(aObserver, times(1)).onNext("one");
verify(aObserver, never()).onNext("two");
verify(aObserver, never()).onNext("three");
- // TODO commented this out for now as it's broken and I'm questioning whether it needs to be
- // verify(s, times(1)).unsubscribe();
+ verify(s, times(1)).unsubscribe();
}
private static class TestObservable extends Observable<String> {
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableIterable.java b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableIterable.java
index 0c58e0411c..802a25bac3 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableIterable.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableIterable.java
@@ -40,7 +40,7 @@ public static <T> Func1<Observer<T>, Subscription> toObservableIterable(Iterable
return new ToObservableIterable<T>(list);
}
- private static class ToObservableIterable<T> implements Func1<Observer<T>, Subscription> {
+ private static class ToObservableIterable<T> implements OperatorSubscribeFunction<T> {
public ToObservableIterable(Iterable<T> list) {
this.iterable = list;
}
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableList.java b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableList.java
index 4b4ef30e44..3c5673b860 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableList.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableList.java
@@ -37,7 +37,7 @@ public static <T> Func1<Observer<List<T>>, Subscription> toObservableList(Observ
return new ToObservableList<T>(that);
}
- private static class ToObservableList<T> implements Func1<Observer<List<T>>, Subscription> {
+ private static class ToObservableList<T> implements OperatorSubscribeFunction<List<T>> {
private final Observable<T> that;
final ConcurrentLinkedQueue<T> list = new ConcurrentLinkedQueue<T>();
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableSortedList.java b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableSortedList.java
index 7f5c99112d..de17b17345 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableSortedList.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableSortedList.java
@@ -64,7 +64,7 @@ public static <T> Func1<Observer<List<T>>, Subscription> toSortedList(Observable
return new ToObservableSortedList<T>(sequence, sortFunction);
}
- private static class ToObservableSortedList<T> implements Func1<Observer<List<T>>, Subscription> {
+ private static class ToObservableSortedList<T> implements OperatorSubscribeFunction<List<T>> {
private final Observable<T> that;
private final ConcurrentLinkedQueue<T> list = new ConcurrentLinkedQueue<T>();
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationZip.java b/rxjava-core/src/main/java/rx/observables/operations/OperationZip.java
index 0b4fa26fba..43e816afe3 100644
--- a/rxjava-core/src/main/java/rx/observables/operations/OperationZip.java
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperationZip.java
@@ -112,7 +112,7 @@ public void onNext(T args) {
* @param <R>
*/
@ThreadSafe
- private static class Aggregator<R> implements Func1<Observer<R>, Subscription> {
+ private static class Aggregator<R> implements OperatorSubscribeFunction<R> {
private volatile AtomicObserverSingleThreaded<R> observer;
private final FuncN<R> zipFunction;
diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperatorSubscribeFunction.java b/rxjava-core/src/main/java/rx/observables/operations/OperatorSubscribeFunction.java
new file mode 100644
index 0000000000..c755dff760
--- /dev/null
+++ b/rxjava-core/src/main/java/rx/observables/operations/OperatorSubscribeFunction.java
@@ -0,0 +1,25 @@
+package rx.observables.operations;
+
+import rx.observables.Observable;
+import rx.observables.Observer;
+import rx.observables.Subscription;
+import rx.util.AtomicObserver;
+import rx.util.functions.Func1;
+
+/**
+ * A "marker" interface used for internal operators implementing the "subscribe" function and turned into Observables using {@link Observable#create(Func1)}.
+ * <p>
+ * This marker is used by it to treat these implementations as "trusted".
+ * <p>
+ * NOTE: If you use this interface you are declaring that your implementation:
+ * <ul>
+ * <li>is thread-safe</li>
+ * <li>doesn't need additional wrapping by {@link AtomicObserver}</li>
+ * <li>obeys the contract of onNext, onError, onComplete</li>
+ * </ul>
+ *
+ * @param <T>
+ */
+public interface OperatorSubscribeFunction<T> extends Func1<Observer<T>, Subscription> {
+
+}
diff --git a/rxjava-core/src/main/java/rx/util/functions/Functions.java b/rxjava-core/src/main/java/rx/util/functions/Functions.java
index 518283c87a..6b9237cdf1 100644
--- a/rxjava-core/src/main/java/rx/util/functions/Functions.java
+++ b/rxjava-core/src/main/java/rx/util/functions/Functions.java
@@ -91,12 +91,6 @@ public static FuncN from(final Object function) {
} else {
/* not an Rx Function so try language adaptors */
- /*
- * TODO the following code needs to be evaluated for performance
- *
- * The c.isInstance and keySet() functions may be areas of concern with as often as this will be executed
- */
-
// check for language adaptor
for (final Class c : languageAdaptors.keySet()) {
if (c.isInstance(function)) {
|
3be0759b44c97834e6fd96ac189500aa4d58dcc1
|
orientdb
|
Fixed issue -1445 providing the new TIMEOUT in- most of the commands--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java
index e8f9485d140..1f87da6be4c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java
@@ -15,6 +15,7 @@
*/
package com.orientechnologies.orient.core.command;
+import java.util.Locale;
import java.util.Map;
import com.orientechnologies.common.listener.OProgressListener;
@@ -35,8 +36,9 @@ public abstract class OCommandExecutorAbstract extends OBaseParser implements OC
protected Map<Object, Object> parameters;
protected OCommandContext context;
- public OCommandExecutorAbstract init(final String iText) {
- parserText = iText;
+ public OCommandExecutorAbstract init(final OCommandRequestText iRequest) {
+ parserText = iRequest.getText().trim();
+ parserTextUpperCase = parserText.toUpperCase(Locale.ENGLISH);
return this;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java
index 1fb1d707de0..920c9fbc76e 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java
@@ -23,6 +23,10 @@
* @param <T>
*/
public interface OCommandRequest {
+ public enum TIMEOUT_STRATEGY {
+ EXCEPTION, RETURN
+ }
+
public <RET> RET execute(Object... iArgs);
/**
@@ -40,6 +44,27 @@ public interface OCommandRequest {
*/
public OCommandRequest setLimit(int iLimit);
+ /**
+ * Returns the command timeout. 0 means no timeout.
+ *
+ * @return
+ */
+ public long getTimeoutTime();
+
+ /**
+ * Returns the command timeout strategy between the defined ones.
+ *
+ * @return
+ */
+ public TIMEOUT_STRATEGY getTimeoutStrategy();
+
+ /**
+ * Sets the command timeout. When the command execution time is major than the timeout the command returns
+ *
+ * @param timeout
+ */
+ public void setTimeout(long timeout, TIMEOUT_STRATEGY strategy);
+
/**
* Returns true if the command doesn't change the database, otherwise false.
*/
diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java
index 4c52a5849e5..fa21df7fc00 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java
@@ -19,6 +19,7 @@
import java.util.Map;
import com.orientechnologies.common.listener.OProgressListener;
+import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
/**
@@ -31,10 +32,12 @@
public abstract class OCommandRequestAbstract implements OCommandRequestInternal {
protected OCommandResultListener resultListener;
protected OProgressListener progressListener;
- protected int limit = -1;
+ protected int limit = -1;
+ protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong();
+ protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION;
protected Map<Object, Object> parameters;
- protected String fetchPlan = null;
- protected boolean useCache = false;
+ protected String fetchPlan = null;
+ protected boolean useCache = false;
protected OCommandContext context;
protected OCommandRequestAbstract() {
@@ -128,4 +131,17 @@ public OCommandRequestAbstract setContext(final OCommandContext iContext) {
context = iContext;
return this;
}
+
+ public long getTimeoutTime() {
+ return timeoutMs;
+ }
+
+ public void setTimeout(final long timeout, TIMEOUT_STRATEGY strategy) {
+ this.timeoutMs = timeout;
+ this.timeoutStrategy = strategy;
+ }
+
+ public TIMEOUT_STRATEGY getTimeoutStrategy() {
+ return timeoutStrategy;
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java
index 5352ec9cbfc..04752630f1c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java
@@ -28,15 +28,18 @@
* @param <T>
*/
public interface OCommandRequestInternal extends OCommandRequest, OSerializableStream {
- public Map<Object, Object> getParameters();
- public OCommandResultListener getResultListener();
+ public static final String EXECUTION_BEGUN = "EXECUTION_BEGUN";
- public void setResultListener(OCommandResultListener iListener);
+ public Map<Object, Object> getParameters();
- public OProgressListener getProgressListener();
+ public OCommandResultListener getResultListener();
- public OCommandRequestInternal setProgressListener(OProgressListener iProgressListener);
+ public void setResultListener(OCommandResultListener iListener);
- public void reset();
+ public OProgressListener getProgressListener();
+
+ public OCommandRequestInternal setProgressListener(OProgressListener iProgressListener);
+
+ public void reset();
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java
index 732f46bece5..b4598281c83 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java
@@ -125,6 +125,11 @@ protected byte[] toStream(final OMemoryStream buffer) {
buffer.set(compositeKey.toStream());
}
}
+
+ // TIMEOUT
+ buffer.set(timeoutMs);
+ buffer.set((byte) timeoutStrategy.ordinal());
+
return buffer.toByteArray();
}
@@ -177,6 +182,9 @@ protected void fromStream(final OMemoryStream buffer) {
parameters.put(p.getKey(), value);
}
}
+
+ timeoutMs = buffer.getAsLong();
+ timeoutStrategy = TIMEOUT_STRATEGY.values()[buffer.getAsByte()];
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
index 087cd68f410..dd6fc79dfea 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
@@ -355,6 +355,9 @@ public void change(final Object iCurrentValue, final Object iNewValue) {
}
}),
+ // COMMAND
+ COMMAND_TIMEOUT("command.timeout", "Default timeout for commands expressed in milliseconds", Long.class, 0),
+
// CLIENT
CLIENT_CHANNEL_MIN_POOL("client.channel.minPool", "Minimum pool size", Integer.class, 1),
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java
index 16807468731..c9801165f66 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java
@@ -15,9 +15,9 @@
*/
package com.orientechnologies.orient.core.sql;
-import java.util.Locale;
-
import com.orientechnologies.orient.core.command.OCommandExecutorAbstract;
+import com.orientechnologies.orient.core.command.OCommandRequest.TIMEOUT_STRATEGY;
+import com.orientechnologies.orient.core.config.OGlobalConfiguration;
/**
* SQL abstract Command Executor implementation.
@@ -32,6 +32,7 @@ public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstra
public static final String KEYWORD_WHERE = "WHERE";
public static final String KEYWORD_LIMIT = "LIMIT";
public static final String KEYWORD_SKIP = "SKIP";
+ public static final String KEYWORD_TIMEOUT = "TIMEOUT";
public static final String KEYWORD_KEY = "key";
public static final String KEYWORD_RID = "rid";
public static final String CLUSTER_PREFIX = "CLUSTER:";
@@ -39,6 +40,9 @@ public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstra
public static final String INDEX_PREFIX = "INDEX:";
public static final String DICTIONARY_PREFIX = "DICTIONARY:";
+ protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong();
+ protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION;
+
protected void throwSyntaxErrorException(final String iText) {
throw new OCommandSQLParsingException(iText + ". Use " + getSyntax(), parserText, parserGetPreviousPosition());
}
@@ -47,14 +51,40 @@ protected void throwParsingException(final String iText) {
throw new OCommandSQLParsingException(iText, parserText, parserGetPreviousPosition());
}
- @Override
- public OCommandExecutorSQLAbstract init(String iText) {
- iText = iText.trim();
- parserTextUpperCase = iText.toUpperCase(Locale.ENGLISH);
- return (OCommandExecutorSQLAbstract) super.init(iText);
- }
-
public boolean isIdempotent() {
return false;
}
+
+ /**
+ * Parses the timeout keyword if found.
+ */
+ protected boolean parseTimeout(final String w) throws OCommandSQLParsingException {
+ if (!w.equals(KEYWORD_TIMEOUT))
+ return false;
+
+ parserNextWord(true);
+ String word = parserGetLastWord();
+
+ try {
+ timeoutMs = Long.parseLong(word);
+ } catch (Exception e) {
+ throwParsingException("Invalid " + KEYWORD_TIMEOUT + " value setted to '" + word
+ + "' but it should be a valid long. Example: " + KEYWORD_TIMEOUT + " 3000");
+ }
+
+ if (timeoutMs < 0)
+ throwParsingException("Invalid " + KEYWORD_TIMEOUT + ": value setted to less than ZERO. Example: " + timeoutMs + " 10");
+
+ parserNextWord(true);
+ word = parserGetLastWord();
+
+ if (word.equals(TIMEOUT_STRATEGY.EXCEPTION.toString()))
+ timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION;
+ else if (word.equals(TIMEOUT_STRATEGY.RETURN.toString()))
+ timeoutStrategy = TIMEOUT_STRATEGY.RETURN;
+ else
+ parserGoBack();
+
+ return true;
+ }
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java
index 47ad969ef18..3e04a79279f 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java
@@ -49,7 +49,7 @@ public OCommandExecutorSQLAlterClass parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java
index a3366c5213e..07558bf140f 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java
@@ -52,7 +52,8 @@ public OCommandExecutorSQLAlterCluster parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java
index d53bbfa2be6..2bdbe49bfd2 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java
@@ -47,7 +47,8 @@ public OCommandExecutorSQLAlterDatabase parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java
index 912bd6a0d00..0ada27949a8 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java
@@ -49,7 +49,8 @@ public class OCommandExecutorSQLAlterProperty extends OCommandExecutorSQLAbstrac
public OCommandExecutorSQLAlterProperty parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java
index c1388936a59..ae245b405e7 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java
@@ -50,7 +50,8 @@ public OCommandExecutorSQLCreateClass parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java
index 4514ff84338..6f48a91e28c 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java
@@ -53,7 +53,8 @@ public OCommandExecutorSQLCreateCluster parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
parserRequiredKeyword(KEYWORD_CREATE);
parserRequiredKeyword(KEYWORD_CLUSTER);
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java
index 287469ef3d0..4f1f3543687 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java
@@ -52,7 +52,8 @@ public OCommandExecutorSQLCreateEdge parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
parserRequiredKeyword("CREATE");
parserRequiredKeyword("EDGE");
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java
index 82950427733..efc5b507b80 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java
@@ -47,7 +47,8 @@ public OCommandExecutorSQLCreateFunction parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
parserRequiredKeyword("CREATE");
parserRequiredKeyword("FUNCTION");
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java
index d67a679f924..c902be41839 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java
@@ -63,7 +63,8 @@ public class OCommandExecutorSQLCreateIndex extends OCommandExecutorSQLAbstract
public OCommandExecutorSQLCreateIndex parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
final StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java
index 04b6e2da030..6090b6e1fe0 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java
@@ -65,7 +65,8 @@ public class OCommandExecutorSQLCreateLink extends OCommandExecutorSQLAbstract {
public OCommandExecutorSQLCreateLink parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java
index 2e6167d0aa4..280f24236f5 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java
@@ -49,7 +49,8 @@ public class OCommandExecutorSQLCreateProperty extends OCommandExecutorSQLAbstra
public OCommandExecutorSQLCreateProperty parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java
index 2b6d136e260..bdb2f69200e 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java
@@ -45,7 +45,8 @@ public OCommandExecutorSQLCreateVertex parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
String className = null;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java
index 0accc30b62c..e25c500a2ba 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java
@@ -66,7 +66,8 @@ public OCommandExecutorSQLDelete parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
query = null;
recordCount = 0;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java
index b0f9c72477d..6b32adedae2 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java
@@ -56,7 +56,8 @@ public OCommandExecutorSQLDeleteEdge parse(final OCommandRequest iRequest) {
database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
parserRequiredKeyword("DELETE");
parserRequiredKeyword("EDGE");
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java
index 513141f9f82..230164bfbca 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java
@@ -49,7 +49,8 @@ public OCommandExecutorSQLDeleteVertex parse(final OCommandRequest iRequest) {
database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
parserRequiredKeyword("DELETE");
parserRequiredKeyword("VERTEX");
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java
index 7df6e5af21e..4e92bd50125 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java
@@ -47,7 +47,8 @@ public class OCommandExecutorSQLDropClass extends OCommandExecutorSQLAbstract im
public OCommandExecutorSQLDropClass parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
final StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java
index 27200afee76..1c582d974a6 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java
@@ -42,7 +42,8 @@ public class OCommandExecutorSQLDropCluster extends OCommandExecutorSQLAbstract
public OCommandExecutorSQLDropCluster parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
final StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java
index d65e6b02665..81aee786a74 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java
@@ -40,7 +40,8 @@ public class OCommandExecutorSQLDropIndex extends OCommandExecutorSQLAbstract im
public OCommandExecutorSQLDropIndex parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
final StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java
index 49dafedc3c4..b37cd35408f 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java
@@ -49,7 +49,8 @@ public class OCommandExecutorSQLDropProperty extends OCommandExecutorSQLAbstract
public OCommandExecutorSQLDropProperty parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
final StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java
index 5778546619c..c1b35b5e073 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java
@@ -48,7 +48,8 @@ public class OCommandExecutorSQLFindReferences extends OCommandExecutorSQLEarlyR
public OCommandExecutorSQLFindReferences parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
parserRequiredKeyword(KEYWORD_FIND);
parserRequiredKeyword(KEYWORD_REFERENCES);
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java
index b8407910728..1931a9fa5fa 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java
@@ -37,7 +37,8 @@ public class OCommandExecutorSQLGrant extends OCommandExecutorSQLPermissionAbstr
public OCommandExecutorSQLGrant parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
privilege = ORole.PERMISSION_NONE;
resource = null;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java
index 4e755e62348..35a3c3810f8 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java
@@ -54,7 +54,8 @@ public OCommandExecutorSQLInsert parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
className = null;
newRecords = null;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java
index bbe7fde823d..cb40d905d96 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java
@@ -42,7 +42,8 @@ public class OCommandExecutorSQLRebuildIndex extends OCommandExecutorSQLAbstract
public OCommandExecutorSQLRebuildIndex parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
final StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java
index 6238be70e65..65534af6231 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java
@@ -96,7 +96,7 @@ public OCommandExecutorSQLResultsetAbstract parse(final OCommandRequest iRequest
OCommandRequestText textRequest = (OCommandRequestText) iRequest;
- init(textRequest.getText());
+ init(textRequest);
if (iRequest instanceof OSQLSynchQuery) {
request = (OSQLSynchQuery<ORecordSchemaAware<?>>) iRequest;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java
index 1715ddb309b..1f008085736 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java
@@ -39,7 +39,8 @@ public OCommandExecutorSQLRevoke parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
privilege = ORole.PERMISSION_NONE;
resource = null;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
index 62702f9c0fc..c4af87e5648 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java
@@ -31,10 +31,12 @@
import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.common.collection.OMultiValue;
+import com.orientechnologies.common.concur.OTimeoutException;
import com.orientechnologies.common.concur.resource.OSharedResource;
import com.orientechnologies.common.util.OPair;
import com.orientechnologies.orient.core.command.OBasicCommandContext;
import com.orientechnologies.orient.core.command.OCommandRequest;
+import com.orientechnologies.orient.core.command.OCommandRequestInternal;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
@@ -92,7 +94,8 @@ public class OCommandExecutorSQLSelect extends OCommandExecutorSQLResultsetAbstr
public static final String KEYWORD_GROUP = "GROUP";
private Map<String, String> projectionDefinition = null;
- private Map<String, Object> projections = null; // THIS HAS BEEN KEPT FOR COMPATIBILITY; BUT IT'S USED THE
+ private Map<String, Object> projections = null; // THIS HAS BEEN KEPT FOR COMPATIBILITY; BUT IT'S
+ // USED THE
// PROJECTIONS IN GROUPED-RESULTS
private List<OPair<String, String>> orderedFields;
private List<String> groupByFields;
@@ -153,6 +156,8 @@ else if (w.equals(KEYWORD_LIMIT))
parseLimit(w);
else if (w.equals(KEYWORD_SKIP))
parseSkip(w);
+ else if (w.equals(KEYWORD_TIMEOUT))
+ parseTimeout(w);
else
throwParsingException("Invalid keyword '" + w + "'");
}
@@ -355,6 +360,10 @@ protected boolean assignTarget(Map<Object, Object> iArgs) {
}
protected boolean executeSearchRecord(final OIdentifiable id) {
+
+ if (!checkTimeout())
+ return false;
+
final ORecordInternal<?> record = id.getRecord();
context.updateMetric("recordReads", +1);
@@ -373,6 +382,24 @@ protected boolean executeSearchRecord(final OIdentifiable id) {
return true;
}
+ protected boolean checkTimeout() {
+ if (timeoutMs > 0) {
+ final Long begun = (Long) context.getVariable(OCommandRequestInternal.EXECUTION_BEGUN);
+ if (begun != null) {
+ if (System.currentTimeMillis() - begun.longValue() > timeoutMs) {
+ // TIMEOUT!
+ switch (timeoutStrategy) {
+ case RETURN:
+ return false;
+ case EXCEPTION:
+ throw new OTimeoutException("Command execution timeout exceed (" + timeoutMs + "ms)");
+ }
+ }
+ }
+ }
+ return true;
+ }
+
protected boolean handleResult(final OIdentifiable iRecord) {
lastRecord = null;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java
index b063c16579e..02a2fa91f0f 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java
@@ -104,6 +104,8 @@ public OCommandExecutorSQLTraverse parse(final OCommandRequest iRequest) {
parseLimit(w);
else if (w.equals(KEYWORD_SKIP))
parseSkip(w);
+ else if (w.equals(KEYWORD_TIMEOUT))
+ parseTimeout(w);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java
index 63d4adc916e..bc713db2775 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java
@@ -43,7 +43,8 @@ public OCommandExecutorSQLTruncateClass parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java
index 7c3079e5083..77d30763ca8 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java
@@ -44,7 +44,8 @@ public OCommandExecutorSQLTruncateCluster parse(final OCommandRequest iRequest)
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java
index 5d581d20360..49768ec3f0a 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java
@@ -46,7 +46,8 @@ public class OCommandExecutorSQLTruncateRecord extends OCommandExecutorSQLAbstra
public OCommandExecutorSQLTruncateRecord parse(final OCommandRequest iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
StringBuilder word = new StringBuilder();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
index cc0fcfdf968..5d95038cb44 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
@@ -76,7 +76,8 @@ public OCommandExecutorSQLUpdate parse(final OCommandRequest iRequest) {
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
- init(((OCommandRequestText) iRequest).getText());
+ init((OCommandRequestText) iRequest);
+
setEntries.clear();
addEntries.clear();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
index b03f1d3f998..13567cf999a 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java
@@ -23,6 +23,7 @@
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
+import com.orientechnologies.orient.core.command.OCommandRequestInternal;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
@@ -92,6 +93,8 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE
throw new OCommandExecutionException("Cannot execute non idempotent command");
long beginTime = Orient.instance().getProfiler().startChrono();
+ executor.getContext().setVariable(OCommandRequestInternal.EXECUTION_BEGUN, System.currentTimeMillis());
+
try {
final Object result = executor.execute(iCommand.getParameters());
@@ -104,11 +107,12 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE
throw new OCommandExecutionException("Error on execution of command: " + iCommand, e);
} finally {
- Orient
- .instance()
- .getProfiler()
- .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".command." + iCommand.toString(),
- "Command executed against the database", beginTime, "db.*.command.*");
+ if (Orient.instance().getProfiler().isRecording())
+ Orient
+ .instance()
+ .getProfiler()
+ .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".command." + iCommand.toString(),
+ "Command executed against the database", beginTime, "db.*.command.*");
}
}
diff --git a/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java b/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java
index e7a62a66c34..2e29005b6de 100644
--- a/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java
+++ b/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java
@@ -109,4 +109,20 @@ public OCommandRequest setContext(final OCommandContext iContext) {
command.setContext(iContext);
return this;
}
+
+ @Override
+ public long getTimeoutTime() {
+ return command.getTimeoutTime();
+ }
+
+ @Override
+ public TIMEOUT_STRATEGY getTimeoutStrategy() {
+ return command.getTimeoutStrategy();
+ }
+
+ @Override
+ public void setTimeout(long timeout, TIMEOUT_STRATEGY strategy) {
+ command.setTimeout(timeout, strategy);
+
+ }
}
diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
index 3b44b781188..99feabfd001 100755
--- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
@@ -24,6 +24,7 @@
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
+
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.OConstants;
@@ -326,15 +327,15 @@ protected boolean executeRequest() throws IOException {
releaseDatabase();
break;
- case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE:
- freezeCluster();
- break;
+ case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE:
+ freezeCluster();
+ break;
- case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE:
- releaseCluster();
- break;
+ case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE:
+ releaseCluster();
+ break;
- case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT:
+ case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT:
cleanOutRecord();
break;
@@ -1125,6 +1126,12 @@ protected void command() throws IOException {
final Map<String, Integer> fetchPlan = command != null ? OFetchHelper.buildFetchPlan(command.getFetchPlan()) : null;
command.setResultListener(new AsyncResultListener(empty, clientTxId, fetchPlan, recordsToSend));
+ final long serverTimeout = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong();
+
+ if (serverTimeout > 0 && command.getTimeoutTime() > serverTimeout)
+ // FORCE THE SERVER'S TIMEOUT
+ command.setTimeout(serverTimeout, command.getTimeoutStrategy());
+
((OCommandRequestInternal) connection.database.command(command)).execute();
if (empty.get())
|
f6ea68ffa03cf7a0cbf75eab3778034632744f46
|
tapiji
|
Adds missing code license headers.
Adresses Issue 75.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java
index e3401100..1960c414 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java
@@ -1,50 +1,57 @@
-package org.eclipse.babel.tapiji.tools.core.ui;
-
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class Activator extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.core.ui"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.core.ui"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
index 2c578eb2..157ec4ee 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java
@@ -1,105 +1,112 @@
-package org.eclipse.babel.tapiji.tools.core.ui.decorators;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipse.babel.tapiji.tools.core.model.IResourceExclusionListener;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceExclusionEvent;
-import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.viewers.DecorationOverlayIcon;
-import org.eclipse.jface.viewers.IDecoration;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.LabelProviderChangedEvent;
-import org.eclipse.swt.graphics.Image;
-
-
-public class ExcludedResource implements ILabelDecorator,
- IResourceExclusionListener {
-
- private static final String ENTRY_SUFFIX = "[no i18n]";
- private static final Image OVERLAY_IMAGE_ON =
- ImageUtils.getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON);
- private static final Image OVERLAY_IMAGE_OFF =
- ImageUtils.getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF);
- private final List<ILabelProviderListener> label_provider_listener =
- new ArrayList<ILabelProviderListener> ();
-
- public boolean decorate(Object element) {
- boolean needsDecoration = false;
- if (element instanceof IFolder ||
- element instanceof IFile) {
- IResource resource = (IResource) element;
- if (!InternationalizationNature.hasNature(resource.getProject()))
- return false;
- try {
- ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject());
- if (!manager.isResourceExclusionListenerRegistered(this))
- manager.registerResourceExclusionListener(this);
- if (ResourceBundleManager.isResourceExcluded(resource)) {
- needsDecoration = true;
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
- return needsDecoration;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- label_provider_listener.add(listener);
- }
-
- @Override
- public void dispose() {
- ResourceBundleManager.unregisterResourceExclusionListenerFromAllManagers (this);
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- label_provider_listener.remove(listener);
- }
-
- @Override
- public void exclusionChanged(ResourceExclusionEvent event) {
- LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(this, event.getChangedResources().toArray());
- for (ILabelProviderListener l : label_provider_listener)
- l.labelProviderChanged(labelEvent);
- }
-
- @Override
- public Image decorateImage(Image image, Object element) {
- if (decorate(element)) {
- DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(image,
- Activator.getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF),
- IDecoration.TOP_RIGHT);
- return overlayIcon.createImage();
- } else {
- return image;
- }
- }
-
- @Override
- public String decorateText(String text, Object element) {
- if (decorate(element)) {
- return text + " " + ENTRY_SUFFIX;
- } else
- return text;
- }
-
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.decorators;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceExclusionListener;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceExclusionEvent;
+import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jface.viewers.DecorationOverlayIcon;
+import org.eclipse.jface.viewers.IDecoration;
+import org.eclipse.jface.viewers.ILabelDecorator;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.LabelProviderChangedEvent;
+import org.eclipse.swt.graphics.Image;
+
+
+public class ExcludedResource implements ILabelDecorator,
+ IResourceExclusionListener {
+
+ private static final String ENTRY_SUFFIX = "[no i18n]";
+ private static final Image OVERLAY_IMAGE_ON =
+ ImageUtils.getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON);
+ private static final Image OVERLAY_IMAGE_OFF =
+ ImageUtils.getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF);
+ private final List<ILabelProviderListener> label_provider_listener =
+ new ArrayList<ILabelProviderListener> ();
+
+ public boolean decorate(Object element) {
+ boolean needsDecoration = false;
+ if (element instanceof IFolder ||
+ element instanceof IFile) {
+ IResource resource = (IResource) element;
+ if (!InternationalizationNature.hasNature(resource.getProject()))
+ return false;
+ try {
+ ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject());
+ if (!manager.isResourceExclusionListenerRegistered(this))
+ manager.registerResourceExclusionListener(this);
+ if (ResourceBundleManager.isResourceExcluded(resource)) {
+ needsDecoration = true;
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
+ return needsDecoration;
+ }
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ label_provider_listener.add(listener);
+ }
+
+ @Override
+ public void dispose() {
+ ResourceBundleManager.unregisterResourceExclusionListenerFromAllManagers (this);
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ label_provider_listener.remove(listener);
+ }
+
+ @Override
+ public void exclusionChanged(ResourceExclusionEvent event) {
+ LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(this, event.getChangedResources().toArray());
+ for (ILabelProviderListener l : label_provider_listener)
+ l.labelProviderChanged(labelEvent);
+ }
+
+ @Override
+ public Image decorateImage(Image image, Object element) {
+ if (decorate(element)) {
+ DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(image,
+ Activator.getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF),
+ IDecoration.TOP_RIGHT);
+ return overlayIcon.createImage();
+ } else {
+ return image;
+ }
+ }
+
+ @Override
+ public String decorateText(String text, Object element) {
+ if (decorate(element)) {
+ return text + " " + ENTRY_SUFFIX;
+ } else
+ return text;
+ }
+
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
index 7e7a55b5..23e79fe9 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java
@@ -1,153 +1,160 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.LocaleUtils;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-
-public class AddLanguageDialoge extends Dialog{
- private Locale locale;
- private Shell shell;
-
- private Text titelText;
- private Text descriptionText;
- private Combo cmbLanguage;
- private Text language;
- private Text country;
- private Text variant;
-
-
-
-
- public AddLanguageDialoge(Shell parentShell){
- super(parentShell);
- shell = parentShell;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND);
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- GridLayout layout = new GridLayout(1,true);
- dialogArea.setLayout(layout);
-
- initDescription(titelArea);
- initCombo(dialogArea);
- initTextArea(dialogArea);
-
- titelArea.pack();
- dialogArea.pack();
- parent.pack();
-
- return dialogArea;
- }
-
- private void initDescription(Composite titelArea) {
- titelArea.setEnabled(false);
- titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true, 1, 1));
- titelArea.setLayout(new GridLayout(1, true));
- titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255));
-
- titelText = new Text(titelArea, SWT.LEFT);
- titelText.setFont(new Font(shell.getDisplay(),shell.getFont().getFontData()[0].getName(), 11, SWT.BOLD));
- titelText.setText("Please, specify the desired language");
-
- descriptionText = new Text(titelArea, SWT.WRAP);
- descriptionText.setLayoutData(new GridData(450, 60)); //TODO improve
- descriptionText.setText("Note: " +
- "In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. "+
- "If the locale is just provided of a ResourceBundle, no new file will be created.");
- }
-
- private void initCombo(Composite dialogArea) {
- cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN);
- cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
-
- final Locale[] locales = Locale.getAvailableLocales();
- final Set<Locale> localeSet = new HashSet<Locale>();
- List<String> localeNames = new LinkedList<String>();
-
- for (Locale l : locales){
- localeNames.add(l.getDisplayName());
- localeSet.add(l);
- }
-
- Collections.sort(localeNames);
-
- String[] s= new String[localeNames.size()];
- cmbLanguage.setItems(localeNames.toArray(s));
- cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0);
-
- cmbLanguage.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int selectIndex = ((Combo)e.getSource()).getSelectionIndex();
- if (!cmbLanguage.getItem(selectIndex).equals(ResourceBundleManager.defaultLocaleTag)){
- Locale l = LocaleUtils.getLocaleByDisplayName(localeSet, cmbLanguage.getItem(selectIndex));
-
- language.setText(l.getLanguage());
- country.setText(l.getCountry());
- variant.setText(l.getVariant());
- }else {
- language.setText("");
- country.setText("");
- variant.setText("");
- }
- }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // TODO Auto-generated method stub
- }
- });
- }
-
- private void initTextArea(Composite dialogArea) {
- final Group group = new Group (dialogArea, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
- group.setLayout(new GridLayout(3, true));
- group.setText("Locale");
-
- Label languageLabel = new Label(group, SWT.SINGLE);
- languageLabel.setText("Language");
- Label countryLabel = new Label(group, SWT.SINGLE);
- countryLabel.setText("Country");
- Label variantLabel = new Label(group, SWT.SINGLE);
- variantLabel.setText("Variant");
-
- language = new Text(group, SWT.SINGLE);
- country = new Text(group, SWT.SINGLE);
- variant = new Text(group, SWT.SINGLE);
- }
-
- @Override
- protected void okPressed() {
- locale = new Locale(language.getText(), country.getText(), variant.getText());
-
- super.okPressed();
- }
-
- public Locale getSelectedLanguage() {
- return locale;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.LocaleUtils;
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+
+public class AddLanguageDialoge extends Dialog{
+ private Locale locale;
+ private Shell shell;
+
+ private Text titelText;
+ private Text descriptionText;
+ private Combo cmbLanguage;
+ private Text language;
+ private Text country;
+ private Text variant;
+
+
+
+
+ public AddLanguageDialoge(Shell parentShell){
+ super(parentShell);
+ shell = parentShell;
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND);
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ GridLayout layout = new GridLayout(1,true);
+ dialogArea.setLayout(layout);
+
+ initDescription(titelArea);
+ initCombo(dialogArea);
+ initTextArea(dialogArea);
+
+ titelArea.pack();
+ dialogArea.pack();
+ parent.pack();
+
+ return dialogArea;
+ }
+
+ private void initDescription(Composite titelArea) {
+ titelArea.setEnabled(false);
+ titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true, 1, 1));
+ titelArea.setLayout(new GridLayout(1, true));
+ titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255));
+
+ titelText = new Text(titelArea, SWT.LEFT);
+ titelText.setFont(new Font(shell.getDisplay(),shell.getFont().getFontData()[0].getName(), 11, SWT.BOLD));
+ titelText.setText("Please, specify the desired language");
+
+ descriptionText = new Text(titelArea, SWT.WRAP);
+ descriptionText.setLayoutData(new GridData(450, 60)); //TODO improve
+ descriptionText.setText("Note: " +
+ "In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. "+
+ "If the locale is just provided of a ResourceBundle, no new file will be created.");
+ }
+
+ private void initCombo(Composite dialogArea) {
+ cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN);
+ cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
+
+ final Locale[] locales = Locale.getAvailableLocales();
+ final Set<Locale> localeSet = new HashSet<Locale>();
+ List<String> localeNames = new LinkedList<String>();
+
+ for (Locale l : locales){
+ localeNames.add(l.getDisplayName());
+ localeSet.add(l);
+ }
+
+ Collections.sort(localeNames);
+
+ String[] s= new String[localeNames.size()];
+ cmbLanguage.setItems(localeNames.toArray(s));
+ cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0);
+
+ cmbLanguage.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ int selectIndex = ((Combo)e.getSource()).getSelectionIndex();
+ if (!cmbLanguage.getItem(selectIndex).equals(ResourceBundleManager.defaultLocaleTag)){
+ Locale l = LocaleUtils.getLocaleByDisplayName(localeSet, cmbLanguage.getItem(selectIndex));
+
+ language.setText(l.getLanguage());
+ country.setText(l.getCountry());
+ variant.setText(l.getVariant());
+ }else {
+ language.setText("");
+ country.setText("");
+ variant.setText("");
+ }
+ }
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
+ }
+
+ private void initTextArea(Composite dialogArea) {
+ final Group group = new Group (dialogArea, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
+ group.setLayout(new GridLayout(3, true));
+ group.setText("Locale");
+
+ Label languageLabel = new Label(group, SWT.SINGLE);
+ languageLabel.setText("Language");
+ Label countryLabel = new Label(group, SWT.SINGLE);
+ countryLabel.setText("Country");
+ Label variantLabel = new Label(group, SWT.SINGLE);
+ variantLabel.setText("Variant");
+
+ language = new Text(group, SWT.SINGLE);
+ country = new Text(group, SWT.SINGLE);
+ variant = new Text(group, SWT.SINGLE);
+ }
+
+ @Override
+ protected void okPressed() {
+ locale = new Locale(language.getText(), country.getText(), variant.getText());
+
+ super.okPressed();
+ }
+
+ public Locale getSelectedLanguage() {
+ return locale;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
index b24a007d..df3fd5fc 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java
@@ -1,60 +1,67 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-public class CreatePatternDialoge extends Dialog{
- private String pattern;
- private Text patternText;
-
-
- public CreatePatternDialoge(Shell shell) {
- this(shell,"");
- }
-
- public CreatePatternDialoge(Shell shell, String pattern) {
- super(shell);
- this.pattern = pattern;
-// setShellStyle(SWT.RESIZE);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1, true));
- composite.setLayoutData(new GridData(SWT.FILL,SWT.TOP, false, false));
-
- Label descriptionLabel = new Label(composite, SWT.NONE);
- descriptionLabel.setText("Enter a regular expression:");
-
- patternText = new Text(composite, SWT.WRAP | SWT.MULTI);
- GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false);
- gData.widthHint = 400;
- gData.heightHint = 60;
- patternText.setLayoutData(gData);
- patternText.setText(pattern);
-
-
-
- return composite;
- }
-
- @Override
- protected void okPressed() {
- pattern = patternText.getText();
-
- super.okPressed();
- }
-
- public String getPattern(){
- return pattern;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class CreatePatternDialoge extends Dialog{
+ private String pattern;
+ private Text patternText;
+
+
+ public CreatePatternDialoge(Shell shell) {
+ this(shell,"");
+ }
+
+ public CreatePatternDialoge(Shell shell, String pattern) {
+ super(shell);
+ this.pattern = pattern;
+// setShellStyle(SWT.RESIZE);
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(1, true));
+ composite.setLayoutData(new GridData(SWT.FILL,SWT.TOP, false, false));
+
+ Label descriptionLabel = new Label(composite, SWT.NONE);
+ descriptionLabel.setText("Enter a regular expression:");
+
+ patternText = new Text(composite, SWT.WRAP | SWT.MULTI);
+ GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false);
+ gData.widthHint = 400;
+ gData.heightHint = 60;
+ patternText.setLayoutData(gData);
+ patternText.setText(pattern);
+
+
+
+ return composite;
+ }
+
+ @Override
+ protected void okPressed() {
+ pattern = patternText.getText();
+
+ super.okPressed();
+ }
+
+ public String getPattern(){
+ return pattern;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
index b3cc8b72..ceb18a88 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
@@ -1,432 +1,439 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.model.exception.ResourceBundleException;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.LocaleUtils;
-import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-
-public class CreateResourceBundleEntryDialog extends TitleAreaDialog {
-
- private static int WIDTH_LEFT_COLUMN = 100;
-
- private static final String DEFAULT_KEY = "defaultkey";
-
- private String projectName;
-
- private Text txtKey;
- private Combo cmbRB;
- private Text txtDefaultText;
- private Combo cmbLanguage;
-
- private Button okButton;
- private Button cancelButton;
-
- /*** Dialog Model ***/
- String selectedRB = "";
- String selectedLocale = "";
- String selectedKey = "";
- String selectedDefaultText = "";
-
- /*** MODIFY LISTENER ***/
- ModifyListener rbModifyListener;
-
- public class DialogConfiguration {
-
- String projectName;
-
- String preselectedKey;
- String preselectedMessage;
- String preselectedBundle;
- String preselectedLocale;
-
- public String getProjectName() {
- return projectName;
- }
- public void setProjectName(String projectName) {
- this.projectName = projectName;
- }
- public String getPreselectedKey() {
- return preselectedKey;
- }
- public void setPreselectedKey(String preselectedKey) {
- this.preselectedKey = preselectedKey;
- }
- public String getPreselectedMessage() {
- return preselectedMessage;
- }
- public void setPreselectedMessage(String preselectedMessage) {
- this.preselectedMessage = preselectedMessage;
- }
- public String getPreselectedBundle() {
- return preselectedBundle;
- }
- public void setPreselectedBundle(String preselectedBundle) {
- this.preselectedBundle = preselectedBundle;
- }
- public String getPreselectedLocale() {
- return preselectedLocale;
- }
- public void setPreselectedLocale(String preselectedLocale) {
- this.preselectedLocale = preselectedLocale;
- }
-
- }
-
- public CreateResourceBundleEntryDialog(Shell parentShell) {
- super(parentShell);
- }
-
- public void setDialogConfiguration(DialogConfiguration config) {
- String preselectedKey = config.getPreselectedKey();
- this.selectedKey = preselectedKey != null ? preselectedKey.trim() : preselectedKey;
- if ("".equals(this.selectedKey)) {
- this.selectedKey = DEFAULT_KEY;
- }
-
- this.selectedDefaultText = config.getPreselectedMessage();
- this.selectedRB = config.getPreselectedBundle();
- this.selectedLocale = config.getPreselectedLocale();
- this.projectName = config.getProjectName();
- }
-
- public String getSelectedResourceBundle () {
- return selectedRB;
- }
-
- public String getSelectedKey () {
- return selectedKey;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructRBSection (dialogArea);
- constructDefaultSection (dialogArea);
- initContent ();
- return dialogArea;
- }
-
- protected void initContent() {
- cmbRB.removeAll();
- int iSel = -1;
- int index = 0;
-
- Collection<String> availableBundles = ResourceBundleManager.getManager(projectName).getResourceBundleNames();
-
- for (String bundle : availableBundles) {
- cmbRB.add(bundle);
- if (bundle.equals(selectedRB)) {
- cmbRB.select(index);
- iSel = index;
- cmbRB.setEnabled(false);
- }
- index ++;
- }
-
- if (availableBundles.size() > 0 && iSel < 0) {
- cmbRB.select(0);
- selectedRB = cmbRB.getText();
- cmbRB.setEnabled(true);
- }
-
- rbModifyListener = new ModifyListener() {
-
- @Override
- public void modifyText(ModifyEvent e) {
- selectedRB = cmbRB.getText();
- validate();
- }
- };
- cmbRB.removeModifyListener(rbModifyListener);
- cmbRB.addModifyListener(rbModifyListener);
-
-
- cmbRB.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- selectedLocale = "";
- updateAvailableLanguages();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- selectedLocale = "";
- updateAvailableLanguages();
- }
- });
- updateAvailableLanguages();
- validate();
- }
-
- protected void updateAvailableLanguages () {
- cmbLanguage.removeAll();
- String selectedBundle = cmbRB.getText();
-
- if ("".equals(selectedBundle.trim())) {
- return;
- }
-
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
-
- // Retrieve available locales for the selected resource-bundle
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- int index = 0;
- int iSel = -1;
- for (Locale l : manager.getProvidedLocales(selectedBundle)) {
- String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
- if (displayName.equals(selectedLocale))
- iSel = index;
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- if (index == iSel)
- cmbLanguage.select(iSel);
- index++;
- }
-
- if (locales.size() > 0) {
- cmbLanguage.select(0);
- selectedLocale = cmbLanguage.getText();
- }
-
- cmbLanguage.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedLocale = cmbLanguage.getText();
- validate();
- }
- });
- }
-
- protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
- }
-
- protected void constructRBSection(Composite parent) {
- final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- group.setText("Resource Bundle");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
- infoLabel.setText("Specify the key of the new resource as well as the Resource-Bundle in\n" +
- "which the resource" +
- "should be added.\n");
-
- // Schl�ssel
- final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblKey.setLayoutData(lblKeyGrid);
- lblKey.setText("Key:");
- txtKey = new Text (group, SWT.BORDER);
- txtKey.setText(selectedKey);
- // grey ouut textfield if there already is a preset key
- txtKey.setEditable(selectedKey.trim().length() == 0 || selectedKey.indexOf("[Platzhalter]")>=0 || selectedKey.equals(DEFAULT_KEY));
- txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- txtKey.addModifyListener(new ModifyListener() {
-
- @Override
- public void modifyText(ModifyEvent e) {
- selectedKey = txtKey.getText();
- validate();
- }
- });
-
- // Resource-Bundle
- final Label lblRB = new Label (group, SWT.NONE);
- lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblRB.setText("Resource-Bundle:");
-
- cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- }
-
- protected void constructDefaultSection(Composite parent) {
- final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1));
- group.setText("Default-Text");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
- infoLabel.setText("Define a default text for the specified resource. Moreover, you need to\n" +
- "select the locale for which the default text should be defined.");
-
- // Text
- final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblTextGrid.heightHint = 80;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Text:");
-
- txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER);
- txtDefaultText.setText(selectedDefaultText);
- txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
- txtDefaultText.addModifyListener(new ModifyListener() {
-
- @Override
- public void modifyText(ModifyEvent e) {
- selectedDefaultText = txtDefaultText.getText();
- validate();
- }
- });
-
- // Sprache
- final Label lblLanguage = new Label (group, SWT.NONE);
- lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblLanguage.setText("Language (Country):");
-
- cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- }
-
- @Override
- protected void okPressed() {
- super.okPressed();
- // TODO debug
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- // Insert new Resource-Bundle reference
- Locale locale = LocaleUtils.getLocaleByDisplayName( manager.getProvidedLocales(selectedRB), selectedLocale); // new Locale(""); // retrieve locale
-
- try {
- manager.addResourceBundleEntry (selectedRB, selectedKey, locale, selectedDefaultText);
- } catch (ResourceBundleException e) {
- Logger.logError(e);
- }
- }
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Create Resource-Bundle entry");
- }
-
- @Override
- public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("New Resource-Bundle entry");
- this.setMessage("Please, specify details about the new Resource-Bundle entry");
- }
-
- /**
- * Validates all inputs of the CreateResourceBundleEntryDialog
- */
- protected void validate () {
- // Check Resource-Bundle ids
- boolean keyValid = false;
- boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey);
- boolean rbValid = false;
- boolean textValid = false;
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- boolean localeValid = LocaleUtils.containsLocaleByDisplayName(manager.getProvidedLocales(selectedRB), selectedLocale);
-
- for (String rbId : manager.getResourceBundleNames()) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
-
- if (!manager.isResourceExisting(selectedRB, selectedKey))
- keyValid = true;
-
- if (selectedDefaultText.trim().length() > 0)
- textValid = true;
-
- // print Validation summary
- String errorMessage = null;
- if (selectedKey.trim().length() == 0)
- errorMessage = "No resource key specified.";
- else if (! keyValidChar)
- errorMessage = "The specified resource key contains invalid characters.";
- else if (! keyValid)
- errorMessage = "The specified resource key is already existing.";
- else if (! rbValid)
- errorMessage = "The specified Resource-Bundle does not exist.";
- else if (! localeValid)
- errorMessage = "The specified Locale does not exist for the selected Resource-Bundle.";
- else if (! textValid)
- errorMessage = "No default translation specified.";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
-
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
- close();
- }
- });
-
- okButton.setEnabled(true);
- cancelButton.setEnabled(true);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.exception.ResourceBundleException;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.LocaleUtils;
+import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+
+public class CreateResourceBundleEntryDialog extends TitleAreaDialog {
+
+ private static int WIDTH_LEFT_COLUMN = 100;
+
+ private static final String DEFAULT_KEY = "defaultkey";
+
+ private String projectName;
+
+ private Text txtKey;
+ private Combo cmbRB;
+ private Text txtDefaultText;
+ private Combo cmbLanguage;
+
+ private Button okButton;
+ private Button cancelButton;
+
+ /*** Dialog Model ***/
+ String selectedRB = "";
+ String selectedLocale = "";
+ String selectedKey = "";
+ String selectedDefaultText = "";
+
+ /*** MODIFY LISTENER ***/
+ ModifyListener rbModifyListener;
+
+ public class DialogConfiguration {
+
+ String projectName;
+
+ String preselectedKey;
+ String preselectedMessage;
+ String preselectedBundle;
+ String preselectedLocale;
+
+ public String getProjectName() {
+ return projectName;
+ }
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+ public String getPreselectedKey() {
+ return preselectedKey;
+ }
+ public void setPreselectedKey(String preselectedKey) {
+ this.preselectedKey = preselectedKey;
+ }
+ public String getPreselectedMessage() {
+ return preselectedMessage;
+ }
+ public void setPreselectedMessage(String preselectedMessage) {
+ this.preselectedMessage = preselectedMessage;
+ }
+ public String getPreselectedBundle() {
+ return preselectedBundle;
+ }
+ public void setPreselectedBundle(String preselectedBundle) {
+ this.preselectedBundle = preselectedBundle;
+ }
+ public String getPreselectedLocale() {
+ return preselectedLocale;
+ }
+ public void setPreselectedLocale(String preselectedLocale) {
+ this.preselectedLocale = preselectedLocale;
+ }
+
+ }
+
+ public CreateResourceBundleEntryDialog(Shell parentShell) {
+ super(parentShell);
+ }
+
+ public void setDialogConfiguration(DialogConfiguration config) {
+ String preselectedKey = config.getPreselectedKey();
+ this.selectedKey = preselectedKey != null ? preselectedKey.trim() : preselectedKey;
+ if ("".equals(this.selectedKey)) {
+ this.selectedKey = DEFAULT_KEY;
+ }
+
+ this.selectedDefaultText = config.getPreselectedMessage();
+ this.selectedRB = config.getPreselectedBundle();
+ this.selectedLocale = config.getPreselectedLocale();
+ this.projectName = config.getProjectName();
+ }
+
+ public String getSelectedResourceBundle () {
+ return selectedRB;
+ }
+
+ public String getSelectedKey () {
+ return selectedKey;
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout (dialogArea);
+ constructRBSection (dialogArea);
+ constructDefaultSection (dialogArea);
+ initContent ();
+ return dialogArea;
+ }
+
+ protected void initContent() {
+ cmbRB.removeAll();
+ int iSel = -1;
+ int index = 0;
+
+ Collection<String> availableBundles = ResourceBundleManager.getManager(projectName).getResourceBundleNames();
+
+ for (String bundle : availableBundles) {
+ cmbRB.add(bundle);
+ if (bundle.equals(selectedRB)) {
+ cmbRB.select(index);
+ iSel = index;
+ cmbRB.setEnabled(false);
+ }
+ index ++;
+ }
+
+ if (availableBundles.size() > 0 && iSel < 0) {
+ cmbRB.select(0);
+ selectedRB = cmbRB.getText();
+ cmbRB.setEnabled(true);
+ }
+
+ rbModifyListener = new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ };
+ cmbRB.removeModifyListener(rbModifyListener);
+ cmbRB.addModifyListener(rbModifyListener);
+
+
+ cmbRB.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ selectedLocale = "";
+ updateAvailableLanguages();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ selectedLocale = "";
+ updateAvailableLanguages();
+ }
+ });
+ updateAvailableLanguages();
+ validate();
+ }
+
+ protected void updateAvailableLanguages () {
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
+
+ if ("".equals(selectedBundle.trim())) {
+ return;
+ }
+
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ int index = 0;
+ int iSel = -1;
+ for (Locale l : manager.getProvidedLocales(selectedBundle)) {
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
+ if (displayName.equals(selectedLocale))
+ iSel = index;
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ if (index == iSel)
+ cmbLanguage.select(iSel);
+ index++;
+ }
+
+ if (locales.size() > 0) {
+ cmbLanguage.select(0);
+ selectedLocale = cmbLanguage.getText();
+ }
+
+ cmbLanguage.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedLocale = cmbLanguage.getText();
+ validate();
+ }
+ });
+ }
+
+ protected void initLayout(Composite parent) {
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
+ }
+
+ protected void constructRBSection(Composite parent) {
+ final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ group.setText("Resource Bundle");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+
+ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+
+ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+ infoLabel.setText("Specify the key of the new resource as well as the Resource-Bundle in\n" +
+ "which the resource" +
+ "should be added.\n");
+
+ // Schl�ssel
+ final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
+ GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+ lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblKey.setLayoutData(lblKeyGrid);
+ lblKey.setText("Key:");
+ txtKey = new Text (group, SWT.BORDER);
+ txtKey.setText(selectedKey);
+ // grey ouut textfield if there already is a preset key
+ txtKey.setEditable(selectedKey.trim().length() == 0 || selectedKey.indexOf("[Platzhalter]")>=0 || selectedKey.equals(DEFAULT_KEY));
+ txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ txtKey.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedKey = txtKey.getText();
+ validate();
+ }
+ });
+
+ // Resource-Bundle
+ final Label lblRB = new Label (group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
+
+ cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ }
+
+ protected void constructDefaultSection(Composite parent) {
+ final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1));
+ group.setText("Default-Text");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+
+ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+
+ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+ infoLabel.setText("Define a default text for the specified resource. Moreover, you need to\n" +
+ "select the locale for which the default text should be defined.");
+
+ // Text
+ final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+ lblTextGrid.heightHint = 80;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Text:");
+
+ txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER);
+ txtDefaultText.setText(selectedDefaultText);
+ txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
+ txtDefaultText.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedDefaultText = txtDefaultText.getText();
+ validate();
+ }
+ });
+
+ // Sprache
+ final Label lblLanguage = new Label (group, SWT.NONE);
+ lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
+ lblLanguage.setText("Language (Country):");
+
+ cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ }
+
+ @Override
+ protected void okPressed() {
+ super.okPressed();
+ // TODO debug
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+ // Insert new Resource-Bundle reference
+ Locale locale = LocaleUtils.getLocaleByDisplayName( manager.getProvidedLocales(selectedRB), selectedLocale); // new Locale(""); // retrieve locale
+
+ try {
+ manager.addResourceBundleEntry (selectedRB, selectedKey, locale, selectedDefaultText);
+ } catch (ResourceBundleException e) {
+ Logger.logError(e);
+ }
+ }
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Create Resource-Bundle entry");
+ }
+
+ @Override
+ public void create() {
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("New Resource-Bundle entry");
+ this.setMessage("Please, specify details about the new Resource-Bundle entry");
+ }
+
+ /**
+ * Validates all inputs of the CreateResourceBundleEntryDialog
+ */
+ protected void validate () {
+ // Check Resource-Bundle ids
+ boolean keyValid = false;
+ boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey);
+ boolean rbValid = false;
+ boolean textValid = false;
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+ boolean localeValid = LocaleUtils.containsLocaleByDisplayName(manager.getProvidedLocales(selectedRB), selectedLocale);
+
+ for (String rbId : manager.getResourceBundleNames()) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
+
+ if (!manager.isResourceExisting(selectedRB, selectedKey))
+ keyValid = true;
+
+ if (selectedDefaultText.trim().length() > 0)
+ textValid = true;
+
+ // print Validation summary
+ String errorMessage = null;
+ if (selectedKey.trim().length() == 0)
+ errorMessage = "No resource key specified.";
+ else if (! keyValidChar)
+ errorMessage = "The specified resource key contains invalid characters.";
+ else if (! keyValid)
+ errorMessage = "The specified resource key is already existing.";
+ else if (! rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist.";
+ else if (! localeValid)
+ errorMessage = "The specified Locale does not exist for the selected Resource-Bundle.";
+ else if (! textValid)
+ errorMessage = "No default translation specified.";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
+
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
+ }
+
+ @Override
+ protected void createButtonsForButtonBar(Composite parent) {
+ okButton = createButton (parent, OK, "Ok", true);
+ okButton.addSelectionListener (new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
+
+ cancelButton = createButton (parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener (new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode (CANCEL);
+ close();
+ }
+ });
+
+ okButton.setEnabled(true);
+ cancelButton.setEnabled(true);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
index 0502a5ae..f29ac103 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java
@@ -1,114 +1,121 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ListDialog;
-
-
-public class FragmentProjectSelectionDialog extends ListDialog{
- private IProject hostproject;
- private List<IProject> allProjects;
-
-
- public FragmentProjectSelectionDialog(Shell parent, IProject hostproject, List<IProject> fragmentprojects){
- super(parent);
- this.hostproject = hostproject;
- this.allProjects = new ArrayList<IProject>(fragmentprojects);
- allProjects.add(0,hostproject);
-
- init();
- }
-
- private void init() {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following plug-ins:");
- this.setTitle("Project Selector");
- this.setContentProvider(new IProjectContentProvider());
- this.setLabelProvider(new IProjectLabelProvider());
-
- this.setInput(allProjects);
- }
-
- public IProject getSelectedProject() {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (IProject) selection[0];
- return null;
- }
-
-
- //private classes--------------------------------------------------------
- class IProjectContentProvider implements IStructuredContentProvider {
-
- @Override
- public Object[] getElements(Object inputElement) {
- List<IProject> resources = (List<IProject>) inputElement;
- return resources.toArray();
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
- }
-
- }
-
- class IProjectLabelProvider implements ILabelProvider {
-
- @Override
- public Image getImage(Object element) {
- return PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_OBJ_PROJECT);
- }
-
- @Override
- public String getText(Object element) {
- IProject p = ((IProject) element);
- String text = p.getName();
- if (p.equals(hostproject)) text += " [host project]";
- else text += " [fragment project]";
- return text;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.dialogs.ListDialog;
+
+
+public class FragmentProjectSelectionDialog extends ListDialog{
+ private IProject hostproject;
+ private List<IProject> allProjects;
+
+
+ public FragmentProjectSelectionDialog(Shell parent, IProject hostproject, List<IProject> fragmentprojects){
+ super(parent);
+ this.hostproject = hostproject;
+ this.allProjects = new ArrayList<IProject>(fragmentprojects);
+ allProjects.add(0,hostproject);
+
+ init();
+ }
+
+ private void init() {
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following plug-ins:");
+ this.setTitle("Project Selector");
+ this.setContentProvider(new IProjectContentProvider());
+ this.setLabelProvider(new IProjectLabelProvider());
+
+ this.setInput(allProjects);
+ }
+
+ public IProject getSelectedProject() {
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (IProject) selection[0];
+ return null;
+ }
+
+
+ //private classes--------------------------------------------------------
+ class IProjectContentProvider implements IStructuredContentProvider {
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ List<IProject> resources = (List<IProject>) inputElement;
+ return resources.toArray();
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
+ }
+
+ }
+
+ class IProjectLabelProvider implements ILabelProvider {
+
+ @Override
+ public Image getImage(Object element) {
+ return PlatformUI.getWorkbench().getSharedImages().getImage(
+ ISharedImages.IMG_OBJ_PROJECT);
+ }
+
+ @Override
+ public String getText(Object element) {
+ IProject p = ((IProject) element);
+ String text = p.getName();
+ if (p.equals(hostproject)) text += " [host project]";
+ else text += " [fragment project]";
+ return text;
+ }
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
index 982e24de..5388f8a8 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
@@ -1,130 +1,137 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-public class GenerateBundleAccessorDialog extends TitleAreaDialog {
-
- private static int WIDTH_LEFT_COLUMN = 100;
-
- private Text bundleAccessor;
- private Text packageName;
-
- public GenerateBundleAccessorDialog(Shell parentShell) {
- super(parentShell);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructBASection (dialogArea);
- //constructDefaultSection (dialogArea);
- initContent ();
- return dialogArea;
- }
-
- protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
- }
-
- protected void constructBASection(Composite parent) {
- final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- group.setText("Resource Bundle");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
- infoLabel.setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
-
- // Schl�ssel
- final Label lblBA = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblBAGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblBA.setLayoutData(lblBAGrid);
- lblBA.setText("Class-Name:");
-
- bundleAccessor = new Text (group, SWT.BORDER);
- bundleAccessor.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
-
- // Resource-Bundle
- final Label lblPkg = new Label (group, SWT.NONE);
- lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblPkg.setText("Package:");
-
- packageName = new Text (group, SWT.BORDER);
- packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- }
-
- protected void initContent () {
- bundleAccessor.setText("BundleAccessor");
- packageName.setText("a.b");
- }
-
- /*
- protected void constructDefaultSection(Composite parent) {
- final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1));
- group.setText("Basis-Text");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
- infoLabel.setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
-
- // Text
- final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblTextGrid.heightHint = 80;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Text:");
-
- txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER);
- txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
-
- // Sprache
- final Label lblLanguage = new Label (group, SWT.NONE);
- lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblLanguage.setText("Sprache (Land):");
-
- cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- } */
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Create Resource-Bundle Accessor");
- }
-
-
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+public class GenerateBundleAccessorDialog extends TitleAreaDialog {
+
+ private static int WIDTH_LEFT_COLUMN = 100;
+
+ private Text bundleAccessor;
+ private Text packageName;
+
+ public GenerateBundleAccessorDialog(Shell parentShell) {
+ super(parentShell);
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout (dialogArea);
+ constructBASection (dialogArea);
+ //constructDefaultSection (dialogArea);
+ initContent ();
+ return dialogArea;
+ }
+
+ protected void initLayout(Composite parent) {
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
+ }
+
+ protected void constructBASection(Composite parent) {
+ final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ group.setText("Resource Bundle");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+
+ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+
+ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+ infoLabel.setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
+
+ // Schl�ssel
+ final Label lblBA = new Label (group, SWT.NONE | SWT.RIGHT);
+ GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+ lblBAGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblBA.setLayoutData(lblBAGrid);
+ lblBA.setText("Class-Name:");
+
+ bundleAccessor = new Text (group, SWT.BORDER);
+ bundleAccessor.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+
+ // Resource-Bundle
+ final Label lblPkg = new Label (group, SWT.NONE);
+ lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
+ lblPkg.setText("Package:");
+
+ packageName = new Text (group, SWT.BORDER);
+ packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ }
+
+ protected void initContent () {
+ bundleAccessor.setText("BundleAccessor");
+ packageName.setText("a.b");
+ }
+
+ /*
+ protected void constructDefaultSection(Composite parent) {
+ final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1));
+ group.setText("Basis-Text");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+
+ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+
+ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
+ infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+ infoLabel.setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.");
+
+ // Text
+ final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+ lblTextGrid.heightHint = 80;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Text:");
+
+ txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER);
+ txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1));
+
+ // Sprache
+ final Label lblLanguage = new Label (group, SWT.NONE);
+ lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
+ lblLanguage.setText("Sprache (Land):");
+
+ cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ } */
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Create Resource-Bundle Accessor");
+ }
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
index d5c2a4eb..13ac24a9 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java
@@ -1,429 +1,436 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.ResourceSelector;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-
-public class QueryResourceBundleEntryDialog extends TitleAreaDialog {
-
- private static int WIDTH_LEFT_COLUMN = 100;
- private static int SEARCH_FULLTEXT = 0;
- private static int SEARCH_KEY = 1;
-
- private ResourceBundleManager manager;
- private Collection<String> availableBundles;
- private int searchOption = SEARCH_FULLTEXT;
- private String resourceBundle = "";
-
- private Combo cmbRB;
-
- private Text txtKey;
- private Button btSearchText;
- private Button btSearchKey;
- private Combo cmbLanguage;
- private ResourceSelector resourceSelector;
- private Text txtPreviewText;
-
- private Button okButton;
- private Button cancelButton;
-
- /*** DIALOG MODEL ***/
- private String selectedRB = "";
- private String preselectedRB = "";
- private Locale selectedLocale = null;
- private String selectedKey = "";
-
-
- public QueryResourceBundleEntryDialog(Shell parentShell, ResourceBundleManager manager, String bundleName) {
- super(parentShell);
- this.manager = manager;
- // init available resource bundles
- this.availableBundles = manager.getResourceBundleNames();
- this.preselectedRB = bundleName;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructSearchSection (dialogArea);
- initContent ();
- return dialogArea;
- }
-
- protected void initContent() {
- // init available resource bundles
- cmbRB.removeAll();
- int i = 0;
- for (String bundle : availableBundles) {
- cmbRB.add(bundle);
- if (bundle.equals(preselectedRB)) {
- cmbRB.select(i);
- cmbRB.setEnabled(false);
- }
- i++;
- }
-
- if (availableBundles.size() > 0) {
- if (preselectedRB.trim().length() == 0) {
- cmbRB.select(0);
- cmbRB.setEnabled(true);
- }
- }
-
- cmbRB.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
- }
- });
-
- // init available translations
- //updateAvailableLanguages();
-
- // init resource selector
- updateResourceSelector();
-
- // update search options
- updateSearchOptions();
- }
-
- protected void updateResourceSelector () {
- resourceBundle = cmbRB.getText();
- resourceSelector.setResourceBundle(resourceBundle);
- }
-
- protected void updateSearchOptions () {
- searchOption = (btSearchKey.getSelection() ? SEARCH_KEY : SEARCH_FULLTEXT);
-// cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
-// lblLanguage.setEnabled(cmbLanguage.getEnabled());
-
- // update ResourceSelector
- resourceSelector.setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT : ResourceSelector.DISPLAY_KEYS);
- }
-
- protected void updateAvailableLanguages () {
- cmbLanguage.removeAll();
- String selectedBundle = cmbRB.getText();
-
- if (selectedBundle.trim().equals(""))
- return;
-
- // Retrieve available locales for the selected resource-bundle
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- for (Locale l : locales) {
- String displayName = l.getDisplayName();
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- }
-
-// if (locales.size() > 0) {
-// cmbLanguage.select(0);
- updateSelectedLocale();
-// }
- }
-
- protected void updateSelectedLocale () {
- String selectedBundle = cmbRB.getText();
-
- if (selectedBundle.trim().equals(""))
- return;
-
- Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
- Iterator<Locale> it = locales.iterator();
- String selectedLocale = cmbLanguage.getText();
- while (it.hasNext()) {
- Locale l = it.next();
- if (l.getDisplayName().equals(selectedLocale)) {
- resourceSelector.setDisplayLocale(l);
- break;
- }
- }
- }
-
- protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
- }
-
- protected void constructSearchSection (Composite parent) {
- final Group group = new Group (parent, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- group.setText("Resource selection");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
- // TODO export as help text
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- GridData infoGrid = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
- infoGrid.heightHint = 70;
- infoLabel.setLayoutData(infoGrid);
- infoLabel.setText("Select the resource that needs to be refrenced. This is achieved in two\n" +
- "steps. First select the Resource-Bundle in which the resource is located. \n" +
- "In a last step you need to choose the required resource.");
-
- // Resource-Bundle
- final Label lblRB = new Label (group, SWT.NONE);
- lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblRB.setText("Resource-Bundle:");
-
- cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- cmbRB.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedRB = cmbRB.getText();
- validate();
- }
- });
-
- // Search-Options
- final Label spacer2 = new Label (group, SWT.NONE | SWT.LEFT);
- spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- Composite searchOptions = new Composite(group, SWT.NONE);
- searchOptions.setLayout(new GridLayout (2, true));
-
- btSearchText = new Button (searchOptions, SWT.RADIO);
- btSearchText.setText("Full-text");
- btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
- btSearchText.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
-
- btSearchKey = new Button (searchOptions, SWT.RADIO);
- btSearchKey.setText("Key");
- btSearchKey.setSelection(searchOption == SEARCH_KEY);
- btSearchKey.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
-
- // Sprache
-// lblLanguage = new Label (group, SWT.NONE);
-// lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
-// lblLanguage.setText("Language (Country):");
-//
-// cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
-// cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
-// cmbLanguage.addSelectionListener(new SelectionListener () {
-//
-// @Override
-// public void widgetDefaultSelected(SelectionEvent e) {
-// updateSelectedLocale();
-// }
-//
-// @Override
-// public void widgetSelected(SelectionEvent e) {
-// updateSelectedLocale();
-// }
-//
-// });
-// cmbLanguage.addModifyListener(new ModifyListener() {
-// @Override
-// public void modifyText(ModifyEvent e) {
-// selectedLocale = LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), cmbLanguage.getText());
-// validate();
-// }
-// });
-
- // Filter
- final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
- lblKey.setLayoutData(lblKeyGrid);
- lblKey.setText("Filter:");
-
- txtKey = new Text (group, SWT.BORDER);
- txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
-
- // Add selector for property keys
- final Label lblKeys = new Label (group, SWT.NONE);
- lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1));
- lblKeys.setText("Resource:");
-
- resourceSelector = new ResourceSelector (group, SWT.NONE);
-
- resourceSelector.setProjectName(manager.getProject().getName());
- resourceSelector.setResourceBundle(cmbRB.getText());
- resourceSelector.setDisplayMode(searchOption);
-
- GridData resourceSelectionData = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1);
- resourceSelectionData.heightHint = 150;
- resourceSelectionData.widthHint = 400;
- resourceSelector.setLayoutData(resourceSelectionData);
- resourceSelector.addSelectionChangedListener(new IResourceSelectionListener() {
-
- @Override
- public void selectionChanged(ResourceSelectionEvent e) {
- selectedKey = e.getSelectedKey();
- updatePreviewLabel(e.getSelectionSummary());
- validate();
- }
- });
-
-// final Label spacer = new Label (group, SWT.SEPARATOR | SWT.HORIZONTAL);
-// spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1));
-
- // Preview
- final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblTextGrid.heightHint = 120;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Preview:");
-
- txtPreviewText = new Text (group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
- txtPreviewText.setEditable(false);
- GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1);
- txtPreviewText.setLayoutData(lblTextGrid2);
- }
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Insert Resource-Bundle-Reference");
- }
-
- @Override
- public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("Reference a Resource");
- this.setMessage("Please, specify details about the required Resource-Bundle reference");
- }
-
- protected void updatePreviewLabel (String previewText) {
- txtPreviewText.setText(previewText);
- }
-
- protected void validate () {
- // Check Resource-Bundle ids
- boolean rbValid = false;
- boolean localeValid = false;
- boolean keyValid = false;
-
- for (String rbId : this.availableBundles) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
-
- if (selectedLocale != null)
- localeValid = true;
-
- if (manager.isResourceExisting(selectedRB, selectedKey))
- keyValid = true;
-
- // print Validation summary
- String errorMessage = null;
- if (! rbValid)
- errorMessage = "The specified Resource-Bundle does not exist";
-// else if (! localeValid)
-// errorMessage = "The specified Locale does not exist for the selecte Resource-Bundle";
- else if (! keyValid)
- errorMessage = "No resource selected";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
-
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
- close();
- }
- });
-
- okButton.setEnabled(false);
- cancelButton.setEnabled(true);
- }
-
- public String getSelectedResourceBundle () {
- return selectedRB;
- }
-
- public String getSelectedResource () {
- return selectedKey;
- }
-
- public Locale getSelectedLocale () {
- return selectedLocale;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.ResourceSelector;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+
+public class QueryResourceBundleEntryDialog extends TitleAreaDialog {
+
+ private static int WIDTH_LEFT_COLUMN = 100;
+ private static int SEARCH_FULLTEXT = 0;
+ private static int SEARCH_KEY = 1;
+
+ private ResourceBundleManager manager;
+ private Collection<String> availableBundles;
+ private int searchOption = SEARCH_FULLTEXT;
+ private String resourceBundle = "";
+
+ private Combo cmbRB;
+
+ private Text txtKey;
+ private Button btSearchText;
+ private Button btSearchKey;
+ private Combo cmbLanguage;
+ private ResourceSelector resourceSelector;
+ private Text txtPreviewText;
+
+ private Button okButton;
+ private Button cancelButton;
+
+ /*** DIALOG MODEL ***/
+ private String selectedRB = "";
+ private String preselectedRB = "";
+ private Locale selectedLocale = null;
+ private String selectedKey = "";
+
+
+ public QueryResourceBundleEntryDialog(Shell parentShell, ResourceBundleManager manager, String bundleName) {
+ super(parentShell);
+ this.manager = manager;
+ // init available resource bundles
+ this.availableBundles = manager.getResourceBundleNames();
+ this.preselectedRB = bundleName;
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout (dialogArea);
+ constructSearchSection (dialogArea);
+ initContent ();
+ return dialogArea;
+ }
+
+ protected void initContent() {
+ // init available resource bundles
+ cmbRB.removeAll();
+ int i = 0;
+ for (String bundle : availableBundles) {
+ cmbRB.add(bundle);
+ if (bundle.equals(preselectedRB)) {
+ cmbRB.select(i);
+ cmbRB.setEnabled(false);
+ }
+ i++;
+ }
+
+ if (availableBundles.size() > 0) {
+ if (preselectedRB.trim().length() == 0) {
+ cmbRB.select(0);
+ cmbRB.setEnabled(true);
+ }
+ }
+
+ cmbRB.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ //updateAvailableLanguages();
+ updateResourceSelector ();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ //updateAvailableLanguages();
+ updateResourceSelector ();
+ }
+ });
+
+ // init available translations
+ //updateAvailableLanguages();
+
+ // init resource selector
+ updateResourceSelector();
+
+ // update search options
+ updateSearchOptions();
+ }
+
+ protected void updateResourceSelector () {
+ resourceBundle = cmbRB.getText();
+ resourceSelector.setResourceBundle(resourceBundle);
+ }
+
+ protected void updateSearchOptions () {
+ searchOption = (btSearchKey.getSelection() ? SEARCH_KEY : SEARCH_FULLTEXT);
+// cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
+// lblLanguage.setEnabled(cmbLanguage.getEnabled());
+
+ // update ResourceSelector
+ resourceSelector.setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT : ResourceSelector.DISPLAY_KEYS);
+ }
+
+ protected void updateAvailableLanguages () {
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
+
+ if (selectedBundle.trim().equals(""))
+ return;
+
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ for (Locale l : locales) {
+ String displayName = l.getDisplayName();
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ }
+
+// if (locales.size() > 0) {
+// cmbLanguage.select(0);
+ updateSelectedLocale();
+// }
+ }
+
+ protected void updateSelectedLocale () {
+ String selectedBundle = cmbRB.getText();
+
+ if (selectedBundle.trim().equals(""))
+ return;
+
+ Set<Locale> locales = manager.getProvidedLocales(selectedBundle);
+ Iterator<Locale> it = locales.iterator();
+ String selectedLocale = cmbLanguage.getText();
+ while (it.hasNext()) {
+ Locale l = it.next();
+ if (l.getDisplayName().equals(selectedLocale)) {
+ resourceSelector.setDisplayLocale(l);
+ break;
+ }
+ }
+ }
+
+ protected void initLayout(Composite parent) {
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
+ }
+
+ protected void constructSearchSection (Composite parent) {
+ final Group group = new Group (parent, SWT.NONE);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ group.setText("Resource selection");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+ // TODO export as help text
+
+ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+
+ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
+ GridData infoGrid = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
+ infoGrid.heightHint = 70;
+ infoLabel.setLayoutData(infoGrid);
+ infoLabel.setText("Select the resource that needs to be refrenced. This is achieved in two\n" +
+ "steps. First select the Resource-Bundle in which the resource is located. \n" +
+ "In a last step you need to choose the required resource.");
+
+ // Resource-Bundle
+ final Label lblRB = new Label (group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
+
+ cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ cmbRB.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ });
+
+ // Search-Options
+ final Label spacer2 = new Label (group, SWT.NONE | SWT.LEFT);
+ spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+
+ Composite searchOptions = new Composite(group, SWT.NONE);
+ searchOptions.setLayout(new GridLayout (2, true));
+
+ btSearchText = new Button (searchOptions, SWT.RADIO);
+ btSearchText.setText("Full-text");
+ btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
+ btSearchText.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
+
+ btSearchKey = new Button (searchOptions, SWT.RADIO);
+ btSearchKey.setText("Key");
+ btSearchKey.setSelection(searchOption == SEARCH_KEY);
+ btSearchKey.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
+
+ // Sprache
+// lblLanguage = new Label (group, SWT.NONE);
+// lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
+// lblLanguage.setText("Language (Country):");
+//
+// cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+// cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+// cmbLanguage.addSelectionListener(new SelectionListener () {
+//
+// @Override
+// public void widgetDefaultSelected(SelectionEvent e) {
+// updateSelectedLocale();
+// }
+//
+// @Override
+// public void widgetSelected(SelectionEvent e) {
+// updateSelectedLocale();
+// }
+//
+// });
+// cmbLanguage.addModifyListener(new ModifyListener() {
+// @Override
+// public void modifyText(ModifyEvent e) {
+// selectedLocale = LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), cmbLanguage.getText());
+// validate();
+// }
+// });
+
+ // Filter
+ final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
+ GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+ lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+ lblKey.setLayoutData(lblKeyGrid);
+ lblKey.setText("Filter:");
+
+ txtKey = new Text (group, SWT.BORDER);
+ txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+
+ // Add selector for property keys
+ final Label lblKeys = new Label (group, SWT.NONE);
+ lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1));
+ lblKeys.setText("Resource:");
+
+ resourceSelector = new ResourceSelector (group, SWT.NONE);
+
+ resourceSelector.setProjectName(manager.getProject().getName());
+ resourceSelector.setResourceBundle(cmbRB.getText());
+ resourceSelector.setDisplayMode(searchOption);
+
+ GridData resourceSelectionData = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1);
+ resourceSelectionData.heightHint = 150;
+ resourceSelectionData.widthHint = 400;
+ resourceSelector.setLayoutData(resourceSelectionData);
+ resourceSelector.addSelectionChangedListener(new IResourceSelectionListener() {
+
+ @Override
+ public void selectionChanged(ResourceSelectionEvent e) {
+ selectedKey = e.getSelectedKey();
+ updatePreviewLabel(e.getSelectionSummary());
+ validate();
+ }
+ });
+
+// final Label spacer = new Label (group, SWT.SEPARATOR | SWT.HORIZONTAL);
+// spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1));
+
+ // Preview
+ final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+ lblTextGrid.heightHint = 120;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Preview:");
+
+ txtPreviewText = new Text (group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
+ txtPreviewText.setEditable(false);
+ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1);
+ txtPreviewText.setLayoutData(lblTextGrid2);
+ }
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Insert Resource-Bundle-Reference");
+ }
+
+ @Override
+ public void create() {
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("Reference a Resource");
+ this.setMessage("Please, specify details about the required Resource-Bundle reference");
+ }
+
+ protected void updatePreviewLabel (String previewText) {
+ txtPreviewText.setText(previewText);
+ }
+
+ protected void validate () {
+ // Check Resource-Bundle ids
+ boolean rbValid = false;
+ boolean localeValid = false;
+ boolean keyValid = false;
+
+ for (String rbId : this.availableBundles) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
+
+ if (selectedLocale != null)
+ localeValid = true;
+
+ if (manager.isResourceExisting(selectedRB, selectedKey))
+ keyValid = true;
+
+ // print Validation summary
+ String errorMessage = null;
+ if (! rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist";
+// else if (! localeValid)
+// errorMessage = "The specified Locale does not exist for the selecte Resource-Bundle";
+ else if (! keyValid)
+ errorMessage = "No resource selected";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
+
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
+ }
+
+ @Override
+ protected void createButtonsForButtonBar(Composite parent) {
+ okButton = createButton (parent, OK, "Ok", true);
+ okButton.addSelectionListener (new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
+
+ cancelButton = createButton (parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener (new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode (CANCEL);
+ close();
+ }
+ });
+
+ okButton.setEnabled(false);
+ cancelButton.setEnabled(true);
+ }
+
+ public String getSelectedResourceBundle () {
+ return selectedRB;
+ }
+
+ public String getSelectedResource () {
+ return selectedKey;
+ }
+
+ public Locale getSelectedLocale () {
+ return selectedLocale;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
index af507158..ac950ffc 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java
@@ -1,111 +1,118 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ListDialog;
-
-
-public class RemoveLanguageDialoge extends ListDialog{
- private IProject project;
-
-
- public RemoveLanguageDialoge(IProject project, Shell shell) {
- super(shell);
- this.project=project;
-
- initDialog();
- }
-
- protected void initDialog () {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following languages to delete:");
- this.setTitle("Language Selector");
- this.setContentProvider(new RBContentProvider());
- this.setLabelProvider(new RBLabelProvider());
-
- this.setInput(ResourceBundleManager.getManager(project).getProjectProvidedLocales());
- }
-
- public Locale getSelectedLanguage() {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (Locale) selection[0];
- return null;
- }
-
-
- //private classes-------------------------------------------------------------------------------------
- class RBContentProvider implements IStructuredContentProvider {
-
- @Override
- public Object[] getElements(Object inputElement) {
- Set<Locale> resources = (Set<Locale>) inputElement;
- return resources.toArray();
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
-
- }
-
- }
-
- class RBLabelProvider implements ILabelProvider {
-
- @Override
- public Image getImage(Object element) {
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- }
-
- @Override
- public String getText(Object element) {
- Locale l = ((Locale) element);
- String text = l.getDisplayName();
- if (text==null || text.equals("")) text="default";
- else text += " - "+l.getLanguage()+" "+l.getCountry()+" "+l.getVariant();
- return text;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.dialogs.ListDialog;
+
+
+public class RemoveLanguageDialoge extends ListDialog{
+ private IProject project;
+
+
+ public RemoveLanguageDialoge(IProject project, Shell shell) {
+ super(shell);
+ this.project=project;
+
+ initDialog();
+ }
+
+ protected void initDialog () {
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following languages to delete:");
+ this.setTitle("Language Selector");
+ this.setContentProvider(new RBContentProvider());
+ this.setLabelProvider(new RBLabelProvider());
+
+ this.setInput(ResourceBundleManager.getManager(project).getProjectProvidedLocales());
+ }
+
+ public Locale getSelectedLanguage() {
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (Locale) selection[0];
+ return null;
+ }
+
+
+ //private classes-------------------------------------------------------------------------------------
+ class RBContentProvider implements IStructuredContentProvider {
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ Set<Locale> resources = (Set<Locale>) inputElement;
+ return resources.toArray();
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ class RBLabelProvider implements ILabelProvider {
+
+ @Override
+ public Image getImage(Object element) {
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ }
+
+ @Override
+ public String getText(Object element) {
+ Locale l = ((Locale) element);
+ String text = l.getDisplayName();
+ if (text==null || text.equals("")) text="default";
+ else text += " - "+l.getLanguage()+" "+l.getCountry()+" "+l.getVariant();
+ return text;
+ }
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
index b0f4f6df..2b076285 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java
@@ -1,436 +1,443 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.ResourceSelector;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-
-public class ResourceBundleEntrySelectionDialog extends TitleAreaDialog {
-
- private static int WIDTH_LEFT_COLUMN = 100;
- private static int SEARCH_FULLTEXT = 0;
- private static int SEARCH_KEY = 1;
-
- private String projectName;
- private String bundleName;
-
- private int searchOption = SEARCH_FULLTEXT;
- private String resourceBundle = "";
-
- private Combo cmbRB;
-
- private Button btSearchText;
- private Button btSearchKey;
- private Combo cmbLanguage;
- private ResourceSelector resourceSelector;
- private Text txtPreviewText;
-
- private Button okButton;
- private Button cancelButton;
-
- /*** DIALOG MODEL ***/
- private String selectedRB = "";
- private String preselectedRB = "";
- private Locale selectedLocale = null;
- private String selectedKey = "";
-
-
- public ResourceBundleEntrySelectionDialog(Shell parentShell) {
- super(parentShell);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite dialogArea = (Composite) super.createDialogArea(parent);
- initLayout (dialogArea);
- constructSearchSection (dialogArea);
- initContent ();
- return dialogArea;
- }
-
- protected void initContent() {
- // init available resource bundles
- cmbRB.removeAll();
- int i = 0;
- for (String bundle : ResourceBundleManager.getManager(projectName).getResourceBundleNames()) {
- cmbRB.add(bundle);
- if (bundle.equals(preselectedRB)) {
- cmbRB.select(i);
- cmbRB.setEnabled(false);
- }
- i++;
- }
-
- if (ResourceBundleManager.getManager(projectName).getResourceBundleNames().size() > 0) {
- if (preselectedRB.trim().length() == 0) {
- cmbRB.select(0);
- cmbRB.setEnabled(true);
- }
- }
-
- cmbRB.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- //updateAvailableLanguages();
- updateResourceSelector ();
- }
- });
-
- // init available translations
- //updateAvailableLanguages();
-
- // init resource selector
- updateResourceSelector();
-
- // update search options
- updateSearchOptions();
- }
-
- protected void updateResourceSelector () {
- resourceBundle = cmbRB.getText();
- resourceSelector.setResourceBundle(resourceBundle);
- }
-
- protected void updateSearchOptions () {
- searchOption = (btSearchKey.getSelection() ? SEARCH_KEY : SEARCH_FULLTEXT);
-// cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
-// lblLanguage.setEnabled(cmbLanguage.getEnabled());
-
- // update ResourceSelector
- resourceSelector.setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT : ResourceSelector.DISPLAY_KEYS);
- }
-
- protected void updateAvailableLanguages () {
- cmbLanguage.removeAll();
- String selectedBundle = cmbRB.getText();
-
- if (selectedBundle.trim().equals(""))
- return;
-
- // Retrieve available locales for the selected resource-bundle
- Set<Locale> locales = ResourceBundleManager.getManager(projectName).getProvidedLocales(selectedBundle);
- for (Locale l : locales) {
- String displayName = l.getDisplayName();
- if (displayName.equals(""))
- displayName = ResourceBundleManager.defaultLocaleTag;
- cmbLanguage.add(displayName);
- }
-
-// if (locales.size() > 0) {
-// cmbLanguage.select(0);
- updateSelectedLocale();
-// }
- }
-
- protected void updateSelectedLocale () {
- String selectedBundle = cmbRB.getText();
-
- if (selectedBundle.trim().equals(""))
- return;
-
- Set<Locale> locales = ResourceBundleManager.getManager(projectName).getProvidedLocales(selectedBundle);
- Iterator<Locale> it = locales.iterator();
- String selectedLocale = cmbLanguage.getText();
- while (it.hasNext()) {
- Locale l = it.next();
- if (l.getDisplayName().equals(selectedLocale)) {
- resourceSelector.setDisplayLocale(l);
- break;
- }
- }
- }
-
- protected void initLayout(Composite parent) {
- final GridLayout layout = new GridLayout(1, true);
- parent.setLayout(layout);
- }
-
- protected void constructSearchSection (Composite parent) {
- final Group group = new Group (parent, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- group.setText("Resource selection");
-
- // define grid data for this group
- GridData gridData = new GridData();
- gridData.horizontalAlignment = SWT.FILL;
- gridData.grabExcessHorizontalSpace = true;
- group.setLayoutData(gridData);
- group.setLayout(new GridLayout(2, false));
- // TODO export as help text
-
- final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
- spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
- GridData infoGrid = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
- infoGrid.heightHint = 70;
- infoLabel.setLayoutData(infoGrid);
- infoLabel.setText("Select the resource that needs to be refrenced. This is accomplished in two\n" +
- "steps. First select the Resource-Bundle in which the resource is located. \n" +
- "In a last step you need to choose a particular resource.");
-
- // Resource-Bundle
- final Label lblRB = new Label (group, SWT.NONE);
- lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
- lblRB.setText("Resource-Bundle:");
-
- cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
- cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
- cmbRB.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- selectedRB = cmbRB.getText();
- validate();
- }
- });
-
- // Search-Options
- final Label spacer2 = new Label (group, SWT.NONE | SWT.LEFT);
- spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
-
- Composite searchOptions = new Composite(group, SWT.NONE);
- searchOptions.setLayout(new GridLayout (2, true));
-
- btSearchText = new Button (searchOptions, SWT.RADIO);
- btSearchText.setText("Flat");
- btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
- btSearchText.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
-
- btSearchKey = new Button (searchOptions, SWT.RADIO);
- btSearchKey.setText("Hierarchical");
- btSearchKey.setSelection(searchOption == SEARCH_KEY);
- btSearchKey.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSearchOptions();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSearchOptions();
- }
- });
-
- // Sprache
-// lblLanguage = new Label (group, SWT.NONE);
-// lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
-// lblLanguage.setText("Language (Country):");
-//
-// cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
-// cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
-// cmbLanguage.addSelectionListener(new SelectionListener () {
-//
-// @Override
-// public void widgetDefaultSelected(SelectionEvent e) {
-// updateSelectedLocale();
-// }
-//
-// @Override
-// public void widgetSelected(SelectionEvent e) {
-// updateSelectedLocale();
-// }
-//
-// });
-// cmbLanguage.addModifyListener(new ModifyListener() {
-// @Override
-// public void modifyText(ModifyEvent e) {
-// selectedLocale = LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), cmbLanguage.getText());
-// validate();
-// }
-// });
-
- // Filter
-// final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
-// GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
-// lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
-// lblKey.setLayoutData(lblKeyGrid);
-// lblKey.setText("Filter:");
-//
-// txtKey = new Text (group, SWT.BORDER);
-// txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
-
- // Add selector for property keys
- final Label lblKeys = new Label (group, SWT.NONE);
- lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1));
- lblKeys.setText("Resource:");
-
- resourceSelector = new ResourceSelector (group, SWT.NONE);
-
- resourceSelector.setProjectName(projectName);
- resourceSelector.setResourceBundle(cmbRB.getText());
- resourceSelector.setDisplayMode(searchOption);
-
- GridData resourceSelectionData = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1);
- resourceSelectionData.heightHint = 150;
- resourceSelectionData.widthHint = 400;
- resourceSelector.setLayoutData(resourceSelectionData);
- resourceSelector.addSelectionChangedListener(new IResourceSelectionListener() {
-
- @Override
- public void selectionChanged(ResourceSelectionEvent e) {
- selectedKey = e.getSelectedKey();
- updatePreviewLabel(e.getSelectionSummary());
- validate();
- }
- });
-
-// final Label spacer = new Label (group, SWT.SEPARATOR | SWT.HORIZONTAL);
-// spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1));
-
- // Preview
- final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
- GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
- lblTextGrid.heightHint = 120;
- lblTextGrid.widthHint = 100;
- lblText.setLayoutData(lblTextGrid);
- lblText.setText("Preview:");
-
- txtPreviewText = new Text (group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
- txtPreviewText.setEditable(false);
- GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1);
- txtPreviewText.setLayoutData(lblTextGrid2);
- }
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText("Select Resource-Bundle entry");
- }
-
- @Override
- public void create() {
- // TODO Auto-generated method stub
- super.create();
- this.setTitle("Select a Resource-Bundle entry");
- this.setMessage("Please, select a resource of a particular Resource-Bundle");
- }
-
- protected void updatePreviewLabel (String previewText) {
- txtPreviewText.setText(previewText);
- }
-
- protected void validate () {
- // Check Resource-Bundle ids
- boolean rbValid = false;
- boolean localeValid = false;
- boolean keyValid = false;
-
- for (String rbId : ResourceBundleManager.getManager(projectName).getResourceBundleNames()) {
- if (rbId.equals(selectedRB)) {
- rbValid = true;
- break;
- }
- }
-
- if (selectedLocale != null)
- localeValid = true;
-
- if (ResourceBundleManager.getManager(projectName).isResourceExisting(selectedRB, selectedKey))
- keyValid = true;
-
- // print Validation summary
- String errorMessage = null;
- if (! rbValid)
- errorMessage = "The specified Resource-Bundle does not exist";
-// else if (! localeValid)
-// errorMessage = "The specified Locale does not exist for the selecte Resource-Bundle";
- else if (! keyValid)
- errorMessage = "No resource selected";
- else {
- if (okButton != null)
- okButton.setEnabled(true);
- }
-
- setErrorMessage(errorMessage);
- if (okButton != null && errorMessage != null)
- okButton.setEnabled(false);
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- okButton = createButton (parent, OK, "Ok", true);
- okButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- // Set return code
- setReturnCode(OK);
- close();
- }
- });
-
- cancelButton = createButton (parent, CANCEL, "Cancel", false);
- cancelButton.addSelectionListener (new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- setReturnCode (CANCEL);
- close();
- }
- });
-
- okButton.setEnabled(false);
- cancelButton.setEnabled(true);
- }
-
- public String getSelectedResourceBundle () {
- return selectedRB;
- }
-
- public String getSelectedResource () {
- return selectedKey;
- }
-
- public Locale getSelectedLocale () {
- return selectedLocale;
- }
-
- public void setProjectName(String projectName) {
- this.projectName = projectName;
- }
-
- public void setBundleName(String bundleName) {
- this.bundleName = bundleName;
-
- if (preselectedRB.isEmpty()) {
- preselectedRB = this.bundleName;
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.ResourceSelector;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipse.jface.dialogs.TitleAreaDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+
+
+public class ResourceBundleEntrySelectionDialog extends TitleAreaDialog {
+
+ private static int WIDTH_LEFT_COLUMN = 100;
+ private static int SEARCH_FULLTEXT = 0;
+ private static int SEARCH_KEY = 1;
+
+ private String projectName;
+ private String bundleName;
+
+ private int searchOption = SEARCH_FULLTEXT;
+ private String resourceBundle = "";
+
+ private Combo cmbRB;
+
+ private Button btSearchText;
+ private Button btSearchKey;
+ private Combo cmbLanguage;
+ private ResourceSelector resourceSelector;
+ private Text txtPreviewText;
+
+ private Button okButton;
+ private Button cancelButton;
+
+ /*** DIALOG MODEL ***/
+ private String selectedRB = "";
+ private String preselectedRB = "";
+ private Locale selectedLocale = null;
+ private String selectedKey = "";
+
+
+ public ResourceBundleEntrySelectionDialog(Shell parentShell) {
+ super(parentShell);
+ }
+
+ @Override
+ protected Control createDialogArea(Composite parent) {
+ Composite dialogArea = (Composite) super.createDialogArea(parent);
+ initLayout (dialogArea);
+ constructSearchSection (dialogArea);
+ initContent ();
+ return dialogArea;
+ }
+
+ protected void initContent() {
+ // init available resource bundles
+ cmbRB.removeAll();
+ int i = 0;
+ for (String bundle : ResourceBundleManager.getManager(projectName).getResourceBundleNames()) {
+ cmbRB.add(bundle);
+ if (bundle.equals(preselectedRB)) {
+ cmbRB.select(i);
+ cmbRB.setEnabled(false);
+ }
+ i++;
+ }
+
+ if (ResourceBundleManager.getManager(projectName).getResourceBundleNames().size() > 0) {
+ if (preselectedRB.trim().length() == 0) {
+ cmbRB.select(0);
+ cmbRB.setEnabled(true);
+ }
+ }
+
+ cmbRB.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ //updateAvailableLanguages();
+ updateResourceSelector ();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ //updateAvailableLanguages();
+ updateResourceSelector ();
+ }
+ });
+
+ // init available translations
+ //updateAvailableLanguages();
+
+ // init resource selector
+ updateResourceSelector();
+
+ // update search options
+ updateSearchOptions();
+ }
+
+ protected void updateResourceSelector () {
+ resourceBundle = cmbRB.getText();
+ resourceSelector.setResourceBundle(resourceBundle);
+ }
+
+ protected void updateSearchOptions () {
+ searchOption = (btSearchKey.getSelection() ? SEARCH_KEY : SEARCH_FULLTEXT);
+// cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT);
+// lblLanguage.setEnabled(cmbLanguage.getEnabled());
+
+ // update ResourceSelector
+ resourceSelector.setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT : ResourceSelector.DISPLAY_KEYS);
+ }
+
+ protected void updateAvailableLanguages () {
+ cmbLanguage.removeAll();
+ String selectedBundle = cmbRB.getText();
+
+ if (selectedBundle.trim().equals(""))
+ return;
+
+ // Retrieve available locales for the selected resource-bundle
+ Set<Locale> locales = ResourceBundleManager.getManager(projectName).getProvidedLocales(selectedBundle);
+ for (Locale l : locales) {
+ String displayName = l.getDisplayName();
+ if (displayName.equals(""))
+ displayName = ResourceBundleManager.defaultLocaleTag;
+ cmbLanguage.add(displayName);
+ }
+
+// if (locales.size() > 0) {
+// cmbLanguage.select(0);
+ updateSelectedLocale();
+// }
+ }
+
+ protected void updateSelectedLocale () {
+ String selectedBundle = cmbRB.getText();
+
+ if (selectedBundle.trim().equals(""))
+ return;
+
+ Set<Locale> locales = ResourceBundleManager.getManager(projectName).getProvidedLocales(selectedBundle);
+ Iterator<Locale> it = locales.iterator();
+ String selectedLocale = cmbLanguage.getText();
+ while (it.hasNext()) {
+ Locale l = it.next();
+ if (l.getDisplayName().equals(selectedLocale)) {
+ resourceSelector.setDisplayLocale(l);
+ break;
+ }
+ }
+ }
+
+ protected void initLayout(Composite parent) {
+ final GridLayout layout = new GridLayout(1, true);
+ parent.setLayout(layout);
+ }
+
+ protected void constructSearchSection (Composite parent) {
+ final Group group = new Group (parent, SWT.NONE);
+ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ group.setText("Resource selection");
+
+ // define grid data for this group
+ GridData gridData = new GridData();
+ gridData.horizontalAlignment = SWT.FILL;
+ gridData.grabExcessHorizontalSpace = true;
+ group.setLayoutData(gridData);
+ group.setLayout(new GridLayout(2, false));
+ // TODO export as help text
+
+ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT);
+ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+
+ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT);
+ GridData infoGrid = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
+ infoGrid.heightHint = 70;
+ infoLabel.setLayoutData(infoGrid);
+ infoLabel.setText("Select the resource that needs to be refrenced. This is accomplished in two\n" +
+ "steps. First select the Resource-Bundle in which the resource is located. \n" +
+ "In a last step you need to choose a particular resource.");
+
+ // Resource-Bundle
+ final Label lblRB = new Label (group, SWT.NONE);
+ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
+ lblRB.setText("Resource-Bundle:");
+
+ cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+ cmbRB.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ selectedRB = cmbRB.getText();
+ validate();
+ }
+ });
+
+ // Search-Options
+ final Label spacer2 = new Label (group, SWT.NONE | SWT.LEFT);
+ spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1));
+
+ Composite searchOptions = new Composite(group, SWT.NONE);
+ searchOptions.setLayout(new GridLayout (2, true));
+
+ btSearchText = new Button (searchOptions, SWT.RADIO);
+ btSearchText.setText("Flat");
+ btSearchText.setSelection(searchOption == SEARCH_FULLTEXT);
+ btSearchText.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
+
+ btSearchKey = new Button (searchOptions, SWT.RADIO);
+ btSearchKey.setText("Hierarchical");
+ btSearchKey.setSelection(searchOption == SEARCH_KEY);
+ btSearchKey.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSearchOptions();
+ }
+ });
+
+ // Sprache
+// lblLanguage = new Label (group, SWT.NONE);
+// lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1));
+// lblLanguage.setText("Language (Country):");
+//
+// cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE);
+// cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+// cmbLanguage.addSelectionListener(new SelectionListener () {
+//
+// @Override
+// public void widgetDefaultSelected(SelectionEvent e) {
+// updateSelectedLocale();
+// }
+//
+// @Override
+// public void widgetSelected(SelectionEvent e) {
+// updateSelectedLocale();
+// }
+//
+// });
+// cmbLanguage.addModifyListener(new ModifyListener() {
+// @Override
+// public void modifyText(ModifyEvent e) {
+// selectedLocale = LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), cmbLanguage.getText());
+// validate();
+// }
+// });
+
+ // Filter
+// final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT);
+// GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+// lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN;
+// lblKey.setLayoutData(lblKeyGrid);
+// lblKey.setText("Filter:");
+//
+// txtKey = new Text (group, SWT.BORDER);
+// txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1));
+
+ // Add selector for property keys
+ final Label lblKeys = new Label (group, SWT.NONE);
+ lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1));
+ lblKeys.setText("Resource:");
+
+ resourceSelector = new ResourceSelector (group, SWT.NONE);
+
+ resourceSelector.setProjectName(projectName);
+ resourceSelector.setResourceBundle(cmbRB.getText());
+ resourceSelector.setDisplayMode(searchOption);
+
+ GridData resourceSelectionData = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1);
+ resourceSelectionData.heightHint = 150;
+ resourceSelectionData.widthHint = 400;
+ resourceSelector.setLayoutData(resourceSelectionData);
+ resourceSelector.addSelectionChangedListener(new IResourceSelectionListener() {
+
+ @Override
+ public void selectionChanged(ResourceSelectionEvent e) {
+ selectedKey = e.getSelectedKey();
+ updatePreviewLabel(e.getSelectionSummary());
+ validate();
+ }
+ });
+
+// final Label spacer = new Label (group, SWT.SEPARATOR | SWT.HORIZONTAL);
+// spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1));
+
+ // Preview
+ final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT);
+ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+ lblTextGrid.heightHint = 120;
+ lblTextGrid.widthHint = 100;
+ lblText.setLayoutData(lblTextGrid);
+ lblText.setText("Preview:");
+
+ txtPreviewText = new Text (group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
+ txtPreviewText.setEditable(false);
+ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1);
+ txtPreviewText.setLayoutData(lblTextGrid2);
+ }
+
+ @Override
+ protected void configureShell(Shell newShell) {
+ super.configureShell(newShell);
+ newShell.setText("Select Resource-Bundle entry");
+ }
+
+ @Override
+ public void create() {
+ // TODO Auto-generated method stub
+ super.create();
+ this.setTitle("Select a Resource-Bundle entry");
+ this.setMessage("Please, select a resource of a particular Resource-Bundle");
+ }
+
+ protected void updatePreviewLabel (String previewText) {
+ txtPreviewText.setText(previewText);
+ }
+
+ protected void validate () {
+ // Check Resource-Bundle ids
+ boolean rbValid = false;
+ boolean localeValid = false;
+ boolean keyValid = false;
+
+ for (String rbId : ResourceBundleManager.getManager(projectName).getResourceBundleNames()) {
+ if (rbId.equals(selectedRB)) {
+ rbValid = true;
+ break;
+ }
+ }
+
+ if (selectedLocale != null)
+ localeValid = true;
+
+ if (ResourceBundleManager.getManager(projectName).isResourceExisting(selectedRB, selectedKey))
+ keyValid = true;
+
+ // print Validation summary
+ String errorMessage = null;
+ if (! rbValid)
+ errorMessage = "The specified Resource-Bundle does not exist";
+// else if (! localeValid)
+// errorMessage = "The specified Locale does not exist for the selecte Resource-Bundle";
+ else if (! keyValid)
+ errorMessage = "No resource selected";
+ else {
+ if (okButton != null)
+ okButton.setEnabled(true);
+ }
+
+ setErrorMessage(errorMessage);
+ if (okButton != null && errorMessage != null)
+ okButton.setEnabled(false);
+ }
+
+ @Override
+ protected void createButtonsForButtonBar(Composite parent) {
+ okButton = createButton (parent, OK, "Ok", true);
+ okButton.addSelectionListener (new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ // Set return code
+ setReturnCode(OK);
+ close();
+ }
+ });
+
+ cancelButton = createButton (parent, CANCEL, "Cancel", false);
+ cancelButton.addSelectionListener (new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ setReturnCode (CANCEL);
+ close();
+ }
+ });
+
+ okButton.setEnabled(false);
+ cancelButton.setEnabled(true);
+ }
+
+ public String getSelectedResourceBundle () {
+ return selectedRB;
+ }
+
+ public String getSelectedResource () {
+ return selectedKey;
+ }
+
+ public Locale getSelectedLocale () {
+ return selectedLocale;
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ public void setBundleName(String bundleName) {
+ this.bundleName = bundleName;
+
+ if (preselectedRB.isEmpty()) {
+ preselectedRB = this.bundleName;
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
index 64e8a924..862d9d9d 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
@@ -1,110 +1,117 @@
-package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
-
-import java.util.List;
-
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ListDialog;
-
-
-public class ResourceBundleSelectionDialog extends ListDialog {
-
- private IProject project;
-
- public ResourceBundleSelectionDialog(Shell parent, IProject project) {
- super(parent);
- this.project = project;
-
- initDialog ();
- }
-
- protected void initDialog () {
- this.setAddCancelButton(true);
- this.setMessage("Select one of the following Resource-Bundle to open:");
- this.setTitle("Resource-Bundle Selector");
- this.setContentProvider(new RBContentProvider());
- this.setLabelProvider(new RBLabelProvider());
- this.setBlockOnOpen(true);
-
- if (project != null)
- this.setInput(RBManager.getInstance(project).getMessagesBundleGroupNames());
- else
- this.setInput(RBManager.getAllMessagesBundleGroupNames());
- }
-
- public String getSelectedBundleId () {
- Object[] selection = this.getResult();
- if (selection != null && selection.length > 0)
- return (String) selection[0];
- return null;
- }
-
- class RBContentProvider implements IStructuredContentProvider {
-
- @Override
- public Object[] getElements(Object inputElement) {
- List<String> resources = (List<String>) inputElement;
- return resources.toArray();
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // TODO Auto-generated method stub
-
- }
-
- }
-
- class RBLabelProvider implements ILabelProvider {
-
- @Override
- public Image getImage(Object element) {
- // TODO Auto-generated method stub
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- }
-
- @Override
- public String getText(Object element) {
- // TODO Auto-generated method stub
- return ((String) element);
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.dialogs;
+
+import java.util.List;
+
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.dialogs.ListDialog;
+
+
+public class ResourceBundleSelectionDialog extends ListDialog {
+
+ private IProject project;
+
+ public ResourceBundleSelectionDialog(Shell parent, IProject project) {
+ super(parent);
+ this.project = project;
+
+ initDialog ();
+ }
+
+ protected void initDialog () {
+ this.setAddCancelButton(true);
+ this.setMessage("Select one of the following Resource-Bundle to open:");
+ this.setTitle("Resource-Bundle Selector");
+ this.setContentProvider(new RBContentProvider());
+ this.setLabelProvider(new RBLabelProvider());
+ this.setBlockOnOpen(true);
+
+ if (project != null)
+ this.setInput(RBManager.getInstance(project).getMessagesBundleGroupNames());
+ else
+ this.setInput(RBManager.getAllMessagesBundleGroupNames());
+ }
+
+ public String getSelectedBundleId () {
+ Object[] selection = this.getResult();
+ if (selection != null && selection.length > 0)
+ return (String) selection[0];
+ return null;
+ }
+
+ class RBContentProvider implements IStructuredContentProvider {
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ List<String> resources = (List<String>) inputElement;
+ return resources.toArray();
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ class RBLabelProvider implements ILabelProvider {
+
+ @Override
+ public Image getImage(Object element) {
+ // TODO Auto-generated method stub
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ }
+
+ @Override
+ public String getText(Object element) {
+ // TODO Auto-generated method stub
+ return ((String) element);
+ }
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
index ee7d638a..921d0dcd 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
@@ -1,31 +1,38 @@
-package org.eclipse.babel.tapiji.tools.core.ui.filters;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-
-public class PropertiesFileFilter extends ViewerFilter {
-
- private boolean debugEnabled = true;
-
- public PropertiesFileFilter() {
-
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (debugEnabled)
- return true;
-
- if (element.getClass().getSimpleName().equals("CompilationUnit"))
- return false;
-
- if (!(element instanceof IFile))
- return true;
-
- IFile file = (IFile) element;
-
- return file.getFileExtension().equalsIgnoreCase("properties");
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.filters;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+
+public class PropertiesFileFilter extends ViewerFilter {
+
+ private boolean debugEnabled = true;
+
+ public PropertiesFileFilter() {
+
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ if (debugEnabled)
+ return true;
+
+ if (element.getClass().getSimpleName().equals("CompilationUnit"))
+ return false;
+
+ if (!(element instanceof IFile))
+ return true;
+
+ IFile file = (IFile) element;
+
+ return file.getFileExtension().equalsIgnoreCase("properties");
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
index 83257d7a..2d7ce104 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui.markers;
import org.eclipse.babel.tapiji.tools.core.Logger;
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/StringLiterals.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/StringLiterals.java
index aa9f994e..5e0a1931 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/StringLiterals.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/StringLiterals.java
@@ -1,5 +1,12 @@
-package org.eclipse.babel.tapiji.tools.core.ui.markers;
-
-public class StringLiterals {
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.markers;
+
+public class StringLiterals {
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java
index 6383be93..7b70158e 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java
@@ -1,373 +1,380 @@
-package org.eclipse.babel.tapiji.tools.core.ui.menus;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.AddLanguageDialoge;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.FragmentProjectSelectionDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.GenerateBundleAccessorDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.RemoveLanguageDialoge;
-import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipse.babel.tapiji.tools.core.util.LanguageUtils;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.MenuAdapter;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.IProgressService;
-
-
-public class InternationalizationMenu extends ContributionItem {
- private boolean excludeMode = true;
- private boolean internationalizationEnabled = false;
-
- private MenuItem mnuToggleInt;
- private MenuItem excludeResource;
- private MenuItem addLanguage;
- private MenuItem removeLanguage;
-
- public InternationalizationMenu() {}
-
- public InternationalizationMenu(String id) {
- super(id);
- }
-
- @Override
- public void fill(Menu menu, int index) {
- if (getSelectedProjects().size() == 0 ||
- !projectsSupported())
- return;
-
- // Toggle Internatinalization
- mnuToggleInt = new MenuItem (menu, SWT.PUSH);
- mnuToggleInt.addSelectionListener(new SelectionAdapter () {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runToggleInt();
- }
-
- });
-
- // Exclude Resource
- excludeResource = new MenuItem (menu, SWT.PUSH);
- excludeResource.addSelectionListener(new SelectionAdapter () {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runExclude();
- }
-
- });
-
- new MenuItem(menu, SWT.SEPARATOR);
-
- // Add Language
- addLanguage = new MenuItem(menu, SWT.PUSH);
- addLanguage.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runAddLanguage();
- }
-
- });
-
- // Remove Language
- removeLanguage = new MenuItem(menu, SWT.PUSH);
- removeLanguage.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runRemoveLanguage();
- }
-
- });
-
- menu.addMenuListener(new MenuAdapter () {
- public void menuShown (MenuEvent e) {
- updateStateToggleInt (mnuToggleInt);
- //updateStateGenRBAccessor (generateAccessor);
- updateStateExclude (excludeResource);
- updateStateAddLanguage (addLanguage);
- updateStateRemoveLanguage (removeLanguage);
- }
- });
- }
-
- protected void runGenRBAccessor () {
- GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog(Display.getDefault().getActiveShell());
- if (dlg.open() != InputDialog.OK)
- return;
- }
-
- protected void updateStateGenRBAccessor (MenuItem menuItem) {
- Collection<IPackageFragment> frags = getSelectedPackageFragments();
- menuItem.setEnabled(frags.size() > 0);
- }
-
- protected void updateStateToggleInt (MenuItem menuItem) {
- Collection<IProject> projects = getSelectedProjects();
- boolean enabled = projects.size() > 0;
- menuItem.setEnabled(enabled);
- setVisible(enabled);
- internationalizationEnabled = InternationalizationNature.hasNature(projects.iterator().next());
- //menuItem.setSelection(enabled && internationalizationEnabled);
-
- if (internationalizationEnabled)
- menuItem.setText("Disable Internationalization");
- else
- menuItem.setText("Enable Internationalization");
- }
-
- private Collection<IPackageFragment> getSelectedPackageFragments () {
- Collection<IPackageFragment> frags = new HashSet<IPackageFragment> ();
- IWorkbenchWindow window =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection ();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IPackageFragment) {
- IPackageFragment frag = (IPackageFragment) elem;
- if (!frag.isReadOnly())
- frags.add (frag);
- }
- }
- }
- return frags;
- }
-
- private Collection<IProject> getSelectedProjects () {
- Collection<IProject> projects = new HashSet<IProject> ();
- IWorkbenchWindow window =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection ();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (!(elem instanceof IResource)) {
- if (!(elem instanceof IAdaptable))
- continue;
- elem = ((IAdaptable) elem).getAdapter (IResource.class);
- if (!(elem instanceof IResource))
- continue;
- }
- if (!(elem instanceof IProject)) {
- elem = ((IResource) elem).getProject();
- if (!(elem instanceof IProject))
- continue;
- }
- if (((IProject)elem).isAccessible())
- projects.add ((IProject)elem);
-
- }
- }
- return projects;
- }
-
- protected boolean projectsSupported() {
- Collection<IProject> projects = getSelectedProjects ();
- for (IProject project : projects) {
- if (!InternationalizationNature.supportsNature(project))
- return false;
- }
-
- return true;
- }
-
- protected void runToggleInt () {
- Collection<IProject> projects = getSelectedProjects ();
- for (IProject project : projects) {
- toggleNature (project);
- }
- }
-
- private void toggleNature (IProject project) {
- if (InternationalizationNature.hasNature (project)) {
- InternationalizationNature.removeNature (project);
- } else {
- InternationalizationNature.addNature (project);
- }
- }
- protected void updateStateExclude (MenuItem menuItem) {
- Collection<IResource> resources = getSelectedResources();
- menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled);
- ResourceBundleManager manager = null;
- excludeMode = false;
-
- for (IResource res : resources) {
- if (manager == null || (manager.getProject() != res.getProject()))
- manager = ResourceBundleManager.getManager(res.getProject());
- try {
- if (!ResourceBundleManager.isResourceExcluded(res)) {
- excludeMode = true;
- }
- } catch (Exception e) { }
- }
-
- if (!excludeMode)
- menuItem.setText("Include Resource");
- else
- menuItem.setText("Exclude Resource");
- }
-
- private Collection<IResource> getSelectedResources () {
- Collection<IResource> resources = new HashSet<IResource> ();
- IWorkbenchWindow window =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection ();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IProject)
- continue;
-
- if (elem instanceof IResource) {
- resources.add ((IResource)elem);
- } else if (elem instanceof IJavaElement) {
- resources.add (((IJavaElement)elem).getResource());
- }
- }
- }
- return resources;
- }
-
- protected void runExclude () {
- final Collection<IResource> selectedResources = getSelectedResources ();
-
- IWorkbench wb = PlatformUI.getWorkbench();
- IProgressService ps = wb.getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) {
-
- ResourceBundleManager manager = null;
- pm.beginTask("Including resources to Internationalization", selectedResources.size());
-
- for (IResource res : selectedResources) {
- if (manager == null || (manager.getProject() != res.getProject()))
- manager = ResourceBundleManager.getManager(res.getProject());
- if (excludeMode)
- manager.excludeResource(res, pm);
- else
- manager.includeResource(res, pm);
- pm.worked(1);
- }
- pm.done();
- }
- });
- } catch (Exception e) {}
- }
-
- protected void updateStateAddLanguage(MenuItem menuItem){
- Collection<IProject> projects = getSelectedProjects();
- boolean hasResourceBundles=false;
- for (IProject p : projects){
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
- hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false;
- }
-
- menuItem.setText("Add Language To Project");
- menuItem.setEnabled(projects.size() > 0 && hasResourceBundles);
- }
-
- protected void runAddLanguage() {
- AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell(Display.getCurrent()));
- if (dialog.open() == InputDialog.OK) {
- final Locale locale = dialog.getSelectedLanguage();
-
- Collection<IProject> selectedProjects = getSelectedProjects();
- for (IProject project : selectedProjects){
- //check if project is fragmentproject and continue working with the hostproject, if host not member of selectedProjects
- if (FragmentProjectUtils.isFragment(project)){
- IProject host = FragmentProjectUtils.getFragmentHost(project);
- if (!selectedProjects.contains(host))
- project = host;
- else
- continue;
- }
-
- List<IProject> fragments = FragmentProjectUtils.getFragments(project);
-
- if (!fragments.isEmpty()) {
- FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog(
- Display.getCurrent().getActiveShell(), project,
- fragments);
-
- if (fragmentDialog.open() == InputDialog.OK)
- project = fragmentDialog.getSelectedProject();
- }
-
- final IProject selectedProject = project;
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- @Override
- public void run() {
- LanguageUtils.addLanguageToProject(selectedProject, locale);
- }
-
- });
-
- }
- }
- }
-
-
- protected void updateStateRemoveLanguage(MenuItem menuItem) {
- Collection<IProject> projects = getSelectedProjects();
- boolean hasResourceBundles=false;
- if (projects.size() == 1){
- IProject project = projects.iterator().next();
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(project);
- hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false;
- }
- menuItem.setText("Remove Language From Project");
- menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/*&& more than one common languages contained*/);
- }
-
- protected void runRemoveLanguage() {
- final IProject project = getSelectedProjects().iterator().next();
- RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project, new Shell(Display.getCurrent()));
-
-
- if (dialog.open() == InputDialog.OK) {
- final Locale locale = dialog.getSelectedLanguage();
- if (locale != null) {
- if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Confirm", "Do you really want remove all properties-files for "+locale.getDisplayName()+"?"))
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- @Override
- public void run() {
- LanguageUtils.removeLanguageFromProject(project, locale);
- }
- });
-
- }
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.menus;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.AddLanguageDialoge;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.FragmentProjectSelectionDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.GenerateBundleAccessorDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.RemoveLanguageDialoge;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.core.util.LanguageUtils;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jdt.core.IJavaElement;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.BusyIndicator;
+import org.eclipse.swt.events.MenuAdapter;
+import org.eclipse.swt.events.MenuEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.progress.IProgressService;
+
+
+public class InternationalizationMenu extends ContributionItem {
+ private boolean excludeMode = true;
+ private boolean internationalizationEnabled = false;
+
+ private MenuItem mnuToggleInt;
+ private MenuItem excludeResource;
+ private MenuItem addLanguage;
+ private MenuItem removeLanguage;
+
+ public InternationalizationMenu() {}
+
+ public InternationalizationMenu(String id) {
+ super(id);
+ }
+
+ @Override
+ public void fill(Menu menu, int index) {
+ if (getSelectedProjects().size() == 0 ||
+ !projectsSupported())
+ return;
+
+ // Toggle Internatinalization
+ mnuToggleInt = new MenuItem (menu, SWT.PUSH);
+ mnuToggleInt.addSelectionListener(new SelectionAdapter () {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runToggleInt();
+ }
+
+ });
+
+ // Exclude Resource
+ excludeResource = new MenuItem (menu, SWT.PUSH);
+ excludeResource.addSelectionListener(new SelectionAdapter () {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runExclude();
+ }
+
+ });
+
+ new MenuItem(menu, SWT.SEPARATOR);
+
+ // Add Language
+ addLanguage = new MenuItem(menu, SWT.PUSH);
+ addLanguage.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runAddLanguage();
+ }
+
+ });
+
+ // Remove Language
+ removeLanguage = new MenuItem(menu, SWT.PUSH);
+ removeLanguage.addSelectionListener(new SelectionAdapter() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ runRemoveLanguage();
+ }
+
+ });
+
+ menu.addMenuListener(new MenuAdapter () {
+ public void menuShown (MenuEvent e) {
+ updateStateToggleInt (mnuToggleInt);
+ //updateStateGenRBAccessor (generateAccessor);
+ updateStateExclude (excludeResource);
+ updateStateAddLanguage (addLanguage);
+ updateStateRemoveLanguage (removeLanguage);
+ }
+ });
+ }
+
+ protected void runGenRBAccessor () {
+ GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog(Display.getDefault().getActiveShell());
+ if (dlg.open() != InputDialog.OK)
+ return;
+ }
+
+ protected void updateStateGenRBAccessor (MenuItem menuItem) {
+ Collection<IPackageFragment> frags = getSelectedPackageFragments();
+ menuItem.setEnabled(frags.size() > 0);
+ }
+
+ protected void updateStateToggleInt (MenuItem menuItem) {
+ Collection<IProject> projects = getSelectedProjects();
+ boolean enabled = projects.size() > 0;
+ menuItem.setEnabled(enabled);
+ setVisible(enabled);
+ internationalizationEnabled = InternationalizationNature.hasNature(projects.iterator().next());
+ //menuItem.setSelection(enabled && internationalizationEnabled);
+
+ if (internationalizationEnabled)
+ menuItem.setText("Disable Internationalization");
+ else
+ menuItem.setText("Enable Internationalization");
+ }
+
+ private Collection<IPackageFragment> getSelectedPackageFragments () {
+ Collection<IPackageFragment> frags = new HashSet<IPackageFragment> ();
+ IWorkbenchWindow window =
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection ();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IPackageFragment) {
+ IPackageFragment frag = (IPackageFragment) elem;
+ if (!frag.isReadOnly())
+ frags.add (frag);
+ }
+ }
+ }
+ return frags;
+ }
+
+ private Collection<IProject> getSelectedProjects () {
+ Collection<IProject> projects = new HashSet<IProject> ();
+ IWorkbenchWindow window =
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection ();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (!(elem instanceof IResource)) {
+ if (!(elem instanceof IAdaptable))
+ continue;
+ elem = ((IAdaptable) elem).getAdapter (IResource.class);
+ if (!(elem instanceof IResource))
+ continue;
+ }
+ if (!(elem instanceof IProject)) {
+ elem = ((IResource) elem).getProject();
+ if (!(elem instanceof IProject))
+ continue;
+ }
+ if (((IProject)elem).isAccessible())
+ projects.add ((IProject)elem);
+
+ }
+ }
+ return projects;
+ }
+
+ protected boolean projectsSupported() {
+ Collection<IProject> projects = getSelectedProjects ();
+ for (IProject project : projects) {
+ if (!InternationalizationNature.supportsNature(project))
+ return false;
+ }
+
+ return true;
+ }
+
+ protected void runToggleInt () {
+ Collection<IProject> projects = getSelectedProjects ();
+ for (IProject project : projects) {
+ toggleNature (project);
+ }
+ }
+
+ private void toggleNature (IProject project) {
+ if (InternationalizationNature.hasNature (project)) {
+ InternationalizationNature.removeNature (project);
+ } else {
+ InternationalizationNature.addNature (project);
+ }
+ }
+ protected void updateStateExclude (MenuItem menuItem) {
+ Collection<IResource> resources = getSelectedResources();
+ menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled);
+ ResourceBundleManager manager = null;
+ excludeMode = false;
+
+ for (IResource res : resources) {
+ if (manager == null || (manager.getProject() != res.getProject()))
+ manager = ResourceBundleManager.getManager(res.getProject());
+ try {
+ if (!ResourceBundleManager.isResourceExcluded(res)) {
+ excludeMode = true;
+ }
+ } catch (Exception e) { }
+ }
+
+ if (!excludeMode)
+ menuItem.setText("Include Resource");
+ else
+ menuItem.setText("Exclude Resource");
+ }
+
+ private Collection<IResource> getSelectedResources () {
+ Collection<IResource> resources = new HashSet<IResource> ();
+ IWorkbenchWindow window =
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection ();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IProject)
+ continue;
+
+ if (elem instanceof IResource) {
+ resources.add ((IResource)elem);
+ } else if (elem instanceof IJavaElement) {
+ resources.add (((IJavaElement)elem).getResource());
+ }
+ }
+ }
+ return resources;
+ }
+
+ protected void runExclude () {
+ final Collection<IResource> selectedResources = getSelectedResources ();
+
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ public void run(IProgressMonitor pm) {
+
+ ResourceBundleManager manager = null;
+ pm.beginTask("Including resources to Internationalization", selectedResources.size());
+
+ for (IResource res : selectedResources) {
+ if (manager == null || (manager.getProject() != res.getProject()))
+ manager = ResourceBundleManager.getManager(res.getProject());
+ if (excludeMode)
+ manager.excludeResource(res, pm);
+ else
+ manager.includeResource(res, pm);
+ pm.worked(1);
+ }
+ pm.done();
+ }
+ });
+ } catch (Exception e) {}
+ }
+
+ protected void updateStateAddLanguage(MenuItem menuItem){
+ Collection<IProject> projects = getSelectedProjects();
+ boolean hasResourceBundles=false;
+ for (IProject p : projects){
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
+ hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false;
+ }
+
+ menuItem.setText("Add Language To Project");
+ menuItem.setEnabled(projects.size() > 0 && hasResourceBundles);
+ }
+
+ protected void runAddLanguage() {
+ AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell(Display.getCurrent()));
+ if (dialog.open() == InputDialog.OK) {
+ final Locale locale = dialog.getSelectedLanguage();
+
+ Collection<IProject> selectedProjects = getSelectedProjects();
+ for (IProject project : selectedProjects){
+ //check if project is fragmentproject and continue working with the hostproject, if host not member of selectedProjects
+ if (FragmentProjectUtils.isFragment(project)){
+ IProject host = FragmentProjectUtils.getFragmentHost(project);
+ if (!selectedProjects.contains(host))
+ project = host;
+ else
+ continue;
+ }
+
+ List<IProject> fragments = FragmentProjectUtils.getFragments(project);
+
+ if (!fragments.isEmpty()) {
+ FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog(
+ Display.getCurrent().getActiveShell(), project,
+ fragments);
+
+ if (fragmentDialog.open() == InputDialog.OK)
+ project = fragmentDialog.getSelectedProject();
+ }
+
+ final IProject selectedProject = project;
+ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
+ @Override
+ public void run() {
+ LanguageUtils.addLanguageToProject(selectedProject, locale);
+ }
+
+ });
+
+ }
+ }
+ }
+
+
+ protected void updateStateRemoveLanguage(MenuItem menuItem) {
+ Collection<IProject> projects = getSelectedProjects();
+ boolean hasResourceBundles=false;
+ if (projects.size() == 1){
+ IProject project = projects.iterator().next();
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(project);
+ hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false;
+ }
+ menuItem.setText("Remove Language From Project");
+ menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/*&& more than one common languages contained*/);
+ }
+
+ protected void runRemoveLanguage() {
+ final IProject project = getSelectedProjects().iterator().next();
+ RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project, new Shell(Display.getCurrent()));
+
+
+ if (dialog.open() == InputDialog.OK) {
+ final Locale locale = dialog.getSelectedLanguage();
+ if (locale != null) {
+ if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Confirm", "Do you really want remove all properties-files for "+locale.getDisplayName()+"?"))
+ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
+ @Override
+ public void run() {
+ LanguageUtils.removeLanguageFromProject(project, locale);
+ }
+ });
+
+ }
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java
index 1cb95550..7c530f40 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java
@@ -1,129 +1,136 @@
-package org.eclipse.babel.tapiji.tools.core.ui.prefrences;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class BuilderPreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
- private static final int INDENT = 20;
-
- private Button checkSameValueButton;
- private Button checkMissingValueButton;
- private Button checkMissingLanguageButton;
-
- private Button rbAuditButton;
-
- private Button sourceAuditButton;
-
-
- @Override
- public void init(IWorkbench workbench) {
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
-
- @Override
- protected Control createContents(Composite parent) {
- IPreferenceStore prefs = getPreferenceStore();
- Composite composite = new Composite(parent, SWT.SHADOW_OUT);
-
- composite.setLayout(new GridLayout(1,false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
-
- Composite field = createComposite(parent, 0, 10);
- Label descriptionLabel = new Label(composite, SWT.NONE);
- descriptionLabel.setText("Select types of reported problems:");
-
- field = createComposite(composite, 0, 0);
- sourceAuditButton = new Button(field, SWT.CHECK);
- sourceAuditButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RESOURCE));
- sourceAuditButton.setText("Check source code for non externalizated Strings");
-
- field = createComposite(composite, 0, 0);
- rbAuditButton = new Button(field, SWT.CHECK);
- rbAuditButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB));
- rbAuditButton.setText("Check ResourceBundles on the following problems:");
- rbAuditButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- setRBAudits();
- }
- });
-
- field = createComposite(composite, INDENT, 0);
- checkMissingValueButton = new Button(field, SWT.CHECK);
- checkMissingValueButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
- checkMissingValueButton.setText("Missing translation for a key");
-
- field = createComposite(composite, INDENT, 0);
- checkSameValueButton = new Button(field, SWT.CHECK);
- checkSameValueButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
- checkSameValueButton.setText("Same translations for one key in diffrent languages");
-
- field = createComposite(composite, INDENT, 0);
- checkMissingLanguageButton = new Button(field, SWT.CHECK);
- checkMissingLanguageButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
- checkMissingLanguageButton.setText("Missing languages in a ResourceBundle");
-
- setRBAudits();
-
- composite.pack();
-
- return composite;
- }
-
- @Override
- protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
-
- sourceAuditButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE));
- rbAuditButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_RB));
- checkMissingValueButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
- checkSameValueButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
- checkMissingLanguageButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
- }
-
- @Override
- public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
-
- prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE, sourceAuditButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, checkMissingValueButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE, checkSameValueButton.getSelection());
- prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, checkMissingLanguageButton.getSelection());
-
- return super.performOk();
- }
-
- private Composite createComposite(Composite parent, int marginWidth, int marginHeight) {
- Composite composite = new Composite(parent, SWT.NONE);
-
- GridLayout indentLayout = new GridLayout(1, false);
- indentLayout.marginWidth = marginWidth;
- indentLayout.marginHeight = marginHeight;
- indentLayout.verticalSpacing = 0;
- composite.setLayout(indentLayout);
-
- return composite;
- }
-
- protected void setRBAudits() {
- boolean selected = rbAuditButton.getSelection();
- checkMissingValueButton.setEnabled(selected);
- checkSameValueButton.setEnabled(selected);
- checkMissingLanguageButton.setEnabled(selected);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.prefrences;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class BuilderPreferencePage extends PreferencePage implements
+ IWorkbenchPreferencePage {
+ private static final int INDENT = 20;
+
+ private Button checkSameValueButton;
+ private Button checkMissingValueButton;
+ private Button checkMissingLanguageButton;
+
+ private Button rbAuditButton;
+
+ private Button sourceAuditButton;
+
+
+ @Override
+ public void init(IWorkbench workbench) {
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ IPreferenceStore prefs = getPreferenceStore();
+ Composite composite = new Composite(parent, SWT.SHADOW_OUT);
+
+ composite.setLayout(new GridLayout(1,false));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+
+ Composite field = createComposite(parent, 0, 10);
+ Label descriptionLabel = new Label(composite, SWT.NONE);
+ descriptionLabel.setText("Select types of reported problems:");
+
+ field = createComposite(composite, 0, 0);
+ sourceAuditButton = new Button(field, SWT.CHECK);
+ sourceAuditButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RESOURCE));
+ sourceAuditButton.setText("Check source code for non externalizated Strings");
+
+ field = createComposite(composite, 0, 0);
+ rbAuditButton = new Button(field, SWT.CHECK);
+ rbAuditButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB));
+ rbAuditButton.setText("Check ResourceBundles on the following problems:");
+ rbAuditButton.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent event) {
+ setRBAudits();
+ }
+ });
+
+ field = createComposite(composite, INDENT, 0);
+ checkMissingValueButton = new Button(field, SWT.CHECK);
+ checkMissingValueButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
+ checkMissingValueButton.setText("Missing translation for a key");
+
+ field = createComposite(composite, INDENT, 0);
+ checkSameValueButton = new Button(field, SWT.CHECK);
+ checkSameValueButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
+ checkSameValueButton.setText("Same translations for one key in diffrent languages");
+
+ field = createComposite(composite, INDENT, 0);
+ checkMissingLanguageButton = new Button(field, SWT.CHECK);
+ checkMissingLanguageButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
+ checkMissingLanguageButton.setText("Missing languages in a ResourceBundle");
+
+ setRBAudits();
+
+ composite.pack();
+
+ return composite;
+ }
+
+ @Override
+ protected void performDefaults() {
+ IPreferenceStore prefs = getPreferenceStore();
+
+ sourceAuditButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE));
+ rbAuditButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_RB));
+ checkMissingValueButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY));
+ checkSameValueButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE));
+ checkMissingLanguageButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE));
+ }
+
+ @Override
+ public boolean performOk() {
+ IPreferenceStore prefs = getPreferenceStore();
+
+ prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE, sourceAuditButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, checkMissingValueButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE, checkSameValueButton.getSelection());
+ prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, checkMissingLanguageButton.getSelection());
+
+ return super.performOk();
+ }
+
+ private Composite createComposite(Composite parent, int marginWidth, int marginHeight) {
+ Composite composite = new Composite(parent, SWT.NONE);
+
+ GridLayout indentLayout = new GridLayout(1, false);
+ indentLayout.marginWidth = marginWidth;
+ indentLayout.marginHeight = marginHeight;
+ indentLayout.verticalSpacing = 0;
+ composite.setLayout(indentLayout);
+
+ return composite;
+ }
+
+ protected void setRBAudits() {
+ boolean selected = rbAuditButton.getSelection();
+ checkMissingValueButton.setEnabled(selected);
+ checkSameValueButton.setEnabled(selected);
+ checkMissingLanguageButton.setEnabled(selected);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/FilePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/FilePreferencePage.java
index 2d3065b1..06ca0a5f 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/FilePreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/FilePreferencePage.java
@@ -1,192 +1,199 @@
-package org.eclipse.babel.tapiji.tools.core.ui.prefrences;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.model.preferences.CheckItem;
-import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreatePatternDialoge;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class FilePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
-
- private Table table;
- protected Object dialoge;
-
- private Button editPatternButton;
- private Button removePatternButton;
-
- @Override
- public void init(IWorkbench workbench) {
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- }
-
- @Override
- protected Control createContents(Composite parent) {
- IPreferenceStore prefs = getPreferenceStore();
- Composite composite = new Composite(parent, SWT.SHADOW_OUT);
-
- composite.setLayout(new GridLayout(2,false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
-
- Label descriptionLabel = new Label(composite, SWT.WRAP);
- GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false);
- descriptionData.horizontalSpan=2;
- descriptionLabel.setLayoutData(descriptionData);
- descriptionLabel.setText("Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files");
-
- table = new Table (composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.CHECK);
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- table.setLayoutData(data);
-
- table.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0){
- editPatternButton.setEnabled(true);
- removePatternButton.setEnabled(true);
- }else{
- editPatternButton.setEnabled(false);
- removePatternButton.setEnabled(false);
- }
- }
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // TODO Auto-generated method stub
- }
- });
-
- List<CheckItem> patternItems = TapiJIPreferences.getNonRbPatternAsList();
- for (CheckItem s : patternItems){
- s.toTableItem(table);
- }
-
- Composite sitebar = new Composite(composite, SWT.NONE);
- sitebar.setLayout(new GridLayout(1,false));
- sitebar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true));
-
- Button addPatternButton = new Button(sitebar, SWT.NONE);
- addPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- addPatternButton.setText("Add Pattern");
- addPatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseDown(MouseEvent e) {
- String pattern = "^.*/<BASENAME>"+"((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?"+ "\\.properties$";
- CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(),pattern);
- if (dialog.open() == InputDialog.OK) {
- pattern = dialog.getPattern();
-
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(pattern);
- item.setChecked(true);
- }
- }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
-
- editPatternButton = new Button(sitebar, SWT.NONE);
- editPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- editPatternButton.setText("Edit");
- editPatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseDown(MouseEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0){
- String pattern = selection[0].getText();
-
- CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(), pattern);
- if (dialog.open() == InputDialog.OK) {
- pattern = dialog.getPattern();
- TableItem item = selection[0];
- item.setText(pattern);
- }
- }
- }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
-
-
- removePatternButton = new Button(sitebar, SWT.NONE);
- removePatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
- removePatternButton.setText("Remove");
- removePatternButton.addMouseListener(new MouseListener() {
- @Override
- public void mouseUp(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void mouseDown(MouseEvent e) {
- TableItem[] selection = table.getSelection();
- if (selection.length > 0)
- table.remove(table.indexOf(selection[0]));
- }
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // TODO Auto-generated method stub
- }
- });
-
- composite.pack();
-
- return composite;
- }
-
- @Override
- protected void performDefaults() {
- IPreferenceStore prefs = getPreferenceStore();
-
- table.removeAll();
-
- List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs.getDefaultString(TapiJIPreferences.NON_RB_PATTERN));
- for (CheckItem s : patterns){
- s.toTableItem(table);
- }
- }
-
- @Override
- public boolean performOk() {
- IPreferenceStore prefs = getPreferenceStore();
- List<CheckItem> patterns =new LinkedList<CheckItem>();
- for (TableItem i : table.getItems()){
- patterns.add(new CheckItem(i.getText(), i.getChecked()));
- }
-
- prefs.setValue(TapiJIPreferences.NON_RB_PATTERN, TapiJIPreferences.convertListToString(patterns));
-
- return super.performOk();
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.prefrences;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.model.preferences.CheckItem;
+import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreatePatternDialoge;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class FilePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
+
+ private Table table;
+ protected Object dialoge;
+
+ private Button editPatternButton;
+ private Button removePatternButton;
+
+ @Override
+ public void init(IWorkbench workbench) {
+ setPreferenceStore(Activator.getDefault().getPreferenceStore());
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ IPreferenceStore prefs = getPreferenceStore();
+ Composite composite = new Composite(parent, SWT.SHADOW_OUT);
+
+ composite.setLayout(new GridLayout(2,false));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+
+ Label descriptionLabel = new Label(composite, SWT.WRAP);
+ GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false);
+ descriptionData.horizontalSpan=2;
+ descriptionLabel.setLayoutData(descriptionData);
+ descriptionLabel.setText("Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files");
+
+ table = new Table (composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.CHECK);
+ GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
+ table.setLayoutData(data);
+
+ table.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ TableItem[] selection = table.getSelection();
+ if (selection.length > 0){
+ editPatternButton.setEnabled(true);
+ removePatternButton.setEnabled(true);
+ }else{
+ editPatternButton.setEnabled(false);
+ removePatternButton.setEnabled(false);
+ }
+ }
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
+
+ List<CheckItem> patternItems = TapiJIPreferences.getNonRbPatternAsList();
+ for (CheckItem s : patternItems){
+ s.toTableItem(table);
+ }
+
+ Composite sitebar = new Composite(composite, SWT.NONE);
+ sitebar.setLayout(new GridLayout(1,false));
+ sitebar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true));
+
+ Button addPatternButton = new Button(sitebar, SWT.NONE);
+ addPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+ addPatternButton.setText("Add Pattern");
+ addPatternButton.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseUp(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void mouseDown(MouseEvent e) {
+ String pattern = "^.*/<BASENAME>"+"((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?"+ "\\.properties$";
+ CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(),pattern);
+ if (dialog.open() == InputDialog.OK) {
+ pattern = dialog.getPattern();
+
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(pattern);
+ item.setChecked(true);
+ }
+ }
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
+
+ editPatternButton = new Button(sitebar, SWT.NONE);
+ editPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+ editPatternButton.setText("Edit");
+ editPatternButton.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseUp(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void mouseDown(MouseEvent e) {
+ TableItem[] selection = table.getSelection();
+ if (selection.length > 0){
+ String pattern = selection[0].getText();
+
+ CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(), pattern);
+ if (dialog.open() == InputDialog.OK) {
+ pattern = dialog.getPattern();
+ TableItem item = selection[0];
+ item.setText(pattern);
+ }
+ }
+ }
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
+
+
+ removePatternButton = new Button(sitebar, SWT.NONE);
+ removePatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
+ removePatternButton.setText("Remove");
+ removePatternButton.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseUp(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ @Override
+ public void mouseDown(MouseEvent e) {
+ TableItem[] selection = table.getSelection();
+ if (selection.length > 0)
+ table.remove(table.indexOf(selection[0]));
+ }
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ // TODO Auto-generated method stub
+ }
+ });
+
+ composite.pack();
+
+ return composite;
+ }
+
+ @Override
+ protected void performDefaults() {
+ IPreferenceStore prefs = getPreferenceStore();
+
+ table.removeAll();
+
+ List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs.getDefaultString(TapiJIPreferences.NON_RB_PATTERN));
+ for (CheckItem s : patterns){
+ s.toTableItem(table);
+ }
+ }
+
+ @Override
+ public boolean performOk() {
+ IPreferenceStore prefs = getPreferenceStore();
+ List<CheckItem> patterns =new LinkedList<CheckItem>();
+ for (TableItem i : table.getItems()){
+ patterns.add(new CheckItem(i.getText(), i.getChecked()));
+ }
+
+ prefs.setValue(TapiJIPreferences.NON_RB_PATTERN, TapiJIPreferences.convertListToString(patterns));
+
+ return super.performOk();
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java
index 60ca9495..0cad4892 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java
@@ -1,34 +1,41 @@
-package org.eclipse.babel.tapiji.tools.core.ui.prefrences;
-
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class TapiHomePreferencePage extends PreferencePage implements
- IWorkbenchPreferencePage {
-
- @Override
- public void init(IWorkbench workbench) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected Control createContents(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(1,true));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
-
- Label description = new Label(composite, SWT.WRAP);
- description.setText("See sub-pages for settings.");
-
- return parent;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.prefrences;
+
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class TapiHomePreferencePage extends PreferencePage implements
+ IWorkbenchPreferencePage {
+
+ @Override
+ public void init(IWorkbench workbench) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ protected Control createContents(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(new GridLayout(1,true));
+ composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ Label description = new Label(composite, SWT.WRAP);
+ description.setText("See sub-pages for settings.");
+
+ return parent;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
index 43d2a728..b72acb63 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java
@@ -1,89 +1,96 @@
-package org.eclipse.babel.tapiji.tools.core.ui.quickfix;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-
-public class CreateResourceBundleEntry implements IMarkerResolution2 {
-
- private String key;
- private String bundleId;
-
- public CreateResourceBundleEntry(String key, String bundleId) {
- this.key = key;
- this.bundleId = bundleId;
- }
-
- @Override
- public String getDescription() {
- return "Creates a new Resource-Bundle entry for the property-key '"
- + key + "'";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Create Resource-Bundle entry for '" + key + "'";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(key != null ? key : "");
- config.setPreselectedMessage("");
- config.setPreselectedBundle(bundleId);
- config.setPreselectedLocale("");
- config.setProjectName(resource.getProject().getName());
-
- dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK)
- return;
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- (new I18nBuilder()).buildResource(resource, null);
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class CreateResourceBundleEntry implements IMarkerResolution2 {
+
+ private String key;
+ private String bundleId;
+
+ public CreateResourceBundleEntry(String key, String bundleId) {
+ this.key = key;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Creates a new Resource-Bundle entry for the property-key '"
+ + key + "'";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Create Resource-Bundle entry for '" + key + "'";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(key != null ? key : "");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle(bundleId);
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ try {
+ (new I18nBuilder()).buildResource(resource, null);
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java
index 6ce95d96..9b74a36a 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview;
import java.util.ArrayList;
@@ -511,4 +518,4 @@ public void dispose(){
ResourceBundleManager.getManager(viewState.getSelectedProjectName()).unregisterResourceBundleChangeListener(viewState.getSelectedBundleId(), this);
} catch (Exception e) {}
}
-}
\ No newline at end of file
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
index cd230bcf..82804bd0 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
@@ -1,114 +1,121 @@
-package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview;
-
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree;
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-
-public class ResourceBundleEntry extends ContributionItem implements
- ISelectionChangedListener {
-
- private PropertyKeySelectionTree parentView;
- private ISelection selection;
- private boolean legalSelection = false;
-
- // Menu-Items
- private MenuItem addItem;
- private MenuItem editItem;
- private MenuItem removeItem;
-
- public ResourceBundleEntry() {
- }
-
- public ResourceBundleEntry(PropertyKeySelectionTree view, ISelection selection) {
- this.selection = selection;
- this.legalSelection = ! selection.isEmpty();
- this.parentView = view;
- parentView.addSelectionChangedListener(this);
- }
-
- @Override
- public void fill(Menu menu, int index) {
-
- // MenuItem for adding a new entry
- addItem = new MenuItem(menu, SWT.NONE, index);
- addItem.setText("Add ...");
- addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
- addItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.addNewItem(selection);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
-
- if ((parentView == null && legalSelection) || parentView != null) {
- // MenuItem for editing the currently selected entry
- editItem = new MenuItem(menu, SWT.NONE, index + 1);
- editItem.setText("Edit");
- editItem.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.editSelectedItem();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
-
- // MenuItem for deleting the currently selected entry
- removeItem = new MenuItem(menu, SWT.NONE, index + 2);
- removeItem.setText("Remove");
- removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
- .createImage());
- removeItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.deleteSelectedItems();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
- enableMenuItems();
- }
- }
-
- protected void enableMenuItems() {
- try {
- editItem.setEnabled(legalSelection);
- removeItem.setEnabled(legalSelection);
- } catch (Exception e) {
- // silent catch
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- legalSelection = !event.getSelection().isEmpty();
- // enableMenuItems ();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview;
+
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree;
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+
+public class ResourceBundleEntry extends ContributionItem implements
+ ISelectionChangedListener {
+
+ private PropertyKeySelectionTree parentView;
+ private ISelection selection;
+ private boolean legalSelection = false;
+
+ // Menu-Items
+ private MenuItem addItem;
+ private MenuItem editItem;
+ private MenuItem removeItem;
+
+ public ResourceBundleEntry() {
+ }
+
+ public ResourceBundleEntry(PropertyKeySelectionTree view, ISelection selection) {
+ this.selection = selection;
+ this.legalSelection = ! selection.isEmpty();
+ this.parentView = view;
+ parentView.addSelectionChangedListener(this);
+ }
+
+ @Override
+ public void fill(Menu menu, int index) {
+
+ // MenuItem for adding a new entry
+ addItem = new MenuItem(menu, SWT.NONE, index);
+ addItem.setText("Add ...");
+ addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
+ addItem.addSelectionListener( new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.addNewItem(selection);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+
+ if ((parentView == null && legalSelection) || parentView != null) {
+ // MenuItem for editing the currently selected entry
+ editItem = new MenuItem(menu, SWT.NONE, index + 1);
+ editItem.setText("Edit");
+ editItem.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.editSelectedItem();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+
+ // MenuItem for deleting the currently selected entry
+ removeItem = new MenuItem(menu, SWT.NONE, index + 2);
+ removeItem.setText("Remove");
+ removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
+ .createImage());
+ removeItem.addSelectionListener( new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.deleteSelectedItems();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+ enableMenuItems();
+ }
+ }
+
+ protected void enableMenuItems() {
+ try {
+ editItem.setEnabled(legalSelection);
+ removeItem.setEnabled(legalSelection);
+ } catch (Exception e) {
+ // silent catch
+ }
+ }
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ legalSelection = !event.getSelection().isEmpty();
+ // enableMenuItems ();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
index 70ad4c20..ba85c7cb 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
@@ -1,148 +1,155 @@
-package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
-
-import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.message.MessagesBundleGroup;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.editor.api.MessageFactory;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.TreeItem;
-
-public class KeyTreeItemDropTarget extends DropTargetAdapter {
- private final TreeViewer target;
-
- public KeyTreeItemDropTarget (TreeViewer viewer) {
- super();
- this.target = viewer;
- }
-
- public void dragEnter (DropTargetEvent event) {
-// if (((DropTarget)event.getSource()).getControl() instanceof Tree)
-// event.detail = DND.DROP_MOVE;
- }
-
- private void addBundleEntries (final String keyPrefix, // new prefix
- final IKeyTreeNode children,
- final IMessagesBundleGroup bundleGroup) {
-
- try {
- String oldKey = children.getMessageKey();
- String key = children.getName();
- String newKey = keyPrefix + "." + key;
-
- IMessage[] messages = bundleGroup.getMessages(oldKey);
- for (IMessage message : messages) {
- IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(message.getLocale());
- IMessage m = MessageFactory.createMessage(newKey, message.getLocale());
- m.setText(message.getValue());
- m.setComment(message.getComment());
- messagesBundle.addMessage(m);
- }
-
- if (messages.length == 0 ) {
- bundleGroup.addMessages(newKey);
- }
-
- for (IKeyTreeNode childs : children.getChildren()) {
- addBundleEntries(keyPrefix+"."+key, childs, bundleGroup);
- }
-
- } catch (Exception e) { Logger.logError(e); }
-
- }
-
- private void remBundleEntries(IKeyTreeNode children, IMessagesBundleGroup group) {
- String key = children.getMessageKey();
-
- for (IKeyTreeNode childs : children.getChildren()) {
- remBundleEntries(childs, group);
- }
-
- group.removeMessagesAddParentKey(key);
- }
-
- public void drop (final DropTargetEvent event) {
- Display.getDefault().asyncExec(new Runnable() {
- public void run() {
- try {
-
- if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) {
- String newKeyPrefix = "";
-
- if (event.item instanceof TreeItem &&
- ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item).getData();
- newKeyPrefix = targetTreeNode.getMessageKey();
- }
-
- String message = (String)event.data;
- String oldKey = message.replaceAll("\"", "");
-
- String[] keyArr = (oldKey).split("\\.");
- String key = keyArr[keyArr.length-1];
-
- ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target.getContentProvider();
- IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target.getInput();
-
- // key gets dropped into it's parent node
- if (oldKey.equals(newKeyPrefix + "." + key))
- return; // TODO: give user feedback
-
- // prevent cycle loop if key gets dropped into its child node
- if (newKeyPrefix.contains(oldKey))
- return; // TODO: give user feedback
-
- // source node already exists in target
- IKeyTreeNode targetTreeNode = keyTree.getChild(newKeyPrefix);
- for (IKeyTreeNode targetChild : targetTreeNode.getChildren()) {
- if (targetChild.getName().equals(key))
- return; // TODO: give user feedback
- }
-
- IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey);
-
- IMessagesBundleGroup bundleGroup = contentProvider.getBundle();
-
- DirtyHack.setFireEnabled(false);
- DirtyHack.setEditorModificationEnabled(false); // editor won't get dirty
-
- // add new bundle entries of source node + all children
- addBundleEntries(newKeyPrefix, sourceTreeNode, bundleGroup);
-
- // if drag & drop is move event, delete source entry + it's children
- if (event.detail == DND.DROP_MOVE) {
- remBundleEntries(sourceTreeNode, bundleGroup);
- }
-
- // Store changes
- RBManager manager = RBManager.getInstance(((MessagesBundleGroup) bundleGroup).getProjectName());
-
- manager.writeToFile(bundleGroup);
- manager.fireEditorChanged(); // refresh the View
-
- target.refresh();
- } else {
- event.detail = DND.DROP_NONE;
- }
-
- } catch (Exception e) { Logger.logError(e); }
- finally {
- DirtyHack.setFireEnabled(true);
- DirtyHack.setEditorModificationEnabled(true);
- }
- }
- });
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
+
+import org.eclipse.babel.core.configuration.DirtyHack;
+import org.eclipse.babel.core.message.MessagesBundleGroup;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.editor.api.MessageFactory;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetAdapter;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.TreeItem;
+
+public class KeyTreeItemDropTarget extends DropTargetAdapter {
+ private final TreeViewer target;
+
+ public KeyTreeItemDropTarget (TreeViewer viewer) {
+ super();
+ this.target = viewer;
+ }
+
+ public void dragEnter (DropTargetEvent event) {
+// if (((DropTarget)event.getSource()).getControl() instanceof Tree)
+// event.detail = DND.DROP_MOVE;
+ }
+
+ private void addBundleEntries (final String keyPrefix, // new prefix
+ final IKeyTreeNode children,
+ final IMessagesBundleGroup bundleGroup) {
+
+ try {
+ String oldKey = children.getMessageKey();
+ String key = children.getName();
+ String newKey = keyPrefix + "." + key;
+
+ IMessage[] messages = bundleGroup.getMessages(oldKey);
+ for (IMessage message : messages) {
+ IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(message.getLocale());
+ IMessage m = MessageFactory.createMessage(newKey, message.getLocale());
+ m.setText(message.getValue());
+ m.setComment(message.getComment());
+ messagesBundle.addMessage(m);
+ }
+
+ if (messages.length == 0 ) {
+ bundleGroup.addMessages(newKey);
+ }
+
+ for (IKeyTreeNode childs : children.getChildren()) {
+ addBundleEntries(keyPrefix+"."+key, childs, bundleGroup);
+ }
+
+ } catch (Exception e) { Logger.logError(e); }
+
+ }
+
+ private void remBundleEntries(IKeyTreeNode children, IMessagesBundleGroup group) {
+ String key = children.getMessageKey();
+
+ for (IKeyTreeNode childs : children.getChildren()) {
+ remBundleEntries(childs, group);
+ }
+
+ group.removeMessagesAddParentKey(key);
+ }
+
+ public void drop (final DropTargetEvent event) {
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ try {
+
+ if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) {
+ String newKeyPrefix = "";
+
+ if (event.item instanceof TreeItem &&
+ ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item).getData();
+ newKeyPrefix = targetTreeNode.getMessageKey();
+ }
+
+ String message = (String)event.data;
+ String oldKey = message.replaceAll("\"", "");
+
+ String[] keyArr = (oldKey).split("\\.");
+ String key = keyArr[keyArr.length-1];
+
+ ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target.getContentProvider();
+ IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target.getInput();
+
+ // key gets dropped into it's parent node
+ if (oldKey.equals(newKeyPrefix + "." + key))
+ return; // TODO: give user feedback
+
+ // prevent cycle loop if key gets dropped into its child node
+ if (newKeyPrefix.contains(oldKey))
+ return; // TODO: give user feedback
+
+ // source node already exists in target
+ IKeyTreeNode targetTreeNode = keyTree.getChild(newKeyPrefix);
+ for (IKeyTreeNode targetChild : targetTreeNode.getChildren()) {
+ if (targetChild.getName().equals(key))
+ return; // TODO: give user feedback
+ }
+
+ IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey);
+
+ IMessagesBundleGroup bundleGroup = contentProvider.getBundle();
+
+ DirtyHack.setFireEnabled(false);
+ DirtyHack.setEditorModificationEnabled(false); // editor won't get dirty
+
+ // add new bundle entries of source node + all children
+ addBundleEntries(newKeyPrefix, sourceTreeNode, bundleGroup);
+
+ // if drag & drop is move event, delete source entry + it's children
+ if (event.detail == DND.DROP_MOVE) {
+ remBundleEntries(sourceTreeNode, bundleGroup);
+ }
+
+ // Store changes
+ RBManager manager = RBManager.getInstance(((MessagesBundleGroup) bundleGroup).getProjectName());
+
+ manager.writeToFile(bundleGroup);
+ manager.fireEditorChanged(); // refresh the View
+
+ target.refresh();
+ } else {
+ event.detail = DND.DROP_NONE;
+ }
+
+ } catch (Exception e) { Logger.logError(e); }
+ finally {
+ DirtyHack.setFireEnabled(true);
+ DirtyHack.setEditorModificationEnabled(true);
+ }
+ }
+ });
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
index 93b6193d..f014158f 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
@@ -1,106 +1,113 @@
-package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TransferData;
-
-public class KeyTreeItemTransfer extends ByteArrayTransfer {
-
- private static final String KEY_TREE_ITEM = "keyTreeItem";
-
- private static final int TYPEID = registerType(KEY_TREE_ITEM);
-
- private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer();
-
- public static KeyTreeItemTransfer getInstance() {
- return transfer;
- }
-
- public void javaToNative(Object object, TransferData transferData) {
- if (!checkType(object) || !isSupportedType(transferData)) {
- DND.error(DND.ERROR_INVALID_DATA);
- }
- IKeyTreeNode[] terms = (IKeyTreeNode[]) object;
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ObjectOutputStream oOut = new ObjectOutputStream(out);
- for (int i = 0, length = terms.length; i < length; i++) {
- oOut.writeObject(terms[i]);
- }
- byte[] buffer = out.toByteArray();
- oOut.close();
-
- super.javaToNative(buffer, transferData);
- } catch (IOException e) {
- Logger.logError(e);
- }
- }
-
- public Object nativeToJava(TransferData transferData) {
- if (isSupportedType(transferData)) {
-
- byte[] buffer;
- try {
- buffer = (byte[]) super.nativeToJava(transferData);
- } catch (Exception e) {
- Logger.logError(e);
- buffer = null;
- }
- if (buffer == null)
- return null;
-
- List<IKeyTreeNode> terms = new ArrayList<IKeyTreeNode>();
- try {
- ByteArrayInputStream in = new ByteArrayInputStream(buffer);
- ObjectInputStream readIn = new ObjectInputStream(in);
- //while (readIn.available() > 0) {
- IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject();
- terms.add(newTerm);
- //}
- readIn.close();
- } catch (Exception ex) {
- Logger.logError(ex);
- return null;
- }
- return terms.toArray(new IKeyTreeNode[terms.size()]);
- }
-
- return null;
- }
-
- protected String[] getTypeNames() {
- return new String[] { KEY_TREE_ITEM };
- }
-
- protected int[] getTypeIds() {
- return new int[] { TYPEID };
- }
-
- boolean checkType(Object object) {
- if (object == null || !(object instanceof IKeyTreeNode[])
- || ((IKeyTreeNode[]) object).length == 0) {
- return false;
- }
- IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object;
- for (int i = 0; i < myTypes.length; i++) {
- if (myTypes[i] == null) {
- return false;
- }
- }
- return true;
- }
-
- protected boolean validate(Object object) {
- return checkType(object);
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.swt.dnd.ByteArrayTransfer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.TransferData;
+
+public class KeyTreeItemTransfer extends ByteArrayTransfer {
+
+ private static final String KEY_TREE_ITEM = "keyTreeItem";
+
+ private static final int TYPEID = registerType(KEY_TREE_ITEM);
+
+ private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer();
+
+ public static KeyTreeItemTransfer getInstance() {
+ return transfer;
+ }
+
+ public void javaToNative(Object object, TransferData transferData) {
+ if (!checkType(object) || !isSupportedType(transferData)) {
+ DND.error(DND.ERROR_INVALID_DATA);
+ }
+ IKeyTreeNode[] terms = (IKeyTreeNode[]) object;
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ObjectOutputStream oOut = new ObjectOutputStream(out);
+ for (int i = 0, length = terms.length; i < length; i++) {
+ oOut.writeObject(terms[i]);
+ }
+ byte[] buffer = out.toByteArray();
+ oOut.close();
+
+ super.javaToNative(buffer, transferData);
+ } catch (IOException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public Object nativeToJava(TransferData transferData) {
+ if (isSupportedType(transferData)) {
+
+ byte[] buffer;
+ try {
+ buffer = (byte[]) super.nativeToJava(transferData);
+ } catch (Exception e) {
+ Logger.logError(e);
+ buffer = null;
+ }
+ if (buffer == null)
+ return null;
+
+ List<IKeyTreeNode> terms = new ArrayList<IKeyTreeNode>();
+ try {
+ ByteArrayInputStream in = new ByteArrayInputStream(buffer);
+ ObjectInputStream readIn = new ObjectInputStream(in);
+ //while (readIn.available() > 0) {
+ IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject();
+ terms.add(newTerm);
+ //}
+ readIn.close();
+ } catch (Exception ex) {
+ Logger.logError(ex);
+ return null;
+ }
+ return terms.toArray(new IKeyTreeNode[terms.size()]);
+ }
+
+ return null;
+ }
+
+ protected String[] getTypeNames() {
+ return new String[] { KEY_TREE_ITEM };
+ }
+
+ protected int[] getTypeIds() {
+ return new int[] { TYPEID };
+ }
+
+ boolean checkType(Object object) {
+ if (object == null || !(object instanceof IKeyTreeNode[])
+ || ((IKeyTreeNode[]) object).length == 0) {
+ return false;
+ }
+ IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object;
+ for (int i = 0; i < myTypes.length; i++) {
+ if (myTypes[i] == null) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ protected boolean validate(Object object) {
+ return checkType(object);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
index 005171a4..26f6fd14 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
@@ -1,42 +1,49 @@
-package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
-
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-
-public class MessagesDragSource implements DragSourceListener {
-
- private final TreeViewer source;
- private String bundleId;
-
- public MessagesDragSource (TreeViewer sourceView, String bundleId) {
- source = sourceView;
- this.bundleId = bundleId;
- }
-
- @Override
- public void dragFinished(DragSourceEvent event) {
-
- }
-
- @Override
- public void dragSetData(DragSourceEvent event) {
- IKeyTreeNode selectionObject = (IKeyTreeNode)
- ((IStructuredSelection)source.getSelection()).toList().get(0);
-
- String key = selectionObject.getMessageKey();
-
- // TODO Solve the problem that its not possible to retrieve the editor position of the drop event
-
-// event.data = "(new ResourceBundle(\"" + bundleId + "\")).getString(\"" + key + "\")";
- event.data = "\"" + key + "\"";
- }
-
- @Override
- public void dragStart(DragSourceEvent event) {
- event.doit = !source.getSelection().isEmpty();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
+
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.DragSourceListener;
+
+public class MessagesDragSource implements DragSourceListener {
+
+ private final TreeViewer source;
+ private String bundleId;
+
+ public MessagesDragSource (TreeViewer sourceView, String bundleId) {
+ source = sourceView;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public void dragFinished(DragSourceEvent event) {
+
+ }
+
+ @Override
+ public void dragSetData(DragSourceEvent event) {
+ IKeyTreeNode selectionObject = (IKeyTreeNode)
+ ((IStructuredSelection)source.getSelection()).toList().get(0);
+
+ String key = selectionObject.getMessageKey();
+
+ // TODO Solve the problem that its not possible to retrieve the editor position of the drop event
+
+// event.data = "(new ResourceBundle(\"" + bundleId + "\")).getString(\"" + key + "\")";
+ event.data = "\"" + key + "\"";
+ }
+
+ @Override
+ public void dragStart(DragSourceEvent event) {
+ event.doit = !source.getSelection().isEmpty();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
index 3ea615ff..5c4ad5f5 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
@@ -1,60 +1,67 @@
-package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
-
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.TreeItem;
-
-public class MessagesDropTarget extends DropTargetAdapter {
- private final String projectName;
- private String bundleName;
-
- public MessagesDropTarget (TreeViewer viewer, String projectName, String bundleName) {
- super();
- this.projectName = projectName;
- this.bundleName = bundleName;
- }
-
- public void dragEnter (DropTargetEvent event) {
- }
-
- public void drop (DropTargetEvent event) {
- if (event.detail != DND.DROP_COPY)
- return;
-
- if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) {
- //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- String newKeyPrefix = "";
-
- if (event.item instanceof TreeItem &&
- ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
- newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item).getData()).getMessageKey();
- }
-
- String message = (String)event.data;
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]" : "");
- config.setPreselectedMessage(message);
- config.setPreselectedBundle(bundleName);
- config.setPreselectedLocale("");
- config.setProjectName(projectName);
-
- dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK)
- return;
- } else
- event.detail = DND.DROP_NONE;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetAdapter;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.TreeItem;
+
+public class MessagesDropTarget extends DropTargetAdapter {
+ private final String projectName;
+ private String bundleName;
+
+ public MessagesDropTarget (TreeViewer viewer, String projectName, String bundleName) {
+ super();
+ this.projectName = projectName;
+ this.bundleName = bundleName;
+ }
+
+ public void dragEnter (DropTargetEvent event) {
+ }
+
+ public void drop (DropTargetEvent event) {
+ if (event.detail != DND.DROP_COPY)
+ return;
+
+ if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) {
+ //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ String newKeyPrefix = "";
+
+ if (event.item instanceof TreeItem &&
+ ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) {
+ newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item).getData()).getMessageKey();
+ }
+
+ String message = (String)event.data;
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]" : "");
+ config.setPreselectedMessage(message);
+ config.setPreselectedBundle(bundleName);
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+ } else
+ event.detail = DND.DROP_NONE;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java
index e7983252..5edc5a26 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java
@@ -1,9 +1,16 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets;
-
-
-public class MVTextTransfer {
-
- private MVTextTransfer () {
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets;
+
+
+public class MVTextTransfer {
+
+ private MVTextTransfer () {
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
index 972fb38e..0b2f461b 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
@@ -1,734 +1,741 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.message.manager.IMessagesEditorListener;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.editor.api.KeyTreeFactory;
-import org.eclipse.babel.editor.api.MessageFactory;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.model.view.SortInfo;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
-import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.KeyTreeItemDropTarget;
-import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDragSource;
-import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDropTarget;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.ExactMatcher;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.FuzzyMatcher;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.sorter.ValuedKeyTreeItemSorter;
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.TreeType;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.layout.TreeColumnLayout;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IElementComparer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-
-public class PropertyKeySelectionTree extends Composite implements IResourceBundleChangedListener {
-
- private final int KEY_COLUMN_WEIGHT = 1;
- private final int LOCALE_COLUMN_WEIGHT = 1;
-
- private List<Locale> visibleLocales = new ArrayList<Locale>();
- private boolean editable;
- private String resourceBundle;
-
- private IWorkbenchPartSite site;
- private TreeColumnLayout basicLayout;
- private TreeViewer treeViewer;
- private TreeColumn keyColumn;
- private boolean grouped = true;
- private boolean fuzzyMatchingEnabled = false;
- private float matchingPrecision = .75f;
- private Locale uiLocale = new Locale("en");
-
- private SortInfo sortInfo;
-
- private ResKeyTreeContentProvider contentProvider;
- private ResKeyTreeLabelProvider labelProvider;
- private TreeType treeType = TreeType.Tree;
-
- private IMessagesEditorListener editorListener;
-
- /*** MATCHER ***/
- ExactMatcher matcher;
-
- /*** SORTER ***/
- ValuedKeyTreeItemSorter sorter;
-
- /*** ACTIONS ***/
- private Action doubleClickAction;
-
- /*** LISTENERS ***/
- private ISelectionChangedListener selectionChangedListener;
- private String projectName;
-
- public PropertyKeySelectionTree(IViewSite viewSite, IWorkbenchPartSite site, Composite parent, int style,
- String projectName, String resources, List<Locale> locales) {
- super(parent, style);
- this.site = site;
- this.resourceBundle = resources;
- this.projectName = projectName;
-
- if (resourceBundle != null && resourceBundle.trim().length() > 0) {
- if (locales == null)
- initVisibleLocales();
- else
- this.visibleLocales = locales;
- }
-
- constructWidget();
-
- if (resourceBundle != null && resourceBundle.trim().length() > 0) {
- initTreeViewer();
- initMatchers();
- initSorters();
- treeViewer.expandAll();
- }
-
- hookDragAndDrop();
- registerListeners();
- }
-
- @Override
- public void dispose() {
- super.dispose();
- unregisterListeners();
- }
-
- protected void initSorters() {
- sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo);
- treeViewer.setSorter(sorter);
- }
-
- public void enableFuzzyMatching(boolean enable) {
- String pattern = "";
- if (matcher != null) {
- pattern = matcher.getPattern();
-
- if (!fuzzyMatchingEnabled && enable) {
- if (matcher.getPattern().trim().length() > 1 && matcher.getPattern().startsWith("*")
- && matcher.getPattern().endsWith("*"))
- pattern = pattern.substring(1).substring(0, pattern.length() - 2);
- matcher.setPattern(null);
- }
- }
- fuzzyMatchingEnabled = enable;
- initMatchers();
-
- matcher.setPattern(pattern);
- treeViewer.refresh();
- }
-
- public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
- }
-
- protected void initMatchers() {
- treeViewer.resetFilters();
-
- if (fuzzyMatchingEnabled) {
- matcher = new FuzzyMatcher(treeViewer);
- ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
- } else
- matcher = new ExactMatcher(treeViewer);
-
- }
-
- protected void initTreeViewer() {
- this.setRedraw(false);
- // init content provider
- contentProvider = new ResKeyTreeContentProvider(visibleLocales,
- projectName, resourceBundle, treeType);
- treeViewer.setContentProvider(contentProvider);
-
- // init label provider
- labelProvider = new ResKeyTreeLabelProvider(visibleLocales);
- treeViewer.setLabelProvider(labelProvider);
-
- // we need this to keep the tree expanded
- treeViewer.setComparer(new IElementComparer() {
-
- @Override
- public int hashCode(Object element) {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((toString() == null) ? 0 : toString().hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object a, Object b) {
- if (a == b) {
- return true;
- }
- if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
- IKeyTreeNode nodeA = (IKeyTreeNode) a;
- IKeyTreeNode nodeB = (IKeyTreeNode) b;
- return nodeA.equals(nodeB);
- }
- return false;
- }
- });
-
- setTreeStructure();
- this.setRedraw(true);
- }
-
- public void setTreeStructure() {
- IAbstractKeyTreeModel model = KeyTreeFactory.createModel(ResourceBundleManager.getManager(projectName).getResourceBundle(resourceBundle));
- if (treeViewer.getInput() == null) {
- treeViewer.setUseHashlookup(true);
- }
- org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer.getExpandedTreePaths();
- treeViewer.setInput(model);
- treeViewer.refresh();
- treeViewer.setExpandedTreePaths(expandedTreePaths);
- }
-
- protected void refreshContent(ResourceBundleChangedEvent event) {
- if (visibleLocales == null) {
- initVisibleLocales();
- }
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
-
- // update content provider
- contentProvider.setLocales(visibleLocales);
- contentProvider.setProjectName(manager.getProject().getName());
- contentProvider.setBundleId(resourceBundle);
-
- // init label provider
- IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
- labelProvider.setLocales(visibleLocales);
- if (treeViewer.getLabelProvider() != labelProvider)
- treeViewer.setLabelProvider(labelProvider);
-
- // define input of treeviewer
- setTreeStructure();
- }
-
- protected void initVisibleLocales() {
- SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>();
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- sortInfo = new SortInfo();
- visibleLocales.clear();
- if (resourceBundle != null) {
- for (Locale l : manager.getProvidedLocales(resourceBundle)) {
- if (l == null) {
- locSorted.put("Default", null);
- } else {
- locSorted.put(l.getDisplayName(uiLocale), l);
- }
- }
- }
-
- for (String lString : locSorted.keySet()) {
- visibleLocales.add(locSorted.get(lString));
- }
- sortInfo.setVisibleLocales(visibleLocales);
- }
-
- protected void constructWidget() {
- basicLayout = new TreeColumnLayout();
- this.setLayout(basicLayout);
-
- treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
- Tree tree = treeViewer.getTree();
-
- if (resourceBundle != null) {
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
-
- // create tree-columns
- constructTreeColumns(tree);
- } else {
- tree.setHeaderVisible(false);
- tree.setLinesVisible(false);
- }
-
- makeActions();
- hookDoubleClickAction();
-
- // register messages table as selection provider
- site.setSelectionProvider(treeViewer);
- }
-
- protected void constructTreeColumns(Tree tree) {
- tree.removeAll();
- //tree.getColumns().length;
-
- // construct key-column
- keyColumn = new TreeColumn(tree, SWT.NONE);
- keyColumn.setText("Key");
- keyColumn.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(0);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(0);
- }
- });
- basicLayout.setColumnData(keyColumn, new ColumnWeightData(KEY_COLUMN_WEIGHT));
-
- if (visibleLocales != null) {
- final ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- for (final Locale l : visibleLocales) {
- TreeColumn col = new TreeColumn(tree, SWT.NONE);
-
- // Add editing support to this table column
- TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col);
- tCol.setEditingSupport(new EditingSupport(treeViewer) {
-
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- boolean writeToFile = true;
-
- if (element instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
- String activeKey = vkti.getMessageKey();
-
- if (activeKey != null) {
- IMessagesBundleGroup bundleGroup = manager.getResourceBundle(resourceBundle);
- IMessage entry = bundleGroup.getMessage(activeKey, l);
-
- if (entry == null || !value.equals(entry.getValue())) {
- String comment = null;
- if (entry != null) {
- comment = entry.getComment();
- }
-
- IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(l);
-
- DirtyHack.setFireEnabled(false);
-
- IMessage message = messagesBundle.getMessage(activeKey);
- if (message == null) {
- IMessage newMessage = MessageFactory.createMessage(activeKey, l);
- newMessage.setText(String.valueOf(value));
- newMessage.setComment(comment);
- messagesBundle.addMessage(newMessage);
- } else {
- message.setText(String.valueOf(value));
- message.setComment(comment);
- }
-
- RBManager.getInstance(manager.getProject()).writeToFile(messagesBundle);
-
- // update TreeViewer
- vkti.setValue(l, String.valueOf(value));
- treeViewer.refresh();
-
- DirtyHack.setFireEnabled(true);
- }
- }
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, visibleLocales.indexOf(l) + 1);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer.getControl();
- editor = new TextCellEditor(tree);
- editor.getControl().addTraverseListener(new TraverseListener() {
-
- @Override
- public void keyTraversed(TraverseEvent e) {
- Logger.logInfo("CELL_EDITOR: " + e.toString());
- if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail ==
- SWT.TRAVERSE_TAB_PREVIOUS) {
-
- e.doit = false;
- int colIndex = visibleLocales.indexOf(l)+1;
- Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
- int noOfCols = treeViewer.getTree().getColumnCount();
-
- // go to next cell
- if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
- int nextColIndex = colIndex+1;
- if (nextColIndex < noOfCols)
- treeViewer.editElement(sel, nextColIndex);
- // go to previous cell
- } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
- int prevColIndex = colIndex-1;
- if (prevColIndex > 0)
- treeViewer.editElement(sel, colIndex-1);
- }
- }
- }
- });
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
-
- String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(uiLocale);
-
- col.setText(displayName);
- col.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(visibleLocales.indexOf(l) + 1);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(visibleLocales.indexOf(l) + 1);
- }
- });
- basicLayout.setColumnData(col, new ColumnWeightData(LOCALE_COLUMN_WEIGHT));
- }
- }
- }
-
- protected void updateSorter(int idx) {
- SortInfo sortInfo = sorter.getSortInfo();
- if (idx == sortInfo.getColIdx())
- sortInfo.setDESC(!sortInfo.isDESC());
- else {
- sortInfo.setColIdx(idx);
- sortInfo.setDESC(false);
- }
- sortInfo.setVisibleLocales(visibleLocales);
- sorter.setSortInfo(sortInfo);
- treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
- setTreeStructure();
- treeViewer.refresh();
- }
-
- @Override
- public boolean setFocus() {
- return treeViewer.getControl().setFocus();
- }
-
- /*** DRAG AND DROP ***/
- protected void hookDragAndDrop() {
- //KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource (treeViewer);
- KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
- MessagesDragSource source = new MessagesDragSource(treeViewer, this.resourceBundle);
- MessagesDropTarget target = new MessagesDropTarget(treeViewer, projectName, resourceBundle);
-
- // Initialize drag source for copy event
- DragSource dragSource = new DragSource(treeViewer.getControl(), DND.DROP_COPY | DND.DROP_MOVE);
- dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() });
- //dragSource.addDragListener(ktiSource);
- dragSource.addDragListener(source);
-
- // Initialize drop target for copy event
- DropTarget dropTarget = new DropTarget(treeViewer.getControl(), DND.DROP_MOVE | DND.DROP_COPY);
- dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(), JavaUI.getJavaElementClipboardTransfer() });
- dropTarget.addDropListener(ktiTarget);
- dropTarget.addDropListener(target);
- }
-
- /*** ACTIONS ***/
-
- private void makeActions() {
- doubleClickAction = new Action() {
-
- @Override
- public void run() {
- editSelectedItem();
- }
-
- };
- }
-
- private void hookDoubleClickAction() {
- treeViewer.addDoubleClickListener(new IDoubleClickListener() {
-
- public void doubleClick(DoubleClickEvent event) {
- doubleClickAction.run();
- }
- });
- }
-
- /*** SELECTION LISTENER ***/
-
- protected void registerListeners() {
-
- this.editorListener = new MessagesEditorListener();
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- if (manager != null) {
- RBManager.getInstance(manager.getProject()).addMessagesEditorListener(editorListener);
- }
-
- treeViewer.getControl().addKeyListener(new KeyAdapter() {
-
- public void keyPressed(KeyEvent event) {
- if (event.character == SWT.DEL && event.stateMask == 0) {
- deleteSelectedItems();
- }
- }
- });
- }
-
- protected void unregisterListeners() {
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- if (manager != null) {
- RBManager.getInstance(manager.getProject()).removeMessagesEditorListener(editorListener);
- }
- treeViewer.removeSelectionChangedListener(selectionChangedListener);
- }
-
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- treeViewer.addSelectionChangedListener(listener);
- selectionChangedListener = listener;
- }
-
- @Override
- public void resourceBundleChanged(final ResourceBundleChangedEvent event) {
- if (event.getType() != ResourceBundleChangedEvent.MODIFIED
- || !event.getBundle().equals(this.getResourceBundle()))
- return;
-
- if (Display.getCurrent() != null) {
- refreshViewer(event, true);
- return;
- }
-
- Display.getDefault().asyncExec(new Runnable() {
-
- public void run() {
- refreshViewer(event, true);
- }
- });
- }
-
- private void refreshViewer(ResourceBundleChangedEvent event, boolean computeVisibleLocales) {
- //manager.loadResourceBundle(resourceBundle);
- if (computeVisibleLocales) {
- refreshContent(event);
- }
-
- // Display.getDefault().asyncExec(new Runnable() {
- // public void run() {
- treeViewer.refresh();
- // }
- // });
- }
-
- public StructuredViewer getViewer() {
- return this.treeViewer;
- }
-
- public void setSearchString(String pattern) {
- matcher.setPattern(pattern);
- treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat : TreeType.Tree;
- labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
- // WTF?
- treeType = treeType.equals(TreeType.Tree) && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
- treeViewer.refresh();
- }
-
- public SortInfo getSortInfo() {
- if (this.sorter != null)
- return this.sorter.getSortInfo();
- else
- return null;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- sortInfo.setVisibleLocales(visibleLocales);
- if (sorter != null) {
- sorter.setSortInfo(sortInfo);
- treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
- treeViewer.refresh();
- }
- }
-
- public String getSearchString() {
- return matcher.getPattern();
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public String getResourceBundle() {
- return resourceBundle;
- }
-
- public void editSelectedItem() {
- String key = "";
- ISelection selection = treeViewer.getSelection();
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structSel = (IStructuredSelection) selection;
- if (structSel.getFirstElement() instanceof IKeyTreeNode) {
- IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel.getFirstElement();
- key = keyTreeNode.getMessageKey();
- }
- }
-
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- EditorUtils.openEditor(site.getPage(), manager.getRandomFile(resourceBundle),
- EditorUtils.RESOURCE_BUNDLE_EDITOR, key);
- }
-
- public void deleteSelectedItems() {
- List<String> keys = new ArrayList<String>();
-
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- ISelection selection = window.getActivePage().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IKeyTreeNode) {
- addKeysToRemove((IKeyTreeNode)elem, keys);
- }
- }
- }
-
- try {
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
- manager.removeResourceBundleEntry(getResourceBundle(), keys);
- } catch (Exception ex) {
- Logger.logError(ex);
- }
- }
-
- private void addKeysToRemove(IKeyTreeNode node, List<String> keys) {
- keys.add(node.getMessageKey());
- for (IKeyTreeNode ktn : node.getChildren()) {
- addKeysToRemove(ktn, keys);
- }
- }
-
- public void addNewItem(ISelection selection) {
- //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- String newKeyPrefix = "";
-
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof IKeyTreeNode) {
- newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
- break;
- }
- }
- }
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]" : "");
- config.setPreselectedMessage("");
- config.setPreselectedBundle(getResourceBundle());
- config.setPreselectedLocale("");
- config.setProjectName(projectName);
-
- dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK)
- return;
- }
-
- public void setMatchingPrecision(float value) {
- matchingPrecision = value;
- if (matcher instanceof FuzzyMatcher) {
- ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
- treeViewer.refresh();
- }
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- private class MessagesEditorListener implements IMessagesEditorListener {
- @Override
- public void onSave() {
- if (resourceBundle != null) {
- setTreeStructure();
- }
- }
-
- @Override
- public void onModify() {
- if (resourceBundle != null) {
- setTreeStructure();
- }
- }
-
- @Override
- public void onResourceChanged(IMessagesBundle bundle) {
- // TODO Auto-generated method stub
-
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+import org.eclipse.babel.core.configuration.DirtyHack;
+import org.eclipse.babel.core.message.manager.IMessagesEditorListener;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.editor.api.KeyTreeFactory;
+import org.eclipse.babel.editor.api.MessageFactory;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.model.view.SortInfo;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.KeyTreeItemDropTarget;
+import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDragSource;
+import org.eclipse.babel.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDropTarget;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.ExactMatcher;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.FuzzyMatcher;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.sorter.ValuedKeyTreeItemSorter;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.TreeType;
+import org.eclipse.jdt.ui.JavaUI;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.layout.TreeColumnLayout;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.IElementComparer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSource;
+import org.eclipse.swt.dnd.DropTarget;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.events.TraverseEvent;
+import org.eclipse.swt.events.TraverseListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.ui.IViewSite;
+import org.eclipse.ui.IWorkbenchPartSite;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+
+public class PropertyKeySelectionTree extends Composite implements IResourceBundleChangedListener {
+
+ private final int KEY_COLUMN_WEIGHT = 1;
+ private final int LOCALE_COLUMN_WEIGHT = 1;
+
+ private List<Locale> visibleLocales = new ArrayList<Locale>();
+ private boolean editable;
+ private String resourceBundle;
+
+ private IWorkbenchPartSite site;
+ private TreeColumnLayout basicLayout;
+ private TreeViewer treeViewer;
+ private TreeColumn keyColumn;
+ private boolean grouped = true;
+ private boolean fuzzyMatchingEnabled = false;
+ private float matchingPrecision = .75f;
+ private Locale uiLocale = new Locale("en");
+
+ private SortInfo sortInfo;
+
+ private ResKeyTreeContentProvider contentProvider;
+ private ResKeyTreeLabelProvider labelProvider;
+ private TreeType treeType = TreeType.Tree;
+
+ private IMessagesEditorListener editorListener;
+
+ /*** MATCHER ***/
+ ExactMatcher matcher;
+
+ /*** SORTER ***/
+ ValuedKeyTreeItemSorter sorter;
+
+ /*** ACTIONS ***/
+ private Action doubleClickAction;
+
+ /*** LISTENERS ***/
+ private ISelectionChangedListener selectionChangedListener;
+ private String projectName;
+
+ public PropertyKeySelectionTree(IViewSite viewSite, IWorkbenchPartSite site, Composite parent, int style,
+ String projectName, String resources, List<Locale> locales) {
+ super(parent, style);
+ this.site = site;
+ this.resourceBundle = resources;
+ this.projectName = projectName;
+
+ if (resourceBundle != null && resourceBundle.trim().length() > 0) {
+ if (locales == null)
+ initVisibleLocales();
+ else
+ this.visibleLocales = locales;
+ }
+
+ constructWidget();
+
+ if (resourceBundle != null && resourceBundle.trim().length() > 0) {
+ initTreeViewer();
+ initMatchers();
+ initSorters();
+ treeViewer.expandAll();
+ }
+
+ hookDragAndDrop();
+ registerListeners();
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ unregisterListeners();
+ }
+
+ protected void initSorters() {
+ sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo);
+ treeViewer.setSorter(sorter);
+ }
+
+ public void enableFuzzyMatching(boolean enable) {
+ String pattern = "";
+ if (matcher != null) {
+ pattern = matcher.getPattern();
+
+ if (!fuzzyMatchingEnabled && enable) {
+ if (matcher.getPattern().trim().length() > 1 && matcher.getPattern().startsWith("*")
+ && matcher.getPattern().endsWith("*"))
+ pattern = pattern.substring(1).substring(0, pattern.length() - 2);
+ matcher.setPattern(null);
+ }
+ }
+ fuzzyMatchingEnabled = enable;
+ initMatchers();
+
+ matcher.setPattern(pattern);
+ treeViewer.refresh();
+ }
+
+ public boolean isFuzzyMatchingEnabled() {
+ return fuzzyMatchingEnabled;
+ }
+
+ protected void initMatchers() {
+ treeViewer.resetFilters();
+
+ if (fuzzyMatchingEnabled) {
+ matcher = new FuzzyMatcher(treeViewer);
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
+ } else
+ matcher = new ExactMatcher(treeViewer);
+
+ }
+
+ protected void initTreeViewer() {
+ this.setRedraw(false);
+ // init content provider
+ contentProvider = new ResKeyTreeContentProvider(visibleLocales,
+ projectName, resourceBundle, treeType);
+ treeViewer.setContentProvider(contentProvider);
+
+ // init label provider
+ labelProvider = new ResKeyTreeLabelProvider(visibleLocales);
+ treeViewer.setLabelProvider(labelProvider);
+
+ // we need this to keep the tree expanded
+ treeViewer.setComparer(new IElementComparer() {
+
+ @Override
+ public int hashCode(Object element) {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((toString() == null) ? 0 : toString().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object a, Object b) {
+ if (a == b) {
+ return true;
+ }
+ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
+ IKeyTreeNode nodeA = (IKeyTreeNode) a;
+ IKeyTreeNode nodeB = (IKeyTreeNode) b;
+ return nodeA.equals(nodeB);
+ }
+ return false;
+ }
+ });
+
+ setTreeStructure();
+ this.setRedraw(true);
+ }
+
+ public void setTreeStructure() {
+ IAbstractKeyTreeModel model = KeyTreeFactory.createModel(ResourceBundleManager.getManager(projectName).getResourceBundle(resourceBundle));
+ if (treeViewer.getInput() == null) {
+ treeViewer.setUseHashlookup(true);
+ }
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer.getExpandedTreePaths();
+ treeViewer.setInput(model);
+ treeViewer.refresh();
+ treeViewer.setExpandedTreePaths(expandedTreePaths);
+ }
+
+ protected void refreshContent(ResourceBundleChangedEvent event) {
+ if (visibleLocales == null) {
+ initVisibleLocales();
+ }
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+
+ // update content provider
+ contentProvider.setLocales(visibleLocales);
+ contentProvider.setProjectName(manager.getProject().getName());
+ contentProvider.setBundleId(resourceBundle);
+
+ // init label provider
+ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
+ labelProvider.setLocales(visibleLocales);
+ if (treeViewer.getLabelProvider() != labelProvider)
+ treeViewer.setLabelProvider(labelProvider);
+
+ // define input of treeviewer
+ setTreeStructure();
+ }
+
+ protected void initVisibleLocales() {
+ SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>();
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+ sortInfo = new SortInfo();
+ visibleLocales.clear();
+ if (resourceBundle != null) {
+ for (Locale l : manager.getProvidedLocales(resourceBundle)) {
+ if (l == null) {
+ locSorted.put("Default", null);
+ } else {
+ locSorted.put(l.getDisplayName(uiLocale), l);
+ }
+ }
+ }
+
+ for (String lString : locSorted.keySet()) {
+ visibleLocales.add(locSorted.get(lString));
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ }
+
+ protected void constructWidget() {
+ basicLayout = new TreeColumnLayout();
+ this.setLayout(basicLayout);
+
+ treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER);
+ Tree tree = treeViewer.getTree();
+
+ if (resourceBundle != null) {
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
+
+ // create tree-columns
+ constructTreeColumns(tree);
+ } else {
+ tree.setHeaderVisible(false);
+ tree.setLinesVisible(false);
+ }
+
+ makeActions();
+ hookDoubleClickAction();
+
+ // register messages table as selection provider
+ site.setSelectionProvider(treeViewer);
+ }
+
+ protected void constructTreeColumns(Tree tree) {
+ tree.removeAll();
+ //tree.getColumns().length;
+
+ // construct key-column
+ keyColumn = new TreeColumn(tree, SWT.NONE);
+ keyColumn.setText("Key");
+ keyColumn.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+ });
+ basicLayout.setColumnData(keyColumn, new ColumnWeightData(KEY_COLUMN_WEIGHT));
+
+ if (visibleLocales != null) {
+ final ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+ for (final Locale l : visibleLocales) {
+ TreeColumn col = new TreeColumn(tree, SWT.NONE);
+
+ // Add editing support to this table column
+ TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col);
+ tCol.setEditingSupport(new EditingSupport(treeViewer) {
+
+ TextCellEditor editor = null;
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ boolean writeToFile = true;
+
+ if (element instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+ String activeKey = vkti.getMessageKey();
+
+ if (activeKey != null) {
+ IMessagesBundleGroup bundleGroup = manager.getResourceBundle(resourceBundle);
+ IMessage entry = bundleGroup.getMessage(activeKey, l);
+
+ if (entry == null || !value.equals(entry.getValue())) {
+ String comment = null;
+ if (entry != null) {
+ comment = entry.getComment();
+ }
+
+ IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(l);
+
+ DirtyHack.setFireEnabled(false);
+
+ IMessage message = messagesBundle.getMessage(activeKey);
+ if (message == null) {
+ IMessage newMessage = MessageFactory.createMessage(activeKey, l);
+ newMessage.setText(String.valueOf(value));
+ newMessage.setComment(comment);
+ messagesBundle.addMessage(newMessage);
+ } else {
+ message.setText(String.valueOf(value));
+ message.setComment(comment);
+ }
+
+ RBManager.getInstance(manager.getProject()).writeToFile(messagesBundle);
+
+ // update TreeViewer
+ vkti.setValue(l, String.valueOf(value));
+ treeViewer.refresh();
+
+ DirtyHack.setFireEnabled(true);
+ }
+ }
+ }
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ return labelProvider.getColumnText(element, visibleLocales.indexOf(l) + 1);
+ }
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ if (editor == null) {
+ Composite tree = (Composite) treeViewer.getControl();
+ editor = new TextCellEditor(tree);
+ editor.getControl().addTraverseListener(new TraverseListener() {
+
+ @Override
+ public void keyTraversed(TraverseEvent e) {
+ Logger.logInfo("CELL_EDITOR: " + e.toString());
+ if (e.detail == SWT.TRAVERSE_TAB_NEXT || e.detail ==
+ SWT.TRAVERSE_TAB_PREVIOUS) {
+
+ e.doit = false;
+ int colIndex = visibleLocales.indexOf(l)+1;
+ Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
+ int noOfCols = treeViewer.getTree().getColumnCount();
+
+ // go to next cell
+ if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
+ int nextColIndex = colIndex+1;
+ if (nextColIndex < noOfCols)
+ treeViewer.editElement(sel, nextColIndex);
+ // go to previous cell
+ } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
+ int prevColIndex = colIndex-1;
+ if (prevColIndex > 0)
+ treeViewer.editElement(sel, colIndex-1);
+ }
+ }
+ }
+ });
+ }
+ return editor;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
+
+ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(uiLocale);
+
+ col.setText(displayName);
+ col.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(visibleLocales.indexOf(l) + 1);
+ }
+ });
+ basicLayout.setColumnData(col, new ColumnWeightData(LOCALE_COLUMN_WEIGHT));
+ }
+ }
+ }
+
+ protected void updateSorter(int idx) {
+ SortInfo sortInfo = sorter.getSortInfo();
+ if (idx == sortInfo.getColIdx())
+ sortInfo.setDESC(!sortInfo.isDESC());
+ else {
+ sortInfo.setColIdx(idx);
+ sortInfo.setDESC(false);
+ }
+ sortInfo.setVisibleLocales(visibleLocales);
+ sorter.setSortInfo(sortInfo);
+ treeType = idx == 0 ? TreeType.Tree : TreeType.Flat;
+ setTreeStructure();
+ treeViewer.refresh();
+ }
+
+ @Override
+ public boolean setFocus() {
+ return treeViewer.getControl().setFocus();
+ }
+
+ /*** DRAG AND DROP ***/
+ protected void hookDragAndDrop() {
+ //KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource (treeViewer);
+ KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer);
+ MessagesDragSource source = new MessagesDragSource(treeViewer, this.resourceBundle);
+ MessagesDropTarget target = new MessagesDropTarget(treeViewer, projectName, resourceBundle);
+
+ // Initialize drag source for copy event
+ DragSource dragSource = new DragSource(treeViewer.getControl(), DND.DROP_COPY | DND.DROP_MOVE);
+ dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() });
+ //dragSource.addDragListener(ktiSource);
+ dragSource.addDragListener(source);
+
+ // Initialize drop target for copy event
+ DropTarget dropTarget = new DropTarget(treeViewer.getControl(), DND.DROP_MOVE | DND.DROP_COPY);
+ dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(), JavaUI.getJavaElementClipboardTransfer() });
+ dropTarget.addDropListener(ktiTarget);
+ dropTarget.addDropListener(target);
+ }
+
+ /*** ACTIONS ***/
+
+ private void makeActions() {
+ doubleClickAction = new Action() {
+
+ @Override
+ public void run() {
+ editSelectedItem();
+ }
+
+ };
+ }
+
+ private void hookDoubleClickAction() {
+ treeViewer.addDoubleClickListener(new IDoubleClickListener() {
+
+ public void doubleClick(DoubleClickEvent event) {
+ doubleClickAction.run();
+ }
+ });
+ }
+
+ /*** SELECTION LISTENER ***/
+
+ protected void registerListeners() {
+
+ this.editorListener = new MessagesEditorListener();
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject()).addMessagesEditorListener(editorListener);
+ }
+
+ treeViewer.getControl().addKeyListener(new KeyAdapter() {
+
+ public void keyPressed(KeyEvent event) {
+ if (event.character == SWT.DEL && event.stateMask == 0) {
+ deleteSelectedItems();
+ }
+ }
+ });
+ }
+
+ protected void unregisterListeners() {
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+ if (manager != null) {
+ RBManager.getInstance(manager.getProject()).removeMessagesEditorListener(editorListener);
+ }
+ treeViewer.removeSelectionChangedListener(selectionChangedListener);
+ }
+
+ public void addSelectionChangedListener(ISelectionChangedListener listener) {
+ treeViewer.addSelectionChangedListener(listener);
+ selectionChangedListener = listener;
+ }
+
+ @Override
+ public void resourceBundleChanged(final ResourceBundleChangedEvent event) {
+ if (event.getType() != ResourceBundleChangedEvent.MODIFIED
+ || !event.getBundle().equals(this.getResourceBundle()))
+ return;
+
+ if (Display.getCurrent() != null) {
+ refreshViewer(event, true);
+ return;
+ }
+
+ Display.getDefault().asyncExec(new Runnable() {
+
+ public void run() {
+ refreshViewer(event, true);
+ }
+ });
+ }
+
+ private void refreshViewer(ResourceBundleChangedEvent event, boolean computeVisibleLocales) {
+ //manager.loadResourceBundle(resourceBundle);
+ if (computeVisibleLocales) {
+ refreshContent(event);
+ }
+
+ // Display.getDefault().asyncExec(new Runnable() {
+ // public void run() {
+ treeViewer.refresh();
+ // }
+ // });
+ }
+
+ public StructuredViewer getViewer() {
+ return this.treeViewer;
+ }
+
+ public void setSearchString(String pattern) {
+ matcher.setPattern(pattern);
+ treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat : TreeType.Tree;
+ labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat));
+ // WTF?
+ treeType = treeType.equals(TreeType.Tree) && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
+ treeViewer.refresh();
+ }
+
+ public SortInfo getSortInfo() {
+ if (this.sorter != null)
+ return this.sorter.getSortInfo();
+ else
+ return null;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ sortInfo.setVisibleLocales(visibleLocales);
+ if (sorter != null) {
+ sorter.setSortInfo(sortInfo);
+ treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree : TreeType.Flat;
+ treeViewer.refresh();
+ }
+ }
+
+ public String getSearchString() {
+ return matcher.getPattern();
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public String getResourceBundle() {
+ return resourceBundle;
+ }
+
+ public void editSelectedItem() {
+ String key = "";
+ ISelection selection = treeViewer.getSelection();
+ if (selection instanceof IStructuredSelection) {
+ IStructuredSelection structSel = (IStructuredSelection) selection;
+ if (structSel.getFirstElement() instanceof IKeyTreeNode) {
+ IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel.getFirstElement();
+ key = keyTreeNode.getMessageKey();
+ }
+ }
+
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+ EditorUtils.openEditor(site.getPage(), manager.getRandomFile(resourceBundle),
+ EditorUtils.RESOURCE_BUNDLE_EDITOR, key);
+ }
+
+ public void deleteSelectedItems() {
+ List<String> keys = new ArrayList<String>();
+
+ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ ISelection selection = window.getActivePage().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ addKeysToRemove((IKeyTreeNode)elem, keys);
+ }
+ }
+ }
+
+ try {
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+ manager.removeResourceBundleEntry(getResourceBundle(), keys);
+ } catch (Exception ex) {
+ Logger.logError(ex);
+ }
+ }
+
+ private void addKeysToRemove(IKeyTreeNode node, List<String> keys) {
+ keys.add(node.getMessageKey());
+ for (IKeyTreeNode ktn : node.getChildren()) {
+ addKeysToRemove(ktn, keys);
+ }
+ }
+
+ public void addNewItem(ISelection selection) {
+ //event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ String newKeyPrefix = "";
+
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof IKeyTreeNode) {
+ newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey();
+ break;
+ }
+ }
+ }
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + "." + "[Platzhalter]" : "");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle(getResourceBundle());
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+ }
+
+ public void setMatchingPrecision(float value) {
+ matchingPrecision = value;
+ if (matcher instanceof FuzzyMatcher) {
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
+ treeViewer.refresh();
+ }
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ private class MessagesEditorListener implements IMessagesEditorListener {
+ @Override
+ public void onSave() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
+
+ @Override
+ public void onModify() {
+ if (resourceBundle != null) {
+ setTreeStructure();
+ }
+ }
+
+ @Override
+ public void onResourceChanged(IMessagesBundle bundle) {
+ // TODO Auto-generated method stub
+
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
index 9990ad7b..3fe4db34 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java
@@ -1,241 +1,248 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.editor.api.KeyTreeFactory;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ValueKeyTreeLabelProvider;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.TreeType;
-import org.eclipse.jface.layout.TreeColumnLayout;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.IElementComparer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-
-
-public class ResourceSelector extends Composite {
-
- public static final int DISPLAY_KEYS = 0;
- public static final int DISPLAY_TEXT = 1;
-
- private Locale displayLocale = null; // default
- private int displayMode;
- private String resourceBundle;
- private String projectName;
- private boolean showTree = true;
-
- private TreeViewer viewer;
- private TreeColumnLayout basicLayout;
- private TreeColumn entries;
- private Set<IResourceSelectionListener> listeners = new HashSet<IResourceSelectionListener>();
-
- // Viewer model
- private TreeType treeType = TreeType.Tree;
- private StyledCellLabelProvider labelProvider;
-
- public ResourceSelector(Composite parent,
- int style) {
- super(parent, style);
-
- initLayout (this);
- initViewer (this);
- }
-
- protected void updateContentProvider (IMessagesBundleGroup group) {
- // define input of treeviewer
- if (!showTree || displayMode == DISPLAY_TEXT) {
- treeType = TreeType.Flat;
- }
-
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
-
- IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager.getResourceBundle(resourceBundle));
- ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider)viewer.getContentProvider();
- contentProvider.setProjectName(manager.getProject().getName());
- contentProvider.setBundleId(resourceBundle);
- contentProvider.setTreeType(treeType);
- if (viewer.getInput() == null) {
- viewer.setUseHashlookup(true);
- }
-
-// viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
- org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer.getExpandedTreePaths();
- viewer.setInput(model);
- viewer.refresh();
- viewer.setExpandedTreePaths(expandedTreePaths);
- }
-
- protected void updateViewer (boolean updateContent) {
- IMessagesBundleGroup group = ResourceBundleManager.getManager(projectName).getResourceBundle(resourceBundle);
-
- if (group == null)
- return;
-
- if (displayMode == DISPLAY_TEXT) {
- labelProvider = new ValueKeyTreeLabelProvider(group.getMessagesBundle(displayLocale));
- treeType = TreeType.Flat;
- ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
- } else {
- labelProvider = new ResKeyTreeLabelProvider(null);
- treeType = TreeType.Tree;
- ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
- }
-
- viewer.setLabelProvider(labelProvider);
- if (updateContent)
- updateContentProvider(group);
- }
-
- protected void initLayout (Composite parent) {
- basicLayout = new TreeColumnLayout();
- parent.setLayout(basicLayout);
- }
-
- protected void initViewer (Composite parent) {
- viewer = new TreeViewer (parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
- Tree table = viewer.getTree();
-
- // Init table-columns
- entries = new TreeColumn (table, SWT.NONE);
- basicLayout.setColumnData(entries, new ColumnWeightData(1));
-
- viewer.setContentProvider(new ResKeyTreeContentProvider());
- viewer.addSelectionChangedListener(new ISelectionChangedListener() {
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection = event.getSelection();
- String selectionSummary = "";
- String selectedKey = "";
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
-
- if (selection instanceof IStructuredSelection) {
- Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection).iterator();
- if (itSel.hasNext()) {
- IKeyTreeNode selItem = itSel.next();
- IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
- selectedKey = selItem.getMessageKey();
-
- if (group == null)
- return;
- Iterator<Locale> itLocales = manager.getProvidedLocales(resourceBundle).iterator();
- while (itLocales.hasNext()) {
- Locale l = itLocales.next();
- try {
- selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayLanguage()) + ":\n";
- selectionSummary += "\t" + group.getMessagesBundle(l).getMessage(selItem.getMessageKey()).getValue() + "\n";
- } catch (Exception e) {}
- }
- }
- }
-
- // construct ResourceSelectionEvent
- ResourceSelectionEvent e = new ResourceSelectionEvent(selectedKey, selectionSummary);
- fireSelectionChanged(e);
- }
- });
-
- // we need this to keep the tree expanded
- viewer.setComparer(new IElementComparer() {
-
- @Override
- public int hashCode(Object element) {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((toString() == null) ? 0 : toString().hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object a, Object b) {
- if (a == b) {
- return true;
- }
- if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
- IKeyTreeNode nodeA = (IKeyTreeNode) a;
- IKeyTreeNode nodeB = (IKeyTreeNode) b;
- return nodeA.equals(nodeB);
- }
- return false;
- }
- });
- }
-
- public Locale getDisplayLocale() {
- return displayLocale;
- }
-
- public void setDisplayLocale(Locale displayLocale) {
- this.displayLocale = displayLocale;
- updateViewer(false);
- }
-
- public int getDisplayMode() {
- return displayMode;
- }
-
- public void setDisplayMode(int displayMode) {
- this.displayMode = displayMode;
- updateViewer(true);
- }
-
- public void setResourceBundle(String resourceBundle) {
- this.resourceBundle = resourceBundle;
- updateViewer(true);
- }
-
- public String getResourceBundle() {
- return resourceBundle;
- }
-
- public void addSelectionChangedListener (IResourceSelectionListener l) {
- listeners.add(l);
- }
-
- public void removeSelectionChangedListener (IResourceSelectionListener l) {
- listeners.remove(l);
- }
-
- private void fireSelectionChanged (ResourceSelectionEvent event) {
- Iterator<IResourceSelectionListener> itResList = listeners.iterator();
- while (itResList.hasNext()) {
- itResList.next().selectionChanged(event);
- }
- }
-
- public void setProjectName(String projectName) {
- this.projectName = projectName;
- }
-
- public boolean isShowTree() {
- return showTree;
- }
-
- public void setShowTree(boolean showTree) {
- if (this.showTree != showTree) {
- this.showTree = showTree;
- this.treeType = showTree ? TreeType.Tree : TreeType.Flat;
- updateViewer(false);
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.editor.api.KeyTreeFactory;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.provider.ValueKeyTreeLabelProvider;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.TreeType;
+import org.eclipse.jface.layout.TreeColumnLayout;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.IElementComparer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+
+
+public class ResourceSelector extends Composite {
+
+ public static final int DISPLAY_KEYS = 0;
+ public static final int DISPLAY_TEXT = 1;
+
+ private Locale displayLocale = null; // default
+ private int displayMode;
+ private String resourceBundle;
+ private String projectName;
+ private boolean showTree = true;
+
+ private TreeViewer viewer;
+ private TreeColumnLayout basicLayout;
+ private TreeColumn entries;
+ private Set<IResourceSelectionListener> listeners = new HashSet<IResourceSelectionListener>();
+
+ // Viewer model
+ private TreeType treeType = TreeType.Tree;
+ private StyledCellLabelProvider labelProvider;
+
+ public ResourceSelector(Composite parent,
+ int style) {
+ super(parent, style);
+
+ initLayout (this);
+ initViewer (this);
+ }
+
+ protected void updateContentProvider (IMessagesBundleGroup group) {
+ // define input of treeviewer
+ if (!showTree || displayMode == DISPLAY_TEXT) {
+ treeType = TreeType.Flat;
+ }
+
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+
+ IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager.getResourceBundle(resourceBundle));
+ ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider)viewer.getContentProvider();
+ contentProvider.setProjectName(manager.getProject().getName());
+ contentProvider.setBundleId(resourceBundle);
+ contentProvider.setTreeType(treeType);
+ if (viewer.getInput() == null) {
+ viewer.setUseHashlookup(true);
+ }
+
+// viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
+ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer.getExpandedTreePaths();
+ viewer.setInput(model);
+ viewer.refresh();
+ viewer.setExpandedTreePaths(expandedTreePaths);
+ }
+
+ protected void updateViewer (boolean updateContent) {
+ IMessagesBundleGroup group = ResourceBundleManager.getManager(projectName).getResourceBundle(resourceBundle);
+
+ if (group == null)
+ return;
+
+ if (displayMode == DISPLAY_TEXT) {
+ labelProvider = new ValueKeyTreeLabelProvider(group.getMessagesBundle(displayLocale));
+ treeType = TreeType.Flat;
+ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
+ } else {
+ labelProvider = new ResKeyTreeLabelProvider(null);
+ treeType = TreeType.Tree;
+ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType);
+ }
+
+ viewer.setLabelProvider(labelProvider);
+ if (updateContent)
+ updateContentProvider(group);
+ }
+
+ protected void initLayout (Composite parent) {
+ basicLayout = new TreeColumnLayout();
+ parent.setLayout(basicLayout);
+ }
+
+ protected void initViewer (Composite parent) {
+ viewer = new TreeViewer (parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
+ Tree table = viewer.getTree();
+
+ // Init table-columns
+ entries = new TreeColumn (table, SWT.NONE);
+ basicLayout.setColumnData(entries, new ColumnWeightData(1));
+
+ viewer.setContentProvider(new ResKeyTreeContentProvider());
+ viewer.addSelectionChangedListener(new ISelectionChangedListener() {
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ ISelection selection = event.getSelection();
+ String selectionSummary = "";
+ String selectedKey = "";
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+
+ if (selection instanceof IStructuredSelection) {
+ Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection).iterator();
+ if (itSel.hasNext()) {
+ IKeyTreeNode selItem = itSel.next();
+ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle);
+ selectedKey = selItem.getMessageKey();
+
+ if (group == null)
+ return;
+ Iterator<Locale> itLocales = manager.getProvidedLocales(resourceBundle).iterator();
+ while (itLocales.hasNext()) {
+ Locale l = itLocales.next();
+ try {
+ selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayLanguage()) + ":\n";
+ selectionSummary += "\t" + group.getMessagesBundle(l).getMessage(selItem.getMessageKey()).getValue() + "\n";
+ } catch (Exception e) {}
+ }
+ }
+ }
+
+ // construct ResourceSelectionEvent
+ ResourceSelectionEvent e = new ResourceSelectionEvent(selectedKey, selectionSummary);
+ fireSelectionChanged(e);
+ }
+ });
+
+ // we need this to keep the tree expanded
+ viewer.setComparer(new IElementComparer() {
+
+ @Override
+ public int hashCode(Object element) {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result
+ + ((toString() == null) ? 0 : toString().hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object a, Object b) {
+ if (a == b) {
+ return true;
+ }
+ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) {
+ IKeyTreeNode nodeA = (IKeyTreeNode) a;
+ IKeyTreeNode nodeB = (IKeyTreeNode) b;
+ return nodeA.equals(nodeB);
+ }
+ return false;
+ }
+ });
+ }
+
+ public Locale getDisplayLocale() {
+ return displayLocale;
+ }
+
+ public void setDisplayLocale(Locale displayLocale) {
+ this.displayLocale = displayLocale;
+ updateViewer(false);
+ }
+
+ public int getDisplayMode() {
+ return displayMode;
+ }
+
+ public void setDisplayMode(int displayMode) {
+ this.displayMode = displayMode;
+ updateViewer(true);
+ }
+
+ public void setResourceBundle(String resourceBundle) {
+ this.resourceBundle = resourceBundle;
+ updateViewer(true);
+ }
+
+ public String getResourceBundle() {
+ return resourceBundle;
+ }
+
+ public void addSelectionChangedListener (IResourceSelectionListener l) {
+ listeners.add(l);
+ }
+
+ public void removeSelectionChangedListener (IResourceSelectionListener l) {
+ listeners.remove(l);
+ }
+
+ private void fireSelectionChanged (ResourceSelectionEvent event) {
+ Iterator<IResourceSelectionListener> itResList = listeners.iterator();
+ while (itResList.hasNext()) {
+ itResList.next().selectionChanged(event);
+ }
+ }
+
+ public void setProjectName(String projectName) {
+ this.projectName = projectName;
+ }
+
+ public boolean isShowTree() {
+ return showTree;
+ }
+
+ public void setShowTree(boolean showTree) {
+ if (this.showTree != showTree) {
+ this.showTree = showTree;
+ this.treeType = showTree ? TreeType.Tree : TreeType.Flat;
+ updateViewer(false);
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
index 20bf334a..fcf714f4 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
@@ -1,31 +1,38 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.event;
-
-public class ResourceSelectionEvent {
-
- private String selectionSummary;
- private String selectedKey;
-
- public ResourceSelectionEvent (String selectedKey, String selectionSummary) {
- this.setSelectionSummary(selectionSummary);
- this.setSelectedKey(selectedKey);
- }
-
- public void setSelectedKey (String key) {
- selectedKey = key;
- }
-
- public void setSelectionSummary(String selectionSummary) {
- this.selectionSummary = selectionSummary;
- }
-
- public String getSelectionSummary() {
- return selectionSummary;
- }
-
- public String getSelectedKey() {
- return selectedKey;
- }
-
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.event;
+
+public class ResourceSelectionEvent {
+
+ private String selectionSummary;
+ private String selectedKey;
+
+ public ResourceSelectionEvent (String selectedKey, String selectionSummary) {
+ this.setSelectionSummary(selectionSummary);
+ this.setSelectedKey(selectedKey);
+ }
+
+ public void setSelectedKey (String key) {
+ selectedKey = key;
+ }
+
+ public void setSelectionSummary(String selectionSummary) {
+ this.selectionSummary = selectionSummary;
+ }
+
+ public String getSelectionSummary() {
+ return selectionSummary;
+ }
+
+ public String getSelectedKey() {
+ return selectedKey;
+ }
+
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
index 68bcc2be..c019c468 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
@@ -1,77 +1,84 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
-
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-
-public class ExactMatcher extends ViewerFilter {
-
- protected final StructuredViewer viewer;
- protected String pattern = "";
- protected StringMatcher matcher;
-
- public ExactMatcher (StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public String getPattern () {
- return pattern;
- }
-
- public void setPattern (String p) {
- boolean filtering = matcher != null;
- if (p != null && p.trim().length() > 0) {
- pattern = p;
- matcher = new StringMatcher ("*" + pattern + "*", true, false);
- if (!filtering)
- viewer.addFilter(this);
- else
- viewer.refresh();
- } else {
- pattern = "";
- matcher = null;
- if (filtering) {
- viewer.removeFilter(this);
- }
- }
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = matcher.match(vEle.getMessageKey());
-
- if (selected) {
- int start = -1;
- while ((start = vEle.getMessageKey().toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
- filterInfo.addKeyOccurrence(start, pattern.length());
- }
- filterInfo.setFoundInKey(selected);
- filterInfo.setFoundInKey(true);
- } else
- filterInfo.setFoundInKey(false);
-
- // Iterate translations
- for (Locale l : vEle.getLocales()) {
- String value = vEle.getValue(l);
- if (matcher.match(value)) {
- filterInfo.addFoundInLocale(l);
- filterInfo.addSimilarity(l, 1d);
- int start = -1;
- while ((start = value.toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
- filterInfo.addFoundInLocaleRange(l, start, pattern.length());
- }
- selected = true;
- }
- }
-
- vEle.setInfo(filterInfo);
- return selected;
- }
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+
+public class ExactMatcher extends ViewerFilter {
+
+ protected final StructuredViewer viewer;
+ protected String pattern = "";
+ protected StringMatcher matcher;
+
+ public ExactMatcher (StructuredViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public String getPattern () {
+ return pattern;
+ }
+
+ public void setPattern (String p) {
+ boolean filtering = matcher != null;
+ if (p != null && p.trim().length() > 0) {
+ pattern = p;
+ matcher = new StringMatcher ("*" + pattern + "*", true, false);
+ if (!filtering)
+ viewer.addFilter(this);
+ else
+ viewer.refresh();
+ } else {
+ pattern = "";
+ matcher = null;
+ if (filtering) {
+ viewer.removeFilter(this);
+ }
+ }
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element;
+ FilterInfo filterInfo = new FilterInfo();
+ boolean selected = matcher.match(vEle.getMessageKey());
+
+ if (selected) {
+ int start = -1;
+ while ((start = vEle.getMessageKey().toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
+ filterInfo.addKeyOccurrence(start, pattern.length());
+ }
+ filterInfo.setFoundInKey(selected);
+ filterInfo.setFoundInKey(true);
+ } else
+ filterInfo.setFoundInKey(false);
+
+ // Iterate translations
+ for (Locale l : vEle.getLocales()) {
+ String value = vEle.getValue(l);
+ if (matcher.match(value)) {
+ filterInfo.addFoundInLocale(l);
+ filterInfo.addSimilarity(l, 1d);
+ int start = -1;
+ while ((start = value.toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
+ filterInfo.addFoundInLocaleRange(l, start, pattern.length());
+ }
+ selected = true;
+ }
+ }
+
+ vEle.setInfo(filterInfo);
+ return selected;
+ }
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
index d0f708a6..f8344096 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
@@ -1,84 +1,91 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.jface.text.Region;
-
-public class FilterInfo {
-
- private boolean foundInKey;
- private List<Locale> foundInLocales = new ArrayList<Locale> ();
- private List<Region> keyOccurrences = new ArrayList<Region> ();
- private Double keySimilarity;
- private Map<Locale, List<Region>> occurrences = new HashMap<Locale, List<Region>>();
- private Map<Locale, Double> localeSimilarity = new HashMap<Locale, Double>();
-
- public FilterInfo() {
-
- }
-
- public void setKeySimilarity (Double similarity) {
- keySimilarity = similarity;
- }
-
- public Double getKeySimilarity () {
- return keySimilarity;
- }
-
- public void addSimilarity (Locale l, Double similarity) {
- localeSimilarity.put (l, similarity);
- }
-
- public Double getSimilarityLevel (Locale l) {
- return localeSimilarity.get(l);
- }
-
- public void setFoundInKey(boolean foundInKey) {
- this.foundInKey = foundInKey;
- }
-
- public boolean isFoundInKey() {
- return foundInKey;
- }
-
- public void addFoundInLocale (Locale loc) {
- foundInLocales.add(loc);
- }
-
- public void removeFoundInLocale (Locale loc) {
- foundInLocales.remove(loc);
- }
-
- public void clearFoundInLocale () {
- foundInLocales.clear();
- }
-
- public boolean hasFoundInLocale (Locale l) {
- return foundInLocales.contains(l);
- }
-
- public List<Region> getFoundInLocaleRanges (Locale locale) {
- List<Region> reg = occurrences.get(locale);
- return (reg == null ? new ArrayList<Region>() : reg);
- }
-
- public void addFoundInLocaleRange (Locale locale, int start, int length) {
- List<Region> regions = occurrences.get(locale);
- if (regions == null)
- regions = new ArrayList<Region>();
- regions.add(new Region(start, length));
- occurrences.put(locale, regions);
- }
-
- public List<Region> getKeyOccurrences () {
- return keyOccurrences;
- }
-
- public void addKeyOccurrence (int start, int length) {
- keyOccurrences.add(new Region (start, length));
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.eclipse.jface.text.Region;
+
+public class FilterInfo {
+
+ private boolean foundInKey;
+ private List<Locale> foundInLocales = new ArrayList<Locale> ();
+ private List<Region> keyOccurrences = new ArrayList<Region> ();
+ private Double keySimilarity;
+ private Map<Locale, List<Region>> occurrences = new HashMap<Locale, List<Region>>();
+ private Map<Locale, Double> localeSimilarity = new HashMap<Locale, Double>();
+
+ public FilterInfo() {
+
+ }
+
+ public void setKeySimilarity (Double similarity) {
+ keySimilarity = similarity;
+ }
+
+ public Double getKeySimilarity () {
+ return keySimilarity;
+ }
+
+ public void addSimilarity (Locale l, Double similarity) {
+ localeSimilarity.put (l, similarity);
+ }
+
+ public Double getSimilarityLevel (Locale l) {
+ return localeSimilarity.get(l);
+ }
+
+ public void setFoundInKey(boolean foundInKey) {
+ this.foundInKey = foundInKey;
+ }
+
+ public boolean isFoundInKey() {
+ return foundInKey;
+ }
+
+ public void addFoundInLocale (Locale loc) {
+ foundInLocales.add(loc);
+ }
+
+ public void removeFoundInLocale (Locale loc) {
+ foundInLocales.remove(loc);
+ }
+
+ public void clearFoundInLocale () {
+ foundInLocales.clear();
+ }
+
+ public boolean hasFoundInLocale (Locale l) {
+ return foundInLocales.contains(l);
+ }
+
+ public List<Region> getFoundInLocaleRanges (Locale locale) {
+ List<Region> reg = occurrences.get(locale);
+ return (reg == null ? new ArrayList<Region>() : reg);
+ }
+
+ public void addFoundInLocaleRange (Locale locale, int start, int length) {
+ List<Region> regions = occurrences.get(locale);
+ if (regions == null)
+ regions = new ArrayList<Region>();
+ regions.add(new Region(start, length));
+ occurrences.put(locale, regions);
+ }
+
+ public List<Region> getKeyOccurrences () {
+ return keyOccurrences;
+ }
+
+ public void addKeyOccurrence (int start, int length) {
+ keyOccurrences.add(new Region (start, length));
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
index dcba7e5d..91518be4 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
@@ -1,54 +1,61 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
-
-import java.util.Locale;
-
-import org.eclipse.babel.editor.api.AnalyzerFactory;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-
-public class FuzzyMatcher extends ExactMatcher {
-
- protected ILevenshteinDistanceAnalyzer lvda;
- protected float minimumSimilarity = 0.75f;
-
- public FuzzyMatcher(StructuredViewer viewer) {
- super(viewer);
- lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();;
- }
-
- public double getMinimumSimilarity () {
- return minimumSimilarity;
- }
-
- public void setMinimumSimilarity (float similarity) {
- this.minimumSimilarity = similarity;
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- boolean exactMatch = super.select(viewer, parentElement, element);
- boolean match = exactMatch;
-
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
- FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
-
- for (Locale l : vkti.getLocales()) {
- String value = vkti.getValue(l);
- if (filterInfo.hasFoundInLocale(l))
- continue;
- double dist = lvda.analyse(value, getPattern());
- if (dist >= minimumSimilarity) {
- filterInfo.addFoundInLocale(l);
- filterInfo.addSimilarity(l, dist);
- match = true;
- filterInfo.addFoundInLocaleRange(l, 0, value.length());
- }
- }
-
- vkti.setInfo(filterInfo);
- return match;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
+
+import java.util.Locale;
+
+import org.eclipse.babel.editor.api.AnalyzerFactory;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+
+public class FuzzyMatcher extends ExactMatcher {
+
+ protected ILevenshteinDistanceAnalyzer lvda;
+ protected float minimumSimilarity = 0.75f;
+
+ public FuzzyMatcher(StructuredViewer viewer) {
+ super(viewer);
+ lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();;
+ }
+
+ public double getMinimumSimilarity () {
+ return minimumSimilarity;
+ }
+
+ public void setMinimumSimilarity (float similarity) {
+ this.minimumSimilarity = similarity;
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ boolean exactMatch = super.select(viewer, parentElement, element);
+ boolean match = exactMatch;
+
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+ FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
+
+ for (Locale l : vkti.getLocales()) {
+ String value = vkti.getValue(l);
+ if (filterInfo.hasFoundInLocale(l))
+ continue;
+ double dist = lvda.analyse(value, getPattern());
+ if (dist >= minimumSimilarity) {
+ filterInfo.addFoundInLocale(l);
+ filterInfo.addSimilarity(l, dist);
+ match = true;
+ filterInfo.addFoundInLocaleRange(l, 0, value.length());
+ }
+ }
+
+ vkti.setInfo(filterInfo);
+ return match;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
index 2aa75464..181eb687 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
@@ -1,441 +1,448 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
-
-import java.util.Vector;
-
-/**
- * A string pattern matcher, suppporting "*" and "?" wildcards.
- */
-public class StringMatcher {
- protected String fPattern;
-
- protected int fLength; // pattern length
-
- protected boolean fIgnoreWildCards;
-
- protected boolean fIgnoreCase;
-
- protected boolean fHasLeadingStar;
-
- protected boolean fHasTrailingStar;
-
- protected String fSegments[]; //the given pattern is split into * separated segments
-
- /* boundary value beyond which we don't need to search in the text */
- protected int fBound = 0;
-
- protected static final char fSingleWildCard = '\u0000';
-
- public static class Position {
- int start; //inclusive
-
- int end; //exclusive
-
- public Position(int start, int end) {
- this.start = start;
- this.end = end;
- }
-
- public int getStart() {
- return start;
- }
-
- public int getEnd() {
- return end;
- }
- }
-
- /**
- * StringMatcher constructor takes in a String object that is a simple
- * pattern which may contain '*' for 0 and many characters and
- * '?' for exactly one character.
- *
- * Literal '*' and '?' characters must be escaped in the pattern
- * e.g., "\*" means literal "*", etc.
- *
- * Escaping any other character (including the escape character itself),
- * just results in that character in the pattern.
- * e.g., "\a" means "a" and "\\" means "\"
- *
- * If invoking the StringMatcher with string literals in Java, don't forget
- * escape characters are represented by "\\".
- *
- * @param pattern the pattern to match text against
- * @param ignoreCase if true, case is ignored
- * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
- * (everything is taken literally).
- */
- public StringMatcher(String pattern, boolean ignoreCase,
- boolean ignoreWildCards) {
- if (pattern == null) {
- throw new IllegalArgumentException();
- }
- fIgnoreCase = ignoreCase;
- fIgnoreWildCards = ignoreWildCards;
- fPattern = pattern;
- fLength = pattern.length();
-
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
- }
-
- /**
- * Find the first occurrence of the pattern between <code>start</code)(inclusive)
- * and <code>end</code>(exclusive).
- * @param text the String object to search in
- * @param start the starting index of the search range, inclusive
- * @param end the ending index of the search range, exclusive
- * @return an <code>StringMatcher.Position</code> object that keeps the starting
- * (inclusive) and ending positions (exclusive) of the first occurrence of the
- * pattern in the specified range of the text; return null if not found or subtext
- * is empty (start==end). A pair of zeros is returned if pattern is empty string
- * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
- * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
- */
- public StringMatcher.Position find(String text, int start, int end) {
- if (text == null) {
- throw new IllegalArgumentException();
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
- if (end < 0 || start >= end) {
- return null;
- }
- if (fLength == 0) {
- return new Position(start, start);
- }
- if (fIgnoreWildCards) {
- int x = posIn(text, start, end);
- if (x < 0) {
- return null;
- }
- return new Position(x, x + fLength);
- }
-
- int segCount = fSegments.length;
- if (segCount == 0) {
- return new Position(start, end);
- }
-
- int curPos = start;
- int matchStart = -1;
- int i;
- for (i = 0; i < segCount && curPos < end; ++i) {
- String current = fSegments[i];
- int nextMatch = regExpPosIn(text, curPos, end, current);
- if (nextMatch < 0) {
- return null;
- }
- if (i == 0) {
- matchStart = nextMatch;
- }
- curPos = nextMatch + current.length();
- }
- if (i < segCount) {
- return null;
- }
- return new Position(matchStart, curPos);
- }
-
- /**
- * match the given <code>text</code> with the pattern
- * @return true if matched otherwise false
- * @param text a String object
- */
- public boolean match(String text) {
- if(text == null) {
- return false;
- }
- return match(text, 0, text.length());
- }
-
- /**
- * Given the starting (inclusive) and the ending (exclusive) positions in the
- * <code>text</code>, determine if the given substring matches with aPattern
- * @return true if the specified portion of the text matches the pattern
- * @param text a String object that contains the substring to match
- * @param start marks the starting position (inclusive) of the substring
- * @param end marks the ending index (exclusive) of the substring
- */
- public boolean match(String text, int start, int end) {
- if (null == text) {
- throw new IllegalArgumentException();
- }
-
- if (start > end) {
- return false;
- }
-
- if (fIgnoreWildCards) {
- return (end - start == fLength)
- && fPattern.regionMatches(fIgnoreCase, 0, text, start,
- fLength);
- }
- int segCount = fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
- return true;
- }
- if (start == end) {
- return fLength == 0;
- }
- if (fLength == 0) {
- return start == end;
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
-
- int tCurPos = start;
- int bound = end - fBound;
- if (bound < 0) {
- return false;
- }
- int i = 0;
- String current = fSegments[i];
- int segLength = current.length();
-
- /* process first segment */
- if (!fHasLeadingStar) {
- if (!regExpRegionMatches(text, start, current, 0, segLength)) {
- return false;
- } else {
- ++i;
- tCurPos = tCurPos + segLength;
- }
- }
- if ((fSegments.length == 1) && (!fHasLeadingStar)
- && (!fHasTrailingStar)) {
- // only one segment to match, no wildcards specified
- return tCurPos == end;
- }
- /* process middle segments */
- while (i < segCount) {
- current = fSegments[i];
- int currentMatch;
- int k = current.indexOf(fSingleWildCard);
- if (k < 0) {
- currentMatch = textPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- } else {
- currentMatch = regExpPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- }
- tCurPos = currentMatch + current.length();
- i++;
- }
-
- /* process final segment */
- if (!fHasTrailingStar && tCurPos != end) {
- int clen = current.length();
- return regExpRegionMatches(text, end - clen, current, 0, clen);
- }
- return i == segCount;
- }
-
- /**
- * This method parses the given pattern into segments seperated by wildcard '*' characters.
- * Since wildcards are not being used in this case, the pattern consists of a single segment.
- */
- private void parseNoWildCards() {
- fSegments = new String[1];
- fSegments[0] = fPattern;
- fBound = fLength;
- }
-
- /**
- * Parses the given pattern into segments seperated by wildcard '*' characters.
- * @param p, a String object that is a simple regular expression with '*' and/or '?'
- */
- private void parseWildCards() {
- if (fPattern.startsWith("*")) { //$NON-NLS-1$
- fHasLeadingStar = true;
- }
- if (fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar = true;
- }
- }
-
- Vector temp = new Vector();
-
- int pos = 0;
- StringBuffer buf = new StringBuffer();
- while (pos < fLength) {
- char c = fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next = fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
-
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
-
- fSegments = new String[temp.size()];
- temp.copyInto(fSegments);
- }
-
- /**
- * @param text a string which contains no wildcard
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int posIn(String text, int start, int end) {//no wild card in pattern
- int max = end - fLength;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(fPattern, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength)) {
- return i;
- }
- }
-
- return -1;
- }
-
- /**
- * @param text a simple regular expression that may only contain '?'(s)
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a simple regular expression that may contains '?'
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int regExpPosIn(String text, int start, int end, String p) {
- int plen = p.length();
-
- int max = end - plen;
- for (int i = start; i <= max; ++i) {
- if (regExpRegionMatches(text, i, p, 0, plen)) {
- return i;
- }
- }
- return -1;
- }
-
- /**
- *
- * @return boolean
- * @param text a String to match
- * @param start int that indicates the starting index of match, inclusive
- * @param end</code> int that indicates the ending index of match, exclusive
- * @param p String, String, a simple regular expression that may contain '?'
- * @param ignoreCase boolean indicating wether code>p</code> is case sensitive
- */
- protected boolean regExpRegionMatches(String text, int tStart, String p,
- int pStart, int plen) {
- while (plen-- > 0) {
- char tchar = text.charAt(tStart++);
- char pchar = p.charAt(pStart++);
-
- /* process wild cards */
- if (!fIgnoreWildCards) {
- /* skip single wild cards */
- if (pchar == fSingleWildCard) {
- continue;
- }
- }
- if (pchar == tchar) {
- continue;
- }
- if (fIgnoreCase) {
- if (Character.toUpperCase(tchar) == Character
- .toUpperCase(pchar)) {
- continue;
- }
- // comparing after converting to upper case doesn't handle all cases;
- // also compare after converting to lower case
- if (Character.toLowerCase(tchar) == Character
- .toLowerCase(pchar)) {
- continue;
- }
- }
- return false;
- }
- return true;
- }
-
- /**
- * @param text the string to match
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a pattern string that has no wildcard
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int textPosIn(String text, int start, int end, String p) {
-
- int plen = p.length();
- int max = end - plen;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(p, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen)) {
- return i;
- }
- }
-
- return -1;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.filter;
+
+import java.util.Vector;
+
+/**
+ * A string pattern matcher, suppporting "*" and "?" wildcards.
+ */
+public class StringMatcher {
+ protected String fPattern;
+
+ protected int fLength; // pattern length
+
+ protected boolean fIgnoreWildCards;
+
+ protected boolean fIgnoreCase;
+
+ protected boolean fHasLeadingStar;
+
+ protected boolean fHasTrailingStar;
+
+ protected String fSegments[]; //the given pattern is split into * separated segments
+
+ /* boundary value beyond which we don't need to search in the text */
+ protected int fBound = 0;
+
+ protected static final char fSingleWildCard = '\u0000';
+
+ public static class Position {
+ int start; //inclusive
+
+ int end; //exclusive
+
+ public Position(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ public int getStart() {
+ return start;
+ }
+
+ public int getEnd() {
+ return end;
+ }
+ }
+
+ /**
+ * StringMatcher constructor takes in a String object that is a simple
+ * pattern which may contain '*' for 0 and many characters and
+ * '?' for exactly one character.
+ *
+ * Literal '*' and '?' characters must be escaped in the pattern
+ * e.g., "\*" means literal "*", etc.
+ *
+ * Escaping any other character (including the escape character itself),
+ * just results in that character in the pattern.
+ * e.g., "\a" means "a" and "\\" means "\"
+ *
+ * If invoking the StringMatcher with string literals in Java, don't forget
+ * escape characters are represented by "\\".
+ *
+ * @param pattern the pattern to match text against
+ * @param ignoreCase if true, case is ignored
+ * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
+ * (everything is taken literally).
+ */
+ public StringMatcher(String pattern, boolean ignoreCase,
+ boolean ignoreWildCards) {
+ if (pattern == null) {
+ throw new IllegalArgumentException();
+ }
+ fIgnoreCase = ignoreCase;
+ fIgnoreWildCards = ignoreWildCards;
+ fPattern = pattern;
+ fLength = pattern.length();
+
+ if (fIgnoreWildCards) {
+ parseNoWildCards();
+ } else {
+ parseWildCards();
+ }
+ }
+
+ /**
+ * Find the first occurrence of the pattern between <code>start</code)(inclusive)
+ * and <code>end</code>(exclusive).
+ * @param text the String object to search in
+ * @param start the starting index of the search range, inclusive
+ * @param end the ending index of the search range, exclusive
+ * @return an <code>StringMatcher.Position</code> object that keeps the starting
+ * (inclusive) and ending positions (exclusive) of the first occurrence of the
+ * pattern in the specified range of the text; return null if not found or subtext
+ * is empty (start==end). A pair of zeros is returned if pattern is empty string
+ * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
+ * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
+ */
+ public StringMatcher.Position find(String text, int start, int end) {
+ if (text == null) {
+ throw new IllegalArgumentException();
+ }
+
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+ if (end < 0 || start >= end) {
+ return null;
+ }
+ if (fLength == 0) {
+ return new Position(start, start);
+ }
+ if (fIgnoreWildCards) {
+ int x = posIn(text, start, end);
+ if (x < 0) {
+ return null;
+ }
+ return new Position(x, x + fLength);
+ }
+
+ int segCount = fSegments.length;
+ if (segCount == 0) {
+ return new Position(start, end);
+ }
+
+ int curPos = start;
+ int matchStart = -1;
+ int i;
+ for (i = 0; i < segCount && curPos < end; ++i) {
+ String current = fSegments[i];
+ int nextMatch = regExpPosIn(text, curPos, end, current);
+ if (nextMatch < 0) {
+ return null;
+ }
+ if (i == 0) {
+ matchStart = nextMatch;
+ }
+ curPos = nextMatch + current.length();
+ }
+ if (i < segCount) {
+ return null;
+ }
+ return new Position(matchStart, curPos);
+ }
+
+ /**
+ * match the given <code>text</code> with the pattern
+ * @return true if matched otherwise false
+ * @param text a String object
+ */
+ public boolean match(String text) {
+ if(text == null) {
+ return false;
+ }
+ return match(text, 0, text.length());
+ }
+
+ /**
+ * Given the starting (inclusive) and the ending (exclusive) positions in the
+ * <code>text</code>, determine if the given substring matches with aPattern
+ * @return true if the specified portion of the text matches the pattern
+ * @param text a String object that contains the substring to match
+ * @param start marks the starting position (inclusive) of the substring
+ * @param end marks the ending index (exclusive) of the substring
+ */
+ public boolean match(String text, int start, int end) {
+ if (null == text) {
+ throw new IllegalArgumentException();
+ }
+
+ if (start > end) {
+ return false;
+ }
+
+ if (fIgnoreWildCards) {
+ return (end - start == fLength)
+ && fPattern.regionMatches(fIgnoreCase, 0, text, start,
+ fLength);
+ }
+ int segCount = fSegments.length;
+ if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
+ return true;
+ }
+ if (start == end) {
+ return fLength == 0;
+ }
+ if (fLength == 0) {
+ return start == end;
+ }
+
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+
+ int tCurPos = start;
+ int bound = end - fBound;
+ if (bound < 0) {
+ return false;
+ }
+ int i = 0;
+ String current = fSegments[i];
+ int segLength = current.length();
+
+ /* process first segment */
+ if (!fHasLeadingStar) {
+ if (!regExpRegionMatches(text, start, current, 0, segLength)) {
+ return false;
+ } else {
+ ++i;
+ tCurPos = tCurPos + segLength;
+ }
+ }
+ if ((fSegments.length == 1) && (!fHasLeadingStar)
+ && (!fHasTrailingStar)) {
+ // only one segment to match, no wildcards specified
+ return tCurPos == end;
+ }
+ /* process middle segments */
+ while (i < segCount) {
+ current = fSegments[i];
+ int currentMatch;
+ int k = current.indexOf(fSingleWildCard);
+ if (k < 0) {
+ currentMatch = textPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ } else {
+ currentMatch = regExpPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ }
+ tCurPos = currentMatch + current.length();
+ i++;
+ }
+
+ /* process final segment */
+ if (!fHasTrailingStar && tCurPos != end) {
+ int clen = current.length();
+ return regExpRegionMatches(text, end - clen, current, 0, clen);
+ }
+ return i == segCount;
+ }
+
+ /**
+ * This method parses the given pattern into segments seperated by wildcard '*' characters.
+ * Since wildcards are not being used in this case, the pattern consists of a single segment.
+ */
+ private void parseNoWildCards() {
+ fSegments = new String[1];
+ fSegments[0] = fPattern;
+ fBound = fLength;
+ }
+
+ /**
+ * Parses the given pattern into segments seperated by wildcard '*' characters.
+ * @param p, a String object that is a simple regular expression with '*' and/or '?'
+ */
+ private void parseWildCards() {
+ if (fPattern.startsWith("*")) { //$NON-NLS-1$
+ fHasLeadingStar = true;
+ }
+ if (fPattern.endsWith("*")) {//$NON-NLS-1$
+ /* make sure it's not an escaped wildcard */
+ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
+ fHasTrailingStar = true;
+ }
+ }
+
+ Vector temp = new Vector();
+
+ int pos = 0;
+ StringBuffer buf = new StringBuffer();
+ while (pos < fLength) {
+ char c = fPattern.charAt(pos++);
+ switch (c) {
+ case '\\':
+ if (pos >= fLength) {
+ buf.append(c);
+ } else {
+ char next = fPattern.charAt(pos++);
+ /* if it's an escape sequence */
+ if (next == '*' || next == '?' || next == '\\') {
+ buf.append(next);
+ } else {
+ /* not an escape sequence, just insert literally */
+ buf.append(c);
+ buf.append(next);
+ }
+ }
+ break;
+ case '*':
+ if (buf.length() > 0) {
+ /* new segment */
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ buf.setLength(0);
+ }
+ break;
+ case '?':
+ /* append special character representing single match wildcard */
+ buf.append(fSingleWildCard);
+ break;
+ default:
+ buf.append(c);
+ }
+ }
+
+ /* add last buffer to segment list */
+ if (buf.length() > 0) {
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ }
+
+ fSegments = new String[temp.size()];
+ temp.copyInto(fSegments);
+ }
+
+ /**
+ * @param text a string which contains no wildcard
+ * @param start the starting index in the text for search, inclusive
+ * @param end the stopping point of search, exclusive
+ * @return the starting index in the text of the pattern , or -1 if not found
+ */
+ protected int posIn(String text, int start, int end) {//no wild card in pattern
+ int max = end - fLength;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(fPattern, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
+
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, fPattern, 0, fLength)) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ /**
+ * @param text a simple regular expression that may only contain '?'(s)
+ * @param start the starting index in the text for search, inclusive
+ * @param end the stopping point of search, exclusive
+ * @param p a simple regular expression that may contains '?'
+ * @return the starting index in the text of the pattern , or -1 if not found
+ */
+ protected int regExpPosIn(String text, int start, int end, String p) {
+ int plen = p.length();
+
+ int max = end - plen;
+ for (int i = start; i <= max; ++i) {
+ if (regExpRegionMatches(text, i, p, 0, plen)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ *
+ * @return boolean
+ * @param text a String to match
+ * @param start int that indicates the starting index of match, inclusive
+ * @param end</code> int that indicates the ending index of match, exclusive
+ * @param p String, String, a simple regular expression that may contain '?'
+ * @param ignoreCase boolean indicating wether code>p</code> is case sensitive
+ */
+ protected boolean regExpRegionMatches(String text, int tStart, String p,
+ int pStart, int plen) {
+ while (plen-- > 0) {
+ char tchar = text.charAt(tStart++);
+ char pchar = p.charAt(pStart++);
+
+ /* process wild cards */
+ if (!fIgnoreWildCards) {
+ /* skip single wild cards */
+ if (pchar == fSingleWildCard) {
+ continue;
+ }
+ }
+ if (pchar == tchar) {
+ continue;
+ }
+ if (fIgnoreCase) {
+ if (Character.toUpperCase(tchar) == Character
+ .toUpperCase(pchar)) {
+ continue;
+ }
+ // comparing after converting to upper case doesn't handle all cases;
+ // also compare after converting to lower case
+ if (Character.toLowerCase(tchar) == Character
+ .toLowerCase(pchar)) {
+ continue;
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * @param text the string to match
+ * @param start the starting index in the text for search, inclusive
+ * @param end the stopping point of search, exclusive
+ * @param p a pattern string that has no wildcard
+ * @return the starting index in the text of the pattern , or -1 if not found
+ */
+ protected int textPosIn(String text, int start, int end, String p) {
+
+ int plen = p.length();
+ int max = end - plen;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(p, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
+
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, p, 0, plen)) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
index 8ae2fe68..80422753 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
@@ -1,9 +1,16 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.listener;
-
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
-
-public interface IResourceSelectionListener {
-
- public void selectionChanged (ResourceSelectionEvent e);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.listener;
+
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+
+public interface IResourceSelectionListener {
+
+ public void selectionChanged (ResourceSelectionEvent e);
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
index d720d03c..5b99d847 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
@@ -1,166 +1,173 @@
- /*
-+ * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
- *
- * This file is part of Essiembre ResourceBundle Editor.
- *
- * Essiembre ResourceBundle Editor 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.
- *
- * Essiembre ResourceBundle Editor 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 Essiembre ResourceBundle Editor; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
- * Boston, MA 02111-1307 USA
- */
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.util.FontUtils;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * Label provider for key tree viewer.
- * @author Pascal Essiembre ([email protected])
- * @version $Author: nl_carnage $ $Revision: 1.11 $ $Date: 2007/09/11 16:11:09 $
- */
-public class KeyTreeLabelProvider
- extends StyledCellLabelProvider /*implements IFontProvider, IColorProvider*/ {
-
- private static final int KEY_DEFAULT = 1 << 1;
- private static final int KEY_COMMENTED = 1 << 2;
- private static final int KEY_NOT = 1 << 3;
- private static final int WARNING = 1 << 4;
- private static final int WARNING_GREY = 1 << 5;
-
- /** Registry instead of UIUtils one for image not keyed by file name. */
- private static ImageRegistry imageRegistry = new ImageRegistry();
-
- private Color commentedColor = FontUtils.getSystemColor(SWT.COLOR_GRAY);
-
- /** Group font. */
- private Font groupFontKey = FontUtils.createFont(SWT.BOLD);
- private Font groupFontNoKey = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
-
-
- /**
- * @see ILabelProvider#getImage(Object)
- */
- public Image getImage(Object element) {
- IKeyTreeNode treeItem = ((IKeyTreeNode) element);
-
- int iconFlags = 0;
-
- // Figure out background icon
- if (treeItem.getMessagesBundleGroup() != null &&
- treeItem.getMessagesBundleGroup().isKey(treeItem.getMessageKey())) {
- iconFlags += KEY_DEFAULT;
- } else {
- iconFlags += KEY_NOT;
- }
-
- return generateImage(iconFlags);
- }
-
- /**
- * @see ILabelProvider#getText(Object)
- */
- public String getText(Object element) {
- return ((IKeyTreeNode) element).getName();
- }
-
- /**
- * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
- */
- public void dispose() {
- groupFontKey.dispose();
- groupFontNoKey.dispose();
- }
-
- /**
- * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
- */
- public Font getFont(Object element) {
- IKeyTreeNode item = (IKeyTreeNode) element;
- if (item.getChildren().length > 0 && item.getMessagesBundleGroup() != null) {
- if (item.getMessagesBundleGroup().isKey(item.getMessageKey())) {
- return groupFontKey;
- }
- return groupFontNoKey;
- }
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
- */
- public Color getForeground(Object element) {
- IKeyTreeNode treeItem = (IKeyTreeNode) element;
- return null;
- }
-
- /**
- * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
- */
- public Color getBackground(Object element) {
- // TODO Auto-generated method stub
- return null;
- }
-
- /**
- * Generates an image based on icon flags.
- * @param iconFlags
- * @return generated image
- */
- private Image generateImage(int iconFlags) {
- Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
- if (image == null) {
- // Figure background image
- if ((iconFlags & KEY_COMMENTED) != 0) {
- image = getRegistryImage("keyCommented.gif"); //$NON-NLS-1$
- } else if ((iconFlags & KEY_NOT) != 0) {
- image = getRegistryImage("key.gif"); //$NON-NLS-1$
- } else {
- image = getRegistryImage("key.gif"); //$NON-NLS-1$
- }
-
- }
- return image;
- }
-
-
- private Image getRegistryImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = Activator.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
-
- @Override
- public void update(ViewerCell cell) {
- cell.setBackground(getBackground(cell.getElement()));
- cell.setFont(getFont(cell.getElement()));
- cell.setForeground(getForeground(cell.getElement()));
-
- cell.setText(getText(cell.getElement()));
- cell.setImage(getImage(cell.getElement()));
- super.update(cell);
- }
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * 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
+ ******************************************************************************/
+ /*
++ * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc.
+ *
+ * This file is part of Essiembre ResourceBundle Editor.
+ *
+ * Essiembre ResourceBundle Editor 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.
+ *
+ * Essiembre ResourceBundle Editor 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 Essiembre ResourceBundle Editor; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307 USA
+ */
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.util.FontUtils;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Label provider for key tree viewer.
+ * @author Pascal Essiembre ([email protected])
+ * @version $Author: nl_carnage $ $Revision: 1.11 $ $Date: 2007/09/11 16:11:09 $
+ */
+public class KeyTreeLabelProvider
+ extends StyledCellLabelProvider /*implements IFontProvider, IColorProvider*/ {
+
+ private static final int KEY_DEFAULT = 1 << 1;
+ private static final int KEY_COMMENTED = 1 << 2;
+ private static final int KEY_NOT = 1 << 3;
+ private static final int WARNING = 1 << 4;
+ private static final int WARNING_GREY = 1 << 5;
+
+ /** Registry instead of UIUtils one for image not keyed by file name. */
+ private static ImageRegistry imageRegistry = new ImageRegistry();
+
+ private Color commentedColor = FontUtils.getSystemColor(SWT.COLOR_GRAY);
+
+ /** Group font. */
+ private Font groupFontKey = FontUtils.createFont(SWT.BOLD);
+ private Font groupFontNoKey = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
+
+
+ /**
+ * @see ILabelProvider#getImage(Object)
+ */
+ public Image getImage(Object element) {
+ IKeyTreeNode treeItem = ((IKeyTreeNode) element);
+
+ int iconFlags = 0;
+
+ // Figure out background icon
+ if (treeItem.getMessagesBundleGroup() != null &&
+ treeItem.getMessagesBundleGroup().isKey(treeItem.getMessageKey())) {
+ iconFlags += KEY_DEFAULT;
+ } else {
+ iconFlags += KEY_NOT;
+ }
+
+ return generateImage(iconFlags);
+ }
+
+ /**
+ * @see ILabelProvider#getText(Object)
+ */
+ public String getText(Object element) {
+ return ((IKeyTreeNode) element).getName();
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+ groupFontKey.dispose();
+ groupFontNoKey.dispose();
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
+ */
+ public Font getFont(Object element) {
+ IKeyTreeNode item = (IKeyTreeNode) element;
+ if (item.getChildren().length > 0 && item.getMessagesBundleGroup() != null) {
+ if (item.getMessagesBundleGroup().isKey(item.getMessageKey())) {
+ return groupFontKey;
+ }
+ return groupFontNoKey;
+ }
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
+ */
+ public Color getForeground(Object element) {
+ IKeyTreeNode treeItem = (IKeyTreeNode) element;
+ return null;
+ }
+
+ /**
+ * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
+ */
+ public Color getBackground(Object element) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ /**
+ * Generates an image based on icon flags.
+ * @param iconFlags
+ * @return generated image
+ */
+ private Image generateImage(int iconFlags) {
+ Image image = imageRegistry.get("" + iconFlags); //$NON-NLS-1$
+ if (image == null) {
+ // Figure background image
+ if ((iconFlags & KEY_COMMENTED) != 0) {
+ image = getRegistryImage("keyCommented.gif"); //$NON-NLS-1$
+ } else if ((iconFlags & KEY_NOT) != 0) {
+ image = getRegistryImage("key.gif"); //$NON-NLS-1$
+ } else {
+ image = getRegistryImage("key.gif"); //$NON-NLS-1$
+ }
+
+ }
+ return image;
+ }
+
+
+ private Image getRegistryImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ image = Activator.getImageDescriptor(imageName).createImage();
+ imageRegistry.put(imageName, image);
+ }
+ return image;
+ }
+
+ @Override
+ public void update(ViewerCell cell) {
+ cell.setBackground(getBackground(cell.getElement()));
+ cell.setFont(getFont(cell.getElement()));
+ cell.setForeground(getForeground(cell.getElement()));
+
+ cell.setText(getText(cell.getElement()));
+ cell.setImage(getImage(cell.getElement()));
+ super.update(cell);
+ }
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
index 8268e624..c323b6e2 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
@@ -1,16 +1,23 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
-
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.swt.graphics.Image;
-
-public class LightKeyTreeLabelProvider extends KeyTreeLabelProvider implements ITableLabelProvider {
- @Override
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
- @Override
- public String getColumnText(Object element, int columnIndex) {
- return super.getText(element);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.swt.graphics.Image;
+
+public class LightKeyTreeLabelProvider extends KeyTreeLabelProvider implements ITableLabelProvider {
+ @Override
+ public Image getColumnImage(Object element, int columnIndex) {
+ return null;
+ }
+
+ @Override
+ public String getColumnText(Object element, int columnIndex) {
+ return super.getText(element);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
index f8af7ec2..e3ed078b 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
@@ -1,211 +1,218 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.editor.api.KeyTreeFactory;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.TreeType;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-
-
-
-public class ResKeyTreeContentProvider implements ITreeContentProvider {
-
- private IAbstractKeyTreeModel keyTreeModel;
- private Viewer viewer;
-
- private TreeType treeType = TreeType.Tree;
-
- /** Viewer this provided act upon. */
- protected TreeViewer treeViewer;
-
- private List<Locale> locales;
- private String bundleId;
- private String projectName;
-
- public ResKeyTreeContentProvider (List<Locale> locales, String projectName, String bundleId, TreeType treeType) {
- this.locales = locales;
- this.projectName = projectName;
- this.bundleId = bundleId;
- this.treeType = treeType;
- }
-
- public void setBundleId (String bundleId) {
- this.bundleId = bundleId;
- }
-
- public void setProjectName (String projectName) {
- this.projectName = projectName;
- }
-
- public ResKeyTreeContentProvider() {
- locales = new ArrayList<Locale>();
- }
-
- public void setLocales (List<Locale> locales) {
- this.locales = locales;
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- IKeyTreeNode parentNode = (IKeyTreeNode) parentElement;
- switch (treeType) {
- case Tree:
- return convertKTItoVKTI(keyTreeModel.getChildren(parentNode));
- case Flat:
- return new IKeyTreeNode[0];
- default:
- // Should not happen
- return new IKeyTreeNode[0];
- }
- }
-
- protected Object[] convertKTItoVKTI (Object[] children) {
- Collection<IValuedKeyTreeNode> items = new ArrayList<IValuedKeyTreeNode>();
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(this.projectName).getMessagesBundleGroup(this.bundleId);
-
- for (Object o : children) {
- if (o instanceof IValuedKeyTreeNode)
- items.add((IValuedKeyTreeNode)o);
- else {
- IKeyTreeNode kti = (IKeyTreeNode) o;
- IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(kti.getParent(), kti.getName(), kti.getMessageKey(), messagesBundleGroup);
-
- for (IKeyTreeNode k : kti.getChildren()) {
- vkti.addChild(k);
- }
-
- // init translations
- for (Locale l : locales) {
- try {
- IMessage message = messagesBundleGroup.getMessagesBundle(l).getMessage(kti.getMessageKey());
- if (message != null) {
- vkti.addValue(l, message.getValue());
- }
- } catch (Exception e) {}
- }
- items.add(vkti);
- }
- }
-
- return items.toArray();
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- switch (treeType) {
- case Tree:
- return convertKTItoVKTI(keyTreeModel.getRootNodes());
- case Flat:
- final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>();
- IKeyTreeVisitor visitor = new IKeyTreeVisitor() {
- public void visitKeyTreeNode(IKeyTreeNode node) {
- if (node.isUsedAsKey()) {
- actualKeys.add(node);
- }
- }
- };
- keyTreeModel.accept(visitor, keyTreeModel.getRootNode());
-
- return actualKeys.toArray();
- default:
- // Should not happen
- return new IKeyTreeNode[0];
- }
- }
-
- @Override
- public Object getParent(Object element) {
- IKeyTreeNode node = (IKeyTreeNode) element;
- switch (treeType) {
- case Tree:
- return keyTreeModel.getParent(node);
- case Flat:
- return keyTreeModel;
- default:
- // Should not happen
- return null;
- }
- }
-
- /**
- * @see ITreeContentProvider#hasChildren(Object)
- */
- public boolean hasChildren(Object element) {
- switch (treeType) {
- case Tree:
- return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0;
- case Flat:
- return false;
- default:
- // Should not happen
- return false;
- }
- }
-
- public int countChildren(Object element) {
-
- if (element instanceof IKeyTreeNode) {
- return ((IKeyTreeNode)element).getChildren().length;
- } else if (element instanceof IValuedKeyTreeNode) {
- return ((IValuedKeyTreeNode)element).getChildren().length;
- } else {
- System.out.println("wait a minute");
- return 1;
- }
- }
-
- /**
- * Gets the selected key tree item.
- * @return key tree item
- */
- private IKeyTreeNode getTreeSelection() {
- IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection();
- return ((IKeyTreeNode) selection.getFirstElement());
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- this.viewer = (TreeViewer) viewer;
- this.keyTreeModel = (IAbstractKeyTreeModel) newInput;
- }
-
- public IMessagesBundleGroup getBundle() {
- return RBManager.getInstance(projectName).getMessagesBundleGroup(this.bundleId);
- }
-
- public String getBundleId() {
- return bundleId;
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- public TreeType getTreeType() {
- return treeType;
- }
-
- public void setTreeType(TreeType treeType) {
- if (this.treeType != treeType) {
- this.treeType = treeType;
- if (viewer != null) {
- viewer.refresh();
- }
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.editor.api.KeyTreeFactory;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.TreeType;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+
+
+
+public class ResKeyTreeContentProvider implements ITreeContentProvider {
+
+ private IAbstractKeyTreeModel keyTreeModel;
+ private Viewer viewer;
+
+ private TreeType treeType = TreeType.Tree;
+
+ /** Viewer this provided act upon. */
+ protected TreeViewer treeViewer;
+
+ private List<Locale> locales;
+ private String bundleId;
+ private String projectName;
+
+ public ResKeyTreeContentProvider (List<Locale> locales, String projectName, String bundleId, TreeType treeType) {
+ this.locales = locales;
+ this.projectName = projectName;
+ this.bundleId = bundleId;
+ this.treeType = treeType;
+ }
+
+ public void setBundleId (String bundleId) {
+ this.bundleId = bundleId;
+ }
+
+ public void setProjectName (String projectName) {
+ this.projectName = projectName;
+ }
+
+ public ResKeyTreeContentProvider() {
+ locales = new ArrayList<Locale>();
+ }
+
+ public void setLocales (List<Locale> locales) {
+ this.locales = locales;
+ }
+
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ IKeyTreeNode parentNode = (IKeyTreeNode) parentElement;
+ switch (treeType) {
+ case Tree:
+ return convertKTItoVKTI(keyTreeModel.getChildren(parentNode));
+ case Flat:
+ return new IKeyTreeNode[0];
+ default:
+ // Should not happen
+ return new IKeyTreeNode[0];
+ }
+ }
+
+ protected Object[] convertKTItoVKTI (Object[] children) {
+ Collection<IValuedKeyTreeNode> items = new ArrayList<IValuedKeyTreeNode>();
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(this.projectName).getMessagesBundleGroup(this.bundleId);
+
+ for (Object o : children) {
+ if (o instanceof IValuedKeyTreeNode)
+ items.add((IValuedKeyTreeNode)o);
+ else {
+ IKeyTreeNode kti = (IKeyTreeNode) o;
+ IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(kti.getParent(), kti.getName(), kti.getMessageKey(), messagesBundleGroup);
+
+ for (IKeyTreeNode k : kti.getChildren()) {
+ vkti.addChild(k);
+ }
+
+ // init translations
+ for (Locale l : locales) {
+ try {
+ IMessage message = messagesBundleGroup.getMessagesBundle(l).getMessage(kti.getMessageKey());
+ if (message != null) {
+ vkti.addValue(l, message.getValue());
+ }
+ } catch (Exception e) {}
+ }
+ items.add(vkti);
+ }
+ }
+
+ return items.toArray();
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ switch (treeType) {
+ case Tree:
+ return convertKTItoVKTI(keyTreeModel.getRootNodes());
+ case Flat:
+ final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>();
+ IKeyTreeVisitor visitor = new IKeyTreeVisitor() {
+ public void visitKeyTreeNode(IKeyTreeNode node) {
+ if (node.isUsedAsKey()) {
+ actualKeys.add(node);
+ }
+ }
+ };
+ keyTreeModel.accept(visitor, keyTreeModel.getRootNode());
+
+ return actualKeys.toArray();
+ default:
+ // Should not happen
+ return new IKeyTreeNode[0];
+ }
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ IKeyTreeNode node = (IKeyTreeNode) element;
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getParent(node);
+ case Flat:
+ return keyTreeModel;
+ default:
+ // Should not happen
+ return null;
+ }
+ }
+
+ /**
+ * @see ITreeContentProvider#hasChildren(Object)
+ */
+ public boolean hasChildren(Object element) {
+ switch (treeType) {
+ case Tree:
+ return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0;
+ case Flat:
+ return false;
+ default:
+ // Should not happen
+ return false;
+ }
+ }
+
+ public int countChildren(Object element) {
+
+ if (element instanceof IKeyTreeNode) {
+ return ((IKeyTreeNode)element).getChildren().length;
+ } else if (element instanceof IValuedKeyTreeNode) {
+ return ((IValuedKeyTreeNode)element).getChildren().length;
+ } else {
+ System.out.println("wait a minute");
+ return 1;
+ }
+ }
+
+ /**
+ * Gets the selected key tree item.
+ * @return key tree item
+ */
+ private IKeyTreeNode getTreeSelection() {
+ IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection();
+ return ((IKeyTreeNode) selection.getFirstElement());
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ this.viewer = (TreeViewer) viewer;
+ this.keyTreeModel = (IAbstractKeyTreeModel) newInput;
+ }
+
+ public IMessagesBundleGroup getBundle() {
+ return RBManager.getInstance(projectName).getMessagesBundleGroup(this.bundleId);
+ }
+
+ public String getBundleId() {
+ return bundleId;
+ }
+
+ @Override
+ public void dispose() {
+ // TODO Auto-generated method stub
+
+ }
+
+ public TreeType getTreeType() {
+ return treeType;
+ }
+
+ public void setTreeType(TreeType treeType) {
+ if (this.treeType != treeType) {
+ this.treeType = treeType;
+ if (viewer != null) {
+ viewer.refresh();
+ }
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
index 1a923dd2..332edd0e 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
@@ -1,153 +1,160 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.FilterInfo;
-import org.eclipse.babel.tapiji.tools.core.util.FontUtils;
-import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-
-
-public class ResKeyTreeLabelProvider extends KeyTreeLabelProvider {
-
- private List<Locale> locales;
- private boolean searchEnabled = false;
-
- /*** COLORS ***/
- private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
- private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
- private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
-
- /*** FONTS ***/
- private Font bold = FontUtils.createFont(SWT.BOLD);
- private Font bold_italic = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
-
- public ResKeyTreeLabelProvider (List<Locale> locales) {
- this.locales = locales;
- }
-
- //@Override
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == 0) {
- IKeyTreeNode kti = (IKeyTreeNode) element;
- IMessage[] be = kti.getMessagesBundleGroup().getMessages(kti.getMessageKey());
- boolean incomplete = false;
-
- if (be.length != kti.getMessagesBundleGroup().getMessagesBundleCount())
- incomplete = true;
- else {
- for (IMessage b : be) {
- if (b.getValue() == null || b.getValue().trim().length() == 0) {
- incomplete = true;
- break;
- }
- }
- }
-
- if (incomplete)
- return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE);
- else
- return ImageUtils.getImage(ImageUtils.ICON_RESOURCE);
- }
- return null;
- }
-
- //@Override
- public String getColumnText(Object element, int columnIndex) {
- if (columnIndex == 0)
- return super.getText(element);
-
- if (columnIndex <= locales.size()) {
- IValuedKeyTreeNode item = (IValuedKeyTreeNode) element;
- String entry = item.getValue(locales.get(columnIndex-1));
- if (entry != null) {
- return entry;
- }
- }
- return "";
- }
-
- public void setSearchEnabled (boolean enabled) {
- this.searchEnabled = enabled;
- }
-
- public boolean isSearchEnabled () {
- return this.searchEnabled;
- }
-
- public void setLocales(List<Locale> visibleLocales) {
- locales = visibleLocales;
- }
-
- protected boolean isMatchingToPattern (Object element, int columnIndex) {
- boolean matching = false;
-
- if (element instanceof IValuedKeyTreeNode) {
- IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
-
- if (vkti.getInfo() == null)
- return false;
-
- FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
-
- if (columnIndex == 0) {
- matching = filterInfo.isFoundInKey();
- } else {
- matching = filterInfo.hasFoundInLocale(locales.get(columnIndex-1));
- }
- }
-
- return matching;
- }
-
- protected boolean isSearchEnabled (Object element) {
- return (element instanceof IValuedKeyTreeNode && searchEnabled );
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int columnIndex = cell.getColumnIndex();
-
- if (isSearchEnabled(element)) {
- if (isMatchingToPattern(element, columnIndex) ) {
- List<StyleRange> styleRanges = new ArrayList<StyleRange>();
- FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode)element).getInfo();
-
- if (columnIndex > 0) {
- for (Region reg : filterInfo.getFoundInLocaleRanges(locales.get(columnIndex-1))) {
- styleRanges.add(new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD));
- }
- } else {
- // check if the pattern has been found within the key section
- if (filterInfo.isFoundInKey()) {
- for (Region reg : filterInfo.getKeyOccurrences()) {
- StyleRange sr = new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD);
- styleRanges.add(sr);
- }
- }
- }
- cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()]));
- } else {
- cell.setForeground(gray);
- }
- } else if (columnIndex == 0)
- super.update(cell);
-
- cell.setImage(this.getColumnImage(element, columnIndex));
- cell.setText(this.getColumnText(element, columnIndex));
- }
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.widgets.filter.FilterInfo;
+import org.eclipse.babel.tapiji.tools.core.util.FontUtils;
+import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+
+
+public class ResKeyTreeLabelProvider extends KeyTreeLabelProvider {
+
+ private List<Locale> locales;
+ private boolean searchEnabled = false;
+
+ /*** COLORS ***/
+ private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
+ private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
+ private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
+
+ /*** FONTS ***/
+ private Font bold = FontUtils.createFont(SWT.BOLD);
+ private Font bold_italic = FontUtils.createFont(SWT.BOLD | SWT.ITALIC);
+
+ public ResKeyTreeLabelProvider (List<Locale> locales) {
+ this.locales = locales;
+ }
+
+ //@Override
+ public Image getColumnImage(Object element, int columnIndex) {
+ if (columnIndex == 0) {
+ IKeyTreeNode kti = (IKeyTreeNode) element;
+ IMessage[] be = kti.getMessagesBundleGroup().getMessages(kti.getMessageKey());
+ boolean incomplete = false;
+
+ if (be.length != kti.getMessagesBundleGroup().getMessagesBundleCount())
+ incomplete = true;
+ else {
+ for (IMessage b : be) {
+ if (b.getValue() == null || b.getValue().trim().length() == 0) {
+ incomplete = true;
+ break;
+ }
+ }
+ }
+
+ if (incomplete)
+ return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE);
+ else
+ return ImageUtils.getImage(ImageUtils.ICON_RESOURCE);
+ }
+ return null;
+ }
+
+ //@Override
+ public String getColumnText(Object element, int columnIndex) {
+ if (columnIndex == 0)
+ return super.getText(element);
+
+ if (columnIndex <= locales.size()) {
+ IValuedKeyTreeNode item = (IValuedKeyTreeNode) element;
+ String entry = item.getValue(locales.get(columnIndex-1));
+ if (entry != null) {
+ return entry;
+ }
+ }
+ return "";
+ }
+
+ public void setSearchEnabled (boolean enabled) {
+ this.searchEnabled = enabled;
+ }
+
+ public boolean isSearchEnabled () {
+ return this.searchEnabled;
+ }
+
+ public void setLocales(List<Locale> visibleLocales) {
+ locales = visibleLocales;
+ }
+
+ protected boolean isMatchingToPattern (Object element, int columnIndex) {
+ boolean matching = false;
+
+ if (element instanceof IValuedKeyTreeNode) {
+ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element;
+
+ if (vkti.getInfo() == null)
+ return false;
+
+ FilterInfo filterInfo = (FilterInfo) vkti.getInfo();
+
+ if (columnIndex == 0) {
+ matching = filterInfo.isFoundInKey();
+ } else {
+ matching = filterInfo.hasFoundInLocale(locales.get(columnIndex-1));
+ }
+ }
+
+ return matching;
+ }
+
+ protected boolean isSearchEnabled (Object element) {
+ return (element instanceof IValuedKeyTreeNode && searchEnabled );
+ }
+
+ @Override
+ public void update(ViewerCell cell) {
+ Object element = cell.getElement();
+ int columnIndex = cell.getColumnIndex();
+
+ if (isSearchEnabled(element)) {
+ if (isMatchingToPattern(element, columnIndex) ) {
+ List<StyleRange> styleRanges = new ArrayList<StyleRange>();
+ FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode)element).getInfo();
+
+ if (columnIndex > 0) {
+ for (Region reg : filterInfo.getFoundInLocaleRanges(locales.get(columnIndex-1))) {
+ styleRanges.add(new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD));
+ }
+ } else {
+ // check if the pattern has been found within the key section
+ if (filterInfo.isFoundInKey()) {
+ for (Region reg : filterInfo.getKeyOccurrences()) {
+ StyleRange sr = new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD);
+ styleRanges.add(sr);
+ }
+ }
+ }
+ cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()]));
+ } else {
+ cell.setForeground(gray);
+ }
+ } else if (columnIndex == 0)
+ super.update(cell);
+
+ cell.setImage(this.getColumnImage(element, columnIndex));
+ cell.setText(this.getColumnText(element, columnIndex));
+ }
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
index 540bdc70..c9658063 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
@@ -1,69 +1,76 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
-
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipse.jface.viewers.ITableColorProvider;
-import org.eclipse.jface.viewers.ITableFontProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-
-
-public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements
- ITableColorProvider, ITableFontProvider {
-
- private IMessagesBundle locale;
-
- public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) {
- this.locale = iBundle;
- }
-
- //@Override
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
- //@Override
- public String getColumnText(Object element, int columnIndex) {
- try {
- IKeyTreeNode item = (IKeyTreeNode) element;
- IMessage entry = locale.getMessage(item.getMessageKey());
- if (entry != null) {
- String value = entry.getValue();
- if (value.length() > 40)
- value = value.substring(0, 39) + "...";
- }
- } catch (Exception e) {
- }
- return "";
- }
-
- @Override
- public Color getBackground(Object element, int columnIndex) {
- return null;//return new Color(Display.getDefault(), 255, 0, 0);
- }
-
- @Override
- public Color getForeground(Object element, int columnIndex) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Font getFont(Object element, int columnIndex) {
- return null; //UIUtils.createFont(SWT.BOLD);
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int columnIndex = cell.getColumnIndex();
- cell.setImage(this.getColumnImage(element, columnIndex));
- cell.setText(this.getColumnText(element, columnIndex));
-
- super.update(cell);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.provider;
+
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
+import org.eclipse.jface.viewers.ITableColorProvider;
+import org.eclipse.jface.viewers.ITableFontProvider;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+
+
+public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements
+ ITableColorProvider, ITableFontProvider {
+
+ private IMessagesBundle locale;
+
+ public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) {
+ this.locale = iBundle;
+ }
+
+ //@Override
+ public Image getColumnImage(Object element, int columnIndex) {
+ return null;
+ }
+
+ //@Override
+ public String getColumnText(Object element, int columnIndex) {
+ try {
+ IKeyTreeNode item = (IKeyTreeNode) element;
+ IMessage entry = locale.getMessage(item.getMessageKey());
+ if (entry != null) {
+ String value = entry.getValue();
+ if (value.length() > 40)
+ value = value.substring(0, 39) + "...";
+ }
+ } catch (Exception e) {
+ }
+ return "";
+ }
+
+ @Override
+ public Color getBackground(Object element, int columnIndex) {
+ return null;//return new Color(Display.getDefault(), 255, 0, 0);
+ }
+
+ @Override
+ public Color getForeground(Object element, int columnIndex) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Font getFont(Object element, int columnIndex) {
+ return null; //UIUtils.createFont(SWT.BOLD);
+ }
+
+ @Override
+ public void update(ViewerCell cell) {
+ Object element = cell.getElement();
+ int columnIndex = cell.getColumnIndex();
+ cell.setImage(this.getColumnImage(element, columnIndex));
+ cell.setText(this.getColumnText(element, columnIndex));
+
+ super.update(cell);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
index a9113a2e..9ca3f6fd 100644
--- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
+++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
@@ -1,65 +1,72 @@
-package org.eclipse.babel.tapiji.tools.core.ui.widgets.sorter;
-
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.model.view.SortInfo;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-
-public class ValuedKeyTreeItemSorter extends ViewerSorter {
-
- private StructuredViewer viewer;
- private SortInfo sortInfo;
-
- public ValuedKeyTreeItemSorter (StructuredViewer viewer,
- SortInfo sortInfo) {
- this.viewer = viewer;
- this.sortInfo = sortInfo;
- }
-
- public StructuredViewer getViewer() {
- return viewer;
- }
-
- public void setViewer(StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public SortInfo getSortInfo() {
- return sortInfo;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- this.sortInfo = sortInfo;
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- try {
- if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode))
- return super.compare(viewer, e1, e2);
- IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1;
- IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2;
-
- int result = 0;
-
- if (sortInfo == null)
- return 0;
-
- if (sortInfo.getColIdx() == 0)
- result = comp1.getMessageKey().compareTo(comp2.getMessageKey());
- else {
- Locale loc = sortInfo.getVisibleLocales().get(sortInfo.getColIdx()-1);
- result = (comp1.getValue(loc) == null ? "" : comp1.getValue(loc))
- .compareTo((comp2.getValue(loc) == null ? "" : comp2.getValue(loc)));
- }
-
- return result * (sortInfo.isDESC() ? -1 : 1);
- } catch (Exception e) {
- return 0;
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.ui.widgets.sorter;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.model.view.SortInfo;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerSorter;
+
+public class ValuedKeyTreeItemSorter extends ViewerSorter {
+
+ private StructuredViewer viewer;
+ private SortInfo sortInfo;
+
+ public ValuedKeyTreeItemSorter (StructuredViewer viewer,
+ SortInfo sortInfo) {
+ this.viewer = viewer;
+ this.sortInfo = sortInfo;
+ }
+
+ public StructuredViewer getViewer() {
+ return viewer;
+ }
+
+ public void setViewer(StructuredViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public SortInfo getSortInfo() {
+ return sortInfo;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ this.sortInfo = sortInfo;
+ }
+
+ @Override
+ public int compare(Viewer viewer, Object e1, Object e2) {
+ try {
+ if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode))
+ return super.compare(viewer, e1, e2);
+ IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1;
+ IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2;
+
+ int result = 0;
+
+ if (sortInfo == null)
+ return 0;
+
+ if (sortInfo.getColIdx() == 0)
+ result = comp1.getMessageKey().compareTo(comp2.getMessageKey());
+ else {
+ Locale loc = sortInfo.getVisibleLocales().get(sortInfo.getColIdx()-1);
+ result = (comp1.getValue(loc) == null ? "" : comp1.getValue(loc))
+ .compareTo((comp2.getValue(loc) == null ? "" : comp2.getValue(loc)));
+ }
+
+ return result * (sortInfo.isDESC() ? -1 : 1);
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java
index 09d47373..3f15400d 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java
@@ -1,166 +1,173 @@
-package org.eclipse.babel.tapiji.tools.core;
-
-import java.text.MessageFormat;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class Activator extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.core";
-
- // The builder extension id
- public static final String BUILDER_EXTENSION_ID = "org.eclipse.babel.tapiji.tools.core.builderExtension";
-
- // The shared instance
- private static Activator plugin;
-
- // Resource bundle.
- private ResourceBundle resourceBundle;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- // save state of ResourceBundleManager
- ResourceBundleManager.saveManagerState();
-
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given plug-in
- * relative path
- *
- * @param path
- * the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- if (path.indexOf("icons/") < 0) {
- path = "icons/" + path;
- }
-
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
- /**
- * Returns the string from the plugin's resource bundle, or 'key' if not
- * found.
- *
- * @param key
- * the key for which to fetch a localized text
- * @return localized string corresponding to key
- */
- public static String getString(String key) {
- ResourceBundle bundle = Activator.getDefault().getResourceBundle();
- try {
- return (bundle != null) ? bundle.getString(key) : key;
- } catch (MissingResourceException e) {
- return key;
- }
- }
-
- /**
- * Returns the string from the plugin's resource bundle, or 'key' if not
- * found.
- *
- * @param key
- * the key for which to fetch a localized text
- * @param arg1
- * runtime argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(String key, String arg1) {
- return MessageFormat.format(getString(key), new String[] { arg1 });
- }
-
- /**
- * Returns the string from the plugin's resource bundle, or 'key' if not
- * found.
- *
- * @param key
- * the key for which to fetch a localized text
- * @param arg1
- * runtime first argument to replace in key value
- * @param arg2
- * runtime second argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(String key, String arg1, String arg2) {
- return MessageFormat
- .format(getString(key), new String[] { arg1, arg2 });
- }
-
- /**
- * Returns the string from the plugin's resource bundle, or 'key' if not
- * found.
- *
- * @param key
- * the key for which to fetch a localized text
- * @param arg1
- * runtime argument to replace in key value
- * @param arg2
- * runtime second argument to replace in key value
- * @param arg3
- * runtime third argument to replace in key value
- * @return localized string corresponding to key
- */
- public static String getString(String key, String arg1, String arg2,
- String arg3) {
- return MessageFormat.format(getString(key), new String[] { arg1, arg2,
- arg3 });
- }
-
- /**
- * Returns the plugin's resource bundle.
- *
- * @return resource bundle
- */
- protected ResourceBundle getResourceBundle() {
- return resourceBundle;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.core";
+
+ // The builder extension id
+ public static final String BUILDER_EXTENSION_ID = "org.eclipse.babel.tapiji.tools.core.builderExtension";
+
+ // The shared instance
+ private static Activator plugin;
+
+ // Resource bundle.
+ private ResourceBundle resourceBundle;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
+ * )
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ // save state of ResourceBundleManager
+ ResourceBundleManager.saveManagerState();
+
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given plug-in
+ * relative path
+ *
+ * @param path
+ * the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ if (path.indexOf("icons/") < 0) {
+ path = "icons/" + path;
+ }
+
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key) {
+ ResourceBundle bundle = Activator.getDefault().getResourceBundle();
+ try {
+ return (bundle != null) ? bundle.getString(key) : key;
+ } catch (MissingResourceException e) {
+ return key;
+ }
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime argument to replace in key value
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key, String arg1) {
+ return MessageFormat.format(getString(key), new String[] { arg1 });
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime first argument to replace in key value
+ * @param arg2
+ * runtime second argument to replace in key value
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key, String arg1, String arg2) {
+ return MessageFormat
+ .format(getString(key), new String[] { arg1, arg2 });
+ }
+
+ /**
+ * Returns the string from the plugin's resource bundle, or 'key' if not
+ * found.
+ *
+ * @param key
+ * the key for which to fetch a localized text
+ * @param arg1
+ * runtime argument to replace in key value
+ * @param arg2
+ * runtime second argument to replace in key value
+ * @param arg3
+ * runtime third argument to replace in key value
+ * @return localized string corresponding to key
+ */
+ public static String getString(String key, String arg1, String arg2,
+ String arg3) {
+ return MessageFormat.format(getString(key), new String[] { arg1, arg2,
+ arg3 });
+ }
+
+ /**
+ * Returns the plugin's resource bundle.
+ *
+ * @return resource bundle
+ */
+ protected ResourceBundle getResourceBundle() {
+ return resourceBundle;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
index 3c88a5dd..27c61232 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java
@@ -1,31 +1,38 @@
-package org.eclipse.babel.tapiji.tools.core;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-public class Logger {
-
- public static void logInfo (String message) {
- log(IStatus.INFO, IStatus.OK, message, null);
- }
-
- public static void logError (Throwable exception) {
- logError("Unexpected Exception", exception);
- }
-
- public static void logError(String message, Throwable exception) {
- log(IStatus.ERROR, IStatus.OK, message, exception);
- }
-
- public static void log(int severity, int code, String message, Throwable exception) {
- log(createStatus(severity, code, message, exception));
- }
-
- public static IStatus createStatus(int severity, int code, String message, Throwable exception) {
- return new Status(severity, Activator.PLUGIN_ID, code, message, exception);
- }
-
- public static void log(IStatus status) {
- Activator.getDefault().getLog().log(status);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+
+public class Logger {
+
+ public static void logInfo (String message) {
+ log(IStatus.INFO, IStatus.OK, message, null);
+ }
+
+ public static void logError (Throwable exception) {
+ logError("Unexpected Exception", exception);
+ }
+
+ public static void logError(String message, Throwable exception) {
+ log(IStatus.ERROR, IStatus.OK, message, exception);
+ }
+
+ public static void log(int severity, int code, String message, Throwable exception) {
+ log(createStatus(severity, code, message, exception));
+ }
+
+ public static IStatus createStatus(int severity, int code, String message, Throwable exception) {
+ return new Status(severity, Activator.PLUGIN_ID, code, message, exception);
+ }
+
+ public static void log(IStatus status) {
+ Activator.getDefault().getLog().log(status);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/BuilderPropertyChangeListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/BuilderPropertyChangeListener.java
index 4199631b..224f0585 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/BuilderPropertyChangeListener.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/BuilderPropertyChangeListener.java
@@ -1,124 +1,131 @@
-package org.eclipse.babel.tapiji.tools.core.builder;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.widgets.Display;
-
-public class BuilderPropertyChangeListener implements IPropertyChangeListener {
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getNewValue().equals(true) && isTapiJIPropertyp(event))
- rebuild();
-
- if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN))
- rebuild();
-
- if (event.getNewValue().equals(false)) {
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)) {
- deleteMarkersByCause(EditorUtils.MARKER_ID, -1);
- }
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)) {
- deleteMarkersByCause(EditorUtils.RB_MARKER_ID, -1);
- }
- if (event.getProperty().equals(
- TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)) {
- deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
- IMarkerConstants.CAUSE_UNSPEZIFIED_KEY);
- }
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)) {
- deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
- IMarkerConstants.CAUSE_SAME_VALUE);
- }
- if (event.getProperty().equals(
- TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) {
- deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
- IMarkerConstants.CAUSE_MISSING_LANGUAGE);
- }
- }
-
- }
-
- private boolean isTapiJIPropertyp(PropertyChangeEvent event) {
- if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)
- || event.getProperty().equals(TapiJIPreferences.AUDIT_RB)
- || event.getProperty().equals(
- TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)
- || event.getProperty().equals(
- TapiJIPreferences.AUDIT_SAME_VALUE)
- || event.getProperty().equals(
- TapiJIPreferences.AUDIT_MISSING_LANGUAGE))
- return true;
- else
- return false;
- }
-
- /*
- * cause == -1 ignores the attribute 'case'
- */
- private void deleteMarkersByCause(final String markertype, final int cause) {
- final IWorkspace workspace = ResourcesPlugin.getWorkspace();
- BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
- @Override
- public void run() {
- IMarker[] marker;
- try {
- marker = workspace.getRoot().findMarkers(markertype, true,
- IResource.DEPTH_INFINITE);
-
- for (IMarker m : marker) {
- if (m.exists()) {
- if (m.getAttribute("cause", -1) == cause)
- m.delete();
- if (cause == -1)
- m.getResource().deleteMarkers(markertype, true,
- IResource.DEPTH_INFINITE);
- }
- }
- } catch (CoreException e) {
- }
- }
- });
- }
-
- private void rebuild() {
- final IWorkspace workspace = ResourcesPlugin.getWorkspace();
-
- new Job("Audit source files") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- for (IResource res : workspace.getRoot().members()) {
- final IProject p = (IProject) res;
- try {
- p.build(I18nBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, monitor);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- return Status.OK_STATUS;
- }
-
- }.schedule();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.swt.custom.BusyIndicator;
+import org.eclipse.swt.widgets.Display;
+
+public class BuilderPropertyChangeListener implements IPropertyChangeListener {
+
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if (event.getNewValue().equals(true) && isTapiJIPropertyp(event))
+ rebuild();
+
+ if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN))
+ rebuild();
+
+ if (event.getNewValue().equals(false)) {
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)) {
+ deleteMarkersByCause(EditorUtils.MARKER_ID, -1);
+ }
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID, -1);
+ }
+ if (event.getProperty().equals(
+ TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_UNSPEZIFIED_KEY);
+ }
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_SAME_VALUE);
+ }
+ if (event.getProperty().equals(
+ TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) {
+ deleteMarkersByCause(EditorUtils.RB_MARKER_ID,
+ IMarkerConstants.CAUSE_MISSING_LANGUAGE);
+ }
+ }
+
+ }
+
+ private boolean isTapiJIPropertyp(PropertyChangeEvent event) {
+ if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)
+ || event.getProperty().equals(TapiJIPreferences.AUDIT_RB)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_SAME_VALUE)
+ || event.getProperty().equals(
+ TapiJIPreferences.AUDIT_MISSING_LANGUAGE))
+ return true;
+ else
+ return false;
+ }
+
+ /*
+ * cause == -1 ignores the attribute 'case'
+ */
+ private void deleteMarkersByCause(final String markertype, final int cause) {
+ final IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
+ @Override
+ public void run() {
+ IMarker[] marker;
+ try {
+ marker = workspace.getRoot().findMarkers(markertype, true,
+ IResource.DEPTH_INFINITE);
+
+ for (IMarker m : marker) {
+ if (m.exists()) {
+ if (m.getAttribute("cause", -1) == cause)
+ m.delete();
+ if (cause == -1)
+ m.getResource().deleteMarkers(markertype, true,
+ IResource.DEPTH_INFINITE);
+ }
+ }
+ } catch (CoreException e) {
+ }
+ }
+ });
+ }
+
+ private void rebuild() {
+ final IWorkspace workspace = ResourcesPlugin.getWorkspace();
+
+ new Job("Audit source files") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ for (IResource res : workspace.getRoot().members()) {
+ final IProject p = (IProject) res;
+ try {
+ p.build(I18nBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, monitor);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ return Status.OK_STATUS;
+ }
+
+ }.schedule();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ExtensionManager.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ExtensionManager.java
index 6f767d44..8d7b1c5f 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ExtensionManager.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ExtensionManager.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.builder;
import java.util.ArrayList;
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/I18nBuilder.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/I18nBuilder.java
index 94449c71..bf533ca2 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/I18nBuilder.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/I18nBuilder.java
@@ -1,430 +1,437 @@
-package org.eclipse.babel.tapiji.tools.core.builder;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.babel.core.configuration.ConfigurationManager;
-import org.eclipse.babel.core.configuration.IConfiguration;
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.builder.analyzer.ResourceFinder;
-import org.eclipse.babel.tapiji.tools.core.extensions.I18nAuditor;
-import org.eclipse.babel.tapiji.tools.core.extensions.I18nRBAuditor;
-import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor;
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipse.babel.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.core.resources.ICommand;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-
-public class I18nBuilder extends IncrementalProjectBuilder {
-
- public static final String BUILDER_ID = Activator.PLUGIN_ID
- + ".I18NBuilder";
-
- // private static I18nAuditor[] resourceAuditors;
- // private static Set<String> supportedFileEndings;
-
- public static I18nAuditor getI18nAuditorByContext(String contextId)
- throws NoSuchResourceAuditorException {
- for (I18nAuditor auditor : ExtensionManager.getRegisteredI18nAuditors()) {
- if (auditor.getContextId().equals(contextId)) {
- return auditor;
- }
- }
- throw new NoSuchResourceAuditorException();
- }
-
- public static boolean isResourceAuditable(IResource resource,
- Set<String> supportedExtensions) {
- for (String ext : supportedExtensions) {
- if (resource.getType() == IResource.FILE && !resource.isDerived()
- && resource.getFileExtension() != null
- && (resource.getFileExtension().equalsIgnoreCase(ext))) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- protected IProject[] build(final int kind, Map args,
- IProgressMonitor monitor) throws CoreException {
-
- ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor monitor) throws CoreException {
- if (kind == FULL_BUILD) {
- fullBuild(monitor);
- } else {
- // only perform audit if the resource delta is not empty
- IResourceDelta resDelta = getDelta(getProject());
-
- if (resDelta == null) {
- return;
- }
-
- if (resDelta.getAffectedChildren() == null) {
- return;
- }
-
- incrementalBuild(monitor, resDelta);
- }
- }
- }, monitor);
-
- return null;
- }
-
- private void incrementalBuild(IProgressMonitor monitor,
- IResourceDelta resDelta) throws CoreException {
- try {
- // inspect resource delta
- ResourceFinder csrav = new ResourceFinder(
- ExtensionManager.getSupportedFileEndings());
- resDelta.accept(csrav);
- auditResources(csrav.getResources(), monitor, getProject());
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public void buildResource(IResource resource, IProgressMonitor monitor) {
- if (isResourceAuditable(resource,
- ExtensionManager.getSupportedFileEndings())) {
- List<IResource> resources = new ArrayList<IResource>();
- resources.add(resource);
- // TODO: create instance of progressmonitor and hand it over to
- // auditResources
- try {
- auditResources(resources, monitor, resource.getProject());
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
- }
-
- public void buildProject(IProgressMonitor monitor, IProject proj) {
- try {
- ResourceFinder csrav = new ResourceFinder(
- ExtensionManager.getSupportedFileEndings());
- proj.accept(csrav);
- auditResources(csrav.getResources(), monitor, proj);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- private void fullBuild(IProgressMonitor monitor) {
- buildProject(monitor, getProject());
- }
-
- private void auditResources(List<IResource> resources,
- IProgressMonitor monitor, IProject project) {
- IConfiguration configuration = ConfigurationManager.getInstance()
- .getConfiguration();
-
- int work = resources.size();
- int actWork = 0;
- if (monitor == null) {
- monitor = new NullProgressMonitor();
- }
-
- monitor.beginTask(
- "Audit resource file for Internationalization problems", work);
-
- for (IResource resource : resources) {
- monitor.subTask("'" + resource.getFullPath().toOSString() + "'");
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
-
- if (!EditorUtils.deleteAuditMarkersForResource(resource)) {
- continue;
- }
-
- if (ResourceBundleManager.isResourceExcluded(resource)) {
- continue;
- }
-
- if (!resource.exists()) {
- continue;
- }
-
- for (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) {
- if (ra instanceof I18nResourceAuditor
- && !(configuration.getAuditResource())) {
- continue;
- }
- if (ra instanceof I18nRBAuditor
- && !(configuration.getAuditRb())) {
- continue;
- }
-
- try {
- if (monitor.isCanceled()) {
- monitor.done();
- break;
- }
-
- if (ra.isResourceOfType(resource)) {
- ra.audit(resource);
- }
- } catch (Exception e) {
- Logger.logError(
- "Error during auditing '" + resource.getFullPath()
- + "'", e);
- }
- }
-
- if (monitor != null) {
- monitor.worked(1);
- }
- }
-
- for (I18nAuditor a : ExtensionManager.getRegisteredI18nAuditors()) {
- if (a instanceof I18nResourceAuditor) {
- handleI18NAuditorMarkers((I18nResourceAuditor) a);
- }
- if (a instanceof I18nRBAuditor) {
- handleI18NAuditorMarkers((I18nRBAuditor) a);
- ((I18nRBAuditor) a).resetProblems();
- }
- }
-
- monitor.done();
- }
-
- private void handleI18NAuditorMarkers(I18nResourceAuditor ra) {
- try {
- for (ILocation problem : ra.getConstantStringLiterals()) {
- EditorUtils.reportToMarker(EditorUtils.getFormattedMessage(
- EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
- new String[] { problem.getLiteral() }), problem,
- IMarkerConstants.CAUSE_CONSTANT_LITERAL, "",
- (ILocation) problem.getData(), ra.getContextId());
- }
-
- // Report all broken Resource-Bundle references
- for (ILocation brokenLiteral : ra.getBrokenResourceReferences()) {
- EditorUtils.reportToMarker(EditorUtils.getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
- new String[] {
- brokenLiteral.getLiteral(),
- ((ILocation) brokenLiteral.getData())
- .getLiteral() }), brokenLiteral,
- IMarkerConstants.CAUSE_BROKEN_REFERENCE, brokenLiteral
- .getLiteral(), (ILocation) brokenLiteral
- .getData(), ra.getContextId());
- }
-
- // Report all broken definitions to Resource-Bundle
- // references
- for (ILocation brokenLiteral : ra.getBrokenBundleReferences()) {
- EditorUtils.reportToMarker(EditorUtils.getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
- new String[] { brokenLiteral.getLiteral() }),
- brokenLiteral,
- IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
- brokenLiteral.getLiteral(), (ILocation) brokenLiteral
- .getData(), ra.getContextId());
- }
- } catch (Exception e) {
- Logger.logError(
- "Exception during reporting of Internationalization errors",
- e);
- }
- }
-
- private void handleI18NAuditorMarkers(I18nRBAuditor ra) {
- IConfiguration configuration = ConfigurationManager.getInstance()
- .getConfiguration();
- try {
- // Report all unspecified keys
- if (configuration.getAuditMissingValue()) {
- for (ILocation problem : ra.getUnspecifiedKeyReferences()) {
- EditorUtils.reportToRBMarker(EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_UNSPECIFIED_KEYS,
- new String[] { problem.getLiteral(),
- problem.getFile().getName() }),
- problem, IMarkerConstants.CAUSE_UNSPEZIFIED_KEY,
- problem.getLiteral(), "", (ILocation) problem
- .getData(), ra.getContextId());
- }
- }
-
- // Report all same values
- if (configuration.getAuditSameValue()) {
- Map<ILocation, ILocation> sameValues = ra
- .getSameValuesReferences();
- for (ILocation problem : sameValues.keySet()) {
- EditorUtils.reportToRBMarker(EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_SAME_VALUE,
- new String[] {
- problem.getFile().getName(),
- sameValues.get(problem).getFile()
- .getName(),
- problem.getLiteral() }), problem,
- IMarkerConstants.CAUSE_SAME_VALUE, problem
- .getLiteral(), sameValues.get(problem)
- .getFile().getName(), (ILocation) problem
- .getData(), ra.getContextId());
- }
- }
- // Report all missing languages
- if (configuration.getAuditMissingLanguage()) {
- for (ILocation problem : ra.getMissingLanguageReferences()) {
- EditorUtils
- .reportToRBMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_MISSING_LANGUAGE,
- new String[] {
- RBFileUtils
- .getCorrespondingResourceBundleId(problem
- .getFile()),
- problem.getLiteral() }),
- problem,
- IMarkerConstants.CAUSE_MISSING_LANGUAGE,
- problem.getLiteral(), "",
- (ILocation) problem.getData(), ra
- .getContextId());
- }
- }
- } catch (Exception e) {
- Logger.logError(
- "Exception during reporting of Internationalization errors",
- e);
- }
- }
-
- @SuppressWarnings("unused")
- private void setProgress(IProgressMonitor monitor, int progress)
- throws InterruptedException {
- monitor.worked(progress);
-
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
-
- if (isInterrupted()) {
- throw new InterruptedException();
- }
- }
-
- @Override
- protected void clean(IProgressMonitor monitor) throws CoreException {
- // TODO Auto-generated method stub
- super.clean(monitor);
- }
-
- public static void addBuilderToProject(IProject project) {
- Logger.logInfo("Internationalization-Builder registered for '"
- + project.getName() + "'");
-
- // Only for open projects
- if (!project.isOpen()) {
- return;
- }
-
- IProjectDescription description = null;
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- // Check if the builder is already associated to the specified project
- ICommand[] commands = description.getBuildSpec();
- for (ICommand command : commands) {
- if (command.getBuilderName().equals(BUILDER_ID)) {
- return;
- }
- }
-
- // Associate the builder with the project
- ICommand builderCmd = description.newCommand();
- builderCmd.setBuilderName(BUILDER_ID);
- List<ICommand> newCommands = new ArrayList<ICommand>();
- newCommands.addAll(Arrays.asList(commands));
- newCommands.add(builderCmd);
- description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
- .size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public static void removeBuilderFromProject(IProject project) {
- // Only for open projects
- if (!project.isOpen()) {
- return;
- }
-
- try {
- project.deleteMarkers(EditorUtils.MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- project.deleteMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- } catch (CoreException e1) {
- Logger.logError(e1);
- }
-
- IProjectDescription description = null;
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- // remove builder from project
- int idx = -1;
- ICommand[] commands = description.getBuildSpec();
- for (int i = 0; i < commands.length; i++) {
- if (commands[i].getBuilderName().equals(BUILDER_ID)) {
- idx = i;
- break;
- }
- }
- if (idx == -1) {
- return;
- }
-
- List<ICommand> newCommands = new ArrayList<ICommand>();
- newCommands.addAll(Arrays.asList(commands));
- newCommands.remove(idx);
- description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
- .size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
-
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.babel.core.configuration.ConfigurationManager;
+import org.eclipse.babel.core.configuration.IConfiguration;
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.builder.analyzer.ResourceFinder;
+import org.eclipse.babel.tapiji.tools.core.extensions.I18nAuditor;
+import org.eclipse.babel.tapiji.tools.core.extensions.I18nRBAuditor;
+import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.core.resources.ICommand;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IWorkspaceRunnable;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.OperationCanceledException;
+
+public class I18nBuilder extends IncrementalProjectBuilder {
+
+ public static final String BUILDER_ID = Activator.PLUGIN_ID
+ + ".I18NBuilder";
+
+ // private static I18nAuditor[] resourceAuditors;
+ // private static Set<String> supportedFileEndings;
+
+ public static I18nAuditor getI18nAuditorByContext(String contextId)
+ throws NoSuchResourceAuditorException {
+ for (I18nAuditor auditor : ExtensionManager.getRegisteredI18nAuditors()) {
+ if (auditor.getContextId().equals(contextId)) {
+ return auditor;
+ }
+ }
+ throw new NoSuchResourceAuditorException();
+ }
+
+ public static boolean isResourceAuditable(IResource resource,
+ Set<String> supportedExtensions) {
+ for (String ext : supportedExtensions) {
+ if (resource.getType() == IResource.FILE && !resource.isDerived()
+ && resource.getFileExtension() != null
+ && (resource.getFileExtension().equalsIgnoreCase(ext))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ protected IProject[] build(final int kind, Map args,
+ IProgressMonitor monitor) throws CoreException {
+
+ ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
+ @Override
+ public void run(IProgressMonitor monitor) throws CoreException {
+ if (kind == FULL_BUILD) {
+ fullBuild(monitor);
+ } else {
+ // only perform audit if the resource delta is not empty
+ IResourceDelta resDelta = getDelta(getProject());
+
+ if (resDelta == null) {
+ return;
+ }
+
+ if (resDelta.getAffectedChildren() == null) {
+ return;
+ }
+
+ incrementalBuild(monitor, resDelta);
+ }
+ }
+ }, monitor);
+
+ return null;
+ }
+
+ private void incrementalBuild(IProgressMonitor monitor,
+ IResourceDelta resDelta) throws CoreException {
+ try {
+ // inspect resource delta
+ ResourceFinder csrav = new ResourceFinder(
+ ExtensionManager.getSupportedFileEndings());
+ resDelta.accept(csrav);
+ auditResources(csrav.getResources(), monitor, getProject());
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public void buildResource(IResource resource, IProgressMonitor monitor) {
+ if (isResourceAuditable(resource,
+ ExtensionManager.getSupportedFileEndings())) {
+ List<IResource> resources = new ArrayList<IResource>();
+ resources.add(resource);
+ // TODO: create instance of progressmonitor and hand it over to
+ // auditResources
+ try {
+ auditResources(resources, monitor, resource.getProject());
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
+ }
+
+ public void buildProject(IProgressMonitor monitor, IProject proj) {
+ try {
+ ResourceFinder csrav = new ResourceFinder(
+ ExtensionManager.getSupportedFileEndings());
+ proj.accept(csrav);
+ auditResources(csrav.getResources(), monitor, proj);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ private void fullBuild(IProgressMonitor monitor) {
+ buildProject(monitor, getProject());
+ }
+
+ private void auditResources(List<IResource> resources,
+ IProgressMonitor monitor, IProject project) {
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
+
+ int work = resources.size();
+ int actWork = 0;
+ if (monitor == null) {
+ monitor = new NullProgressMonitor();
+ }
+
+ monitor.beginTask(
+ "Audit resource file for Internationalization problems", work);
+
+ for (IResource resource : resources) {
+ monitor.subTask("'" + resource.getFullPath().toOSString() + "'");
+ if (monitor.isCanceled()) {
+ throw new OperationCanceledException();
+ }
+
+ if (!EditorUtils.deleteAuditMarkersForResource(resource)) {
+ continue;
+ }
+
+ if (ResourceBundleManager.isResourceExcluded(resource)) {
+ continue;
+ }
+
+ if (!resource.exists()) {
+ continue;
+ }
+
+ for (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) {
+ if (ra instanceof I18nResourceAuditor
+ && !(configuration.getAuditResource())) {
+ continue;
+ }
+ if (ra instanceof I18nRBAuditor
+ && !(configuration.getAuditRb())) {
+ continue;
+ }
+
+ try {
+ if (monitor.isCanceled()) {
+ monitor.done();
+ break;
+ }
+
+ if (ra.isResourceOfType(resource)) {
+ ra.audit(resource);
+ }
+ } catch (Exception e) {
+ Logger.logError(
+ "Error during auditing '" + resource.getFullPath()
+ + "'", e);
+ }
+ }
+
+ if (monitor != null) {
+ monitor.worked(1);
+ }
+ }
+
+ for (I18nAuditor a : ExtensionManager.getRegisteredI18nAuditors()) {
+ if (a instanceof I18nResourceAuditor) {
+ handleI18NAuditorMarkers((I18nResourceAuditor) a);
+ }
+ if (a instanceof I18nRBAuditor) {
+ handleI18NAuditorMarkers((I18nRBAuditor) a);
+ ((I18nRBAuditor) a).resetProblems();
+ }
+ }
+
+ monitor.done();
+ }
+
+ private void handleI18NAuditorMarkers(I18nResourceAuditor ra) {
+ try {
+ for (ILocation problem : ra.getConstantStringLiterals()) {
+ EditorUtils.reportToMarker(EditorUtils.getFormattedMessage(
+ EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
+ new String[] { problem.getLiteral() }), problem,
+ IMarkerConstants.CAUSE_CONSTANT_LITERAL, "",
+ (ILocation) problem.getData(), ra.getContextId());
+ }
+
+ // Report all broken Resource-Bundle references
+ for (ILocation brokenLiteral : ra.getBrokenResourceReferences()) {
+ EditorUtils.reportToMarker(EditorUtils.getFormattedMessage(
+ EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
+ new String[] {
+ brokenLiteral.getLiteral(),
+ ((ILocation) brokenLiteral.getData())
+ .getLiteral() }), brokenLiteral,
+ IMarkerConstants.CAUSE_BROKEN_REFERENCE, brokenLiteral
+ .getLiteral(), (ILocation) brokenLiteral
+ .getData(), ra.getContextId());
+ }
+
+ // Report all broken definitions to Resource-Bundle
+ // references
+ for (ILocation brokenLiteral : ra.getBrokenBundleReferences()) {
+ EditorUtils.reportToMarker(EditorUtils.getFormattedMessage(
+ EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
+ new String[] { brokenLiteral.getLiteral() }),
+ brokenLiteral,
+ IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
+ brokenLiteral.getLiteral(), (ILocation) brokenLiteral
+ .getData(), ra.getContextId());
+ }
+ } catch (Exception e) {
+ Logger.logError(
+ "Exception during reporting of Internationalization errors",
+ e);
+ }
+ }
+
+ private void handleI18NAuditorMarkers(I18nRBAuditor ra) {
+ IConfiguration configuration = ConfigurationManager.getInstance()
+ .getConfiguration();
+ try {
+ // Report all unspecified keys
+ if (configuration.getAuditMissingValue()) {
+ for (ILocation problem : ra.getUnspecifiedKeyReferences()) {
+ EditorUtils.reportToRBMarker(EditorUtils
+ .getFormattedMessage(
+ EditorUtils.MESSAGE_UNSPECIFIED_KEYS,
+ new String[] { problem.getLiteral(),
+ problem.getFile().getName() }),
+ problem, IMarkerConstants.CAUSE_UNSPEZIFIED_KEY,
+ problem.getLiteral(), "", (ILocation) problem
+ .getData(), ra.getContextId());
+ }
+ }
+
+ // Report all same values
+ if (configuration.getAuditSameValue()) {
+ Map<ILocation, ILocation> sameValues = ra
+ .getSameValuesReferences();
+ for (ILocation problem : sameValues.keySet()) {
+ EditorUtils.reportToRBMarker(EditorUtils
+ .getFormattedMessage(
+ EditorUtils.MESSAGE_SAME_VALUE,
+ new String[] {
+ problem.getFile().getName(),
+ sameValues.get(problem).getFile()
+ .getName(),
+ problem.getLiteral() }), problem,
+ IMarkerConstants.CAUSE_SAME_VALUE, problem
+ .getLiteral(), sameValues.get(problem)
+ .getFile().getName(), (ILocation) problem
+ .getData(), ra.getContextId());
+ }
+ }
+ // Report all missing languages
+ if (configuration.getAuditMissingLanguage()) {
+ for (ILocation problem : ra.getMissingLanguageReferences()) {
+ EditorUtils
+ .reportToRBMarker(
+ EditorUtils
+ .getFormattedMessage(
+ EditorUtils.MESSAGE_MISSING_LANGUAGE,
+ new String[] {
+ RBFileUtils
+ .getCorrespondingResourceBundleId(problem
+ .getFile()),
+ problem.getLiteral() }),
+ problem,
+ IMarkerConstants.CAUSE_MISSING_LANGUAGE,
+ problem.getLiteral(), "",
+ (ILocation) problem.getData(), ra
+ .getContextId());
+ }
+ }
+ } catch (Exception e) {
+ Logger.logError(
+ "Exception during reporting of Internationalization errors",
+ e);
+ }
+ }
+
+ @SuppressWarnings("unused")
+ private void setProgress(IProgressMonitor monitor, int progress)
+ throws InterruptedException {
+ monitor.worked(progress);
+
+ if (monitor.isCanceled()) {
+ throw new OperationCanceledException();
+ }
+
+ if (isInterrupted()) {
+ throw new InterruptedException();
+ }
+ }
+
+ @Override
+ protected void clean(IProgressMonitor monitor) throws CoreException {
+ // TODO Auto-generated method stub
+ super.clean(monitor);
+ }
+
+ public static void addBuilderToProject(IProject project) {
+ Logger.logInfo("Internationalization-Builder registered for '"
+ + project.getName() + "'");
+
+ // Only for open projects
+ if (!project.isOpen()) {
+ return;
+ }
+
+ IProjectDescription description = null;
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ // Check if the builder is already associated to the specified project
+ ICommand[] commands = description.getBuildSpec();
+ for (ICommand command : commands) {
+ if (command.getBuilderName().equals(BUILDER_ID)) {
+ return;
+ }
+ }
+
+ // Associate the builder with the project
+ ICommand builderCmd = description.newCommand();
+ builderCmd.setBuilderName(BUILDER_ID);
+ List<ICommand> newCommands = new ArrayList<ICommand>();
+ newCommands.addAll(Arrays.asList(commands));
+ newCommands.add(builderCmd);
+ description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
+ .size()]));
+
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public static void removeBuilderFromProject(IProject project) {
+ // Only for open projects
+ if (!project.isOpen()) {
+ return;
+ }
+
+ try {
+ project.deleteMarkers(EditorUtils.MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ project.deleteMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ } catch (CoreException e1) {
+ Logger.logError(e1);
+ }
+
+ IProjectDescription description = null;
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ // remove builder from project
+ int idx = -1;
+ ICommand[] commands = description.getBuildSpec();
+ for (int i = 0; i < commands.length; i++) {
+ if (commands[i].getBuilderName().equals(BUILDER_ID)) {
+ idx = i;
+ break;
+ }
+ }
+ if (idx == -1) {
+ return;
+ }
+
+ List<ICommand> newCommands = new ArrayList<ICommand>();
+ newCommands.addAll(Arrays.asList(commands));
+ newCommands.remove(idx);
+ description.setBuildSpec(newCommands.toArray(new ICommand[newCommands
+ .size()]));
+
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/InternationalizationNature.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/InternationalizationNature.java
index 6aaf12b0..f583b7b1 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/InternationalizationNature.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/InternationalizationNature.java
@@ -1,131 +1,138 @@
-package org.eclipse.babel.tapiji.tools.core.builder;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IProjectNature;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-
-public class InternationalizationNature implements IProjectNature {
-
- private static final String NATURE_ID = Activator.PLUGIN_ID + ".nature";
- private IProject project;
-
- @Override
- public void configure() throws CoreException {
- I18nBuilder.addBuilderToProject(project);
- new Job("Audit source files") {
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- project.build(I18nBuilder.FULL_BUILD,
- I18nBuilder.BUILDER_ID, null, monitor);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- return Status.OK_STATUS;
- }
-
- }.schedule();
- }
-
- @Override
- public void deconfigure() throws CoreException {
- I18nBuilder.removeBuilderFromProject(project);
- }
-
- @Override
- public IProject getProject() {
- return project;
- }
-
- @Override
- public void setProject(IProject project) {
- this.project = project;
- }
-
- public static void addNature(IProject project) {
- if (!project.isOpen())
- return;
-
- IProjectDescription description = null;
-
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- // Check if the project has already this nature
- List<String> newIds = new ArrayList<String>();
- newIds.addAll(Arrays.asList(description.getNatureIds()));
- int index = newIds.indexOf(NATURE_ID);
- if (index != -1)
- return;
-
- // Add the nature
- newIds.add(NATURE_ID);
- description.setNatureIds(newIds.toArray(new String[newIds.size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public static boolean supportsNature(IProject project) {
- return project.isOpen();
- }
-
- public static boolean hasNature(IProject project) {
- try {
- return project.isOpen() && project.hasNature(NATURE_ID);
- } catch (CoreException e) {
- Logger.logError(e);
- return false;
- }
- }
-
- public static void removeNature(IProject project) {
- if (!project.isOpen())
- return;
-
- IProjectDescription description = null;
-
- try {
- description = project.getDescription();
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- // Check if the project has already this nature
- List<String> newIds = new ArrayList<String>();
- newIds.addAll(Arrays.asList(description.getNatureIds()));
- int index = newIds.indexOf(NATURE_ID);
- if (index == -1)
- return;
-
- // remove the nature
- newIds.remove(NATURE_ID);
- description.setNatureIds(newIds.toArray(new String[newIds.size()]));
-
- try {
- project.setDescription(description, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.resources.IProjectNature;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+
+public class InternationalizationNature implements IProjectNature {
+
+ private static final String NATURE_ID = Activator.PLUGIN_ID + ".nature";
+ private IProject project;
+
+ @Override
+ public void configure() throws CoreException {
+ I18nBuilder.addBuilderToProject(project);
+ new Job("Audit source files") {
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ project.build(I18nBuilder.FULL_BUILD,
+ I18nBuilder.BUILDER_ID, null, monitor);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ return Status.OK_STATUS;
+ }
+
+ }.schedule();
+ }
+
+ @Override
+ public void deconfigure() throws CoreException {
+ I18nBuilder.removeBuilderFromProject(project);
+ }
+
+ @Override
+ public IProject getProject() {
+ return project;
+ }
+
+ @Override
+ public void setProject(IProject project) {
+ this.project = project;
+ }
+
+ public static void addNature(IProject project) {
+ if (!project.isOpen())
+ return;
+
+ IProjectDescription description = null;
+
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ // Check if the project has already this nature
+ List<String> newIds = new ArrayList<String>();
+ newIds.addAll(Arrays.asList(description.getNatureIds()));
+ int index = newIds.indexOf(NATURE_ID);
+ if (index != -1)
+ return;
+
+ // Add the nature
+ newIds.add(NATURE_ID);
+ description.setNatureIds(newIds.toArray(new String[newIds.size()]));
+
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public static boolean supportsNature(IProject project) {
+ return project.isOpen();
+ }
+
+ public static boolean hasNature(IProject project) {
+ try {
+ return project.isOpen() && project.hasNature(NATURE_ID);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return false;
+ }
+ }
+
+ public static void removeNature(IProject project) {
+ if (!project.isOpen())
+ return;
+
+ IProjectDescription description = null;
+
+ try {
+ description = project.getDescription();
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ // Check if the project has already this nature
+ List<String> newIds = new ArrayList<String>();
+ newIds.addAll(Arrays.asList(description.getNatureIds()));
+ int index = newIds.indexOf(NATURE_ID);
+ if (index == -1)
+ return;
+
+ // remove the nature
+ newIds.remove(NATURE_ID);
+ description.setNatureIds(newIds.toArray(new String[newIds.size()]));
+
+ try {
+ project.setDescription(description, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ViolationResolutionGenerator.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ViolationResolutionGenerator.java
index f4437bad..413fdf68 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ViolationResolutionGenerator.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/ViolationResolutionGenerator.java
@@ -1,41 +1,48 @@
-package org.eclipse.babel.tapiji.tools.core.builder;
-
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.extensions.I18nAuditor;
-import org.eclipse.babel.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolutionGenerator2;
-
-public class ViolationResolutionGenerator implements
- IMarkerResolutionGenerator2 {
-
- @Override
- public boolean hasResolutions(IMarker marker) {
- return true;
- }
-
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
-
- EditorUtils.updateMarker(marker);
-
- String contextId = marker.getAttribute("context", "");
-
- // find resolution generator for the given context
- try {
- I18nAuditor auditor = I18nBuilder
- .getI18nAuditorByContext(contextId);
- List<IMarkerResolution> resolutions = auditor
- .getMarkerResolutions(marker);
- return resolutions
- .toArray(new IMarkerResolution[resolutions.size()]);
- } catch (NoSuchResourceAuditorException e) {
- }
-
- return new IMarkerResolution[0];
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder;
+
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.I18nAuditor;
+import org.eclipse.babel.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.ui.IMarkerResolution;
+import org.eclipse.ui.IMarkerResolutionGenerator2;
+
+public class ViolationResolutionGenerator implements
+ IMarkerResolutionGenerator2 {
+
+ @Override
+ public boolean hasResolutions(IMarker marker) {
+ return true;
+ }
+
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
+
+ EditorUtils.updateMarker(marker);
+
+ String contextId = marker.getAttribute("context", "");
+
+ // find resolution generator for the given context
+ try {
+ I18nAuditor auditor = I18nBuilder
+ .getI18nAuditorByContext(contextId);
+ List<IMarkerResolution> resolutions = auditor
+ .getMarkerResolutions(marker);
+ return resolutions
+ .toArray(new IMarkerResolution[resolutions.size()]);
+ } catch (NoSuchResourceAuditorException e) {
+ }
+
+ return new IMarkerResolution[0];
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/RBAuditor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/RBAuditor.java
index b0e6459c..3cb2d9e6 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/RBAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/RBAuditor.java
@@ -1,54 +1,61 @@
-package org.eclipse.babel.tapiji.tools.core.builder.analyzer;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor;
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-
-
-public class RBAuditor extends I18nResourceAuditor {
-
- @Override
- public void audit(IResource resource) {
- if (RBFileUtils.isResourceBundleFile(resource)) {
- ResourceBundleManager.getManager(resource.getProject()).addBundleResource (resource);
- }
- }
-
- @Override
- public String[] getFileEndings() {
- return new String [] { "properties" };
- }
-
- @Override
- public List<ILocation> getConstantStringLiterals() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public List<ILocation> getBrokenResourceReferences() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public List<ILocation> getBrokenBundleReferences() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public String getContextId() {
- return "resource_bundle";
- }
-
- @Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder.analyzer;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+
+public class RBAuditor extends I18nResourceAuditor {
+
+ @Override
+ public void audit(IResource resource) {
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ ResourceBundleManager.getManager(resource.getProject()).addBundleResource (resource);
+ }
+ }
+
+ @Override
+ public String[] getFileEndings() {
+ return new String [] { "properties" };
+ }
+
+ @Override
+ public List<ILocation> getConstantStringLiterals() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public List<ILocation> getBrokenResourceReferences() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public List<ILocation> getBrokenBundleReferences() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public String getContextId() {
+ return "resource_bundle";
+ }
+
+ @Override
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
index c4906e48..e8855981 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
@@ -1,52 +1,59 @@
-package org.eclipse.babel.tapiji.tools.core.builder.analyzer;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-
-
-public class ResourceBundleDetectionVisitor implements IResourceVisitor,
- IResourceDeltaVisitor {
-
- private IProject project = null;
-
- public ResourceBundleDetectionVisitor(IProject project) {
- this.project = project;
- }
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- try {
- if (RBFileUtils.isResourceBundleFile(resource)) {
- Logger.logInfo("Loading Resource-Bundle file '" + resource.getName() + "'");
- if (!ResourceBundleManager.isResourceExcluded(resource)) {
- ResourceBundleManager.getManager(project).addBundleResource(resource);
- }
- return false;
- } else {
- return true;
- }
- } catch (Exception e) {
- return false;
- }
- }
-
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
-
- if (RBFileUtils.isResourceBundleFile(resource)) {
-// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
- return false;
- }
-
- return true;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder.analyzer;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.runtime.CoreException;
+
+
+public class ResourceBundleDetectionVisitor implements IResourceVisitor,
+ IResourceDeltaVisitor {
+
+ private IProject project = null;
+
+ public ResourceBundleDetectionVisitor(IProject project) {
+ this.project = project;
+ }
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ try {
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ Logger.logInfo("Loading Resource-Bundle file '" + resource.getName() + "'");
+ if (!ResourceBundleManager.isResourceExcluded(resource)) {
+ ResourceBundleManager.getManager(project).addBundleResource(resource);
+ }
+ return false;
+ } else {
+ return true;
+ }
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ @Override
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ IResource resource = delta.getResource();
+
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
+ return false;
+ }
+
+ return true;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceFinder.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceFinder.java
index 903b932a..43fea867 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceFinder.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/analyzer/ResourceFinder.java
@@ -1,46 +1,53 @@
-package org.eclipse.babel.tapiji.tools.core.builder.analyzer;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-
-public class ResourceFinder implements IResourceVisitor, IResourceDeltaVisitor {
-
- List<IResource> javaResources = null;
- Set<String> supportedExtensions = null;
-
- public ResourceFinder(Set<String> ext) {
- javaResources = new ArrayList<IResource>();
- supportedExtensions = ext;
- }
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- if (I18nBuilder.isResourceAuditable(resource, supportedExtensions)) {
- Logger.logInfo("Audit necessary for resource '"
- + resource.getFullPath().toOSString() + "'");
- javaResources.add(resource);
- return false;
- } else
- return true;
- }
-
- public List<IResource> getResources() {
- return javaResources;
- }
-
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- visit(delta.getResource());
- return true;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder.analyzer;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.runtime.CoreException;
+
+public class ResourceFinder implements IResourceVisitor, IResourceDeltaVisitor {
+
+ List<IResource> javaResources = null;
+ Set<String> supportedExtensions = null;
+
+ public ResourceFinder(Set<String> ext) {
+ javaResources = new ArrayList<IResource>();
+ supportedExtensions = ext;
+ }
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ if (I18nBuilder.isResourceAuditable(resource, supportedExtensions)) {
+ Logger.logInfo("Audit necessary for resource '"
+ + resource.getFullPath().toOSString() + "'");
+ javaResources.add(resource);
+ return false;
+ } else
+ return true;
+ }
+
+ public List<IResource> getResources() {
+ return javaResources;
+ }
+
+ @Override
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ visit(delta.getResource());
+ return true;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
index 5f9d027e..26e15eed 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
@@ -1,184 +1,191 @@
-package org.eclipse.babel.tapiji.tools.core.builder.quickfix;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
-import org.eclipse.babel.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.wizard.IWizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.wizards.IWizardDescriptor;
-
-public class CreateResourceBundle implements IMarkerResolution2 {
-
- private IResource resource;
- private int start;
- private int end;
- private String key;
- private boolean jsfContext;
- private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
-
- public CreateResourceBundle(String key, IResource resource, int start,
- int end) {
- this.key = ResourceUtils.deriveNonExistingRBName(key,
- ResourceBundleManager.getManager(resource.getProject()));
- this.resource = resource;
- this.start = start;
- this.end = end;
- this.jsfContext = jsfContext;
- }
-
- @Override
- public String getDescription() {
- return "Creates a new Resource-Bundle with the id '" + key + "'";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Create Resource-Bundle '" + key + "'";
- }
-
- @Override
- public void run(IMarker marker) {
- runAction();
- }
-
- protected void runAction() {
- // First see if this is a "new wizard".
- IWizardDescriptor descriptor = PlatformUI.getWorkbench()
- .getNewWizardRegistry().findWizard(newBunldeWizard);
- // If not check if it is an "import wizard".
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- // Or maybe an export wizard
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- try {
- // Then if we have a wizard, open it.
- if (descriptor != null) {
- IWizard wizard = descriptor.createWizard();
- if (!(wizard instanceof IResourceBundleWizard))
- return;
-
- IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
- String[] keySilbings = key.split("\\.");
- String rbName = keySilbings[keySilbings.length - 1];
- String packageName = "";
-
- rbw.setBundleId(rbName);
-
- // Set the default path according to the specified package name
- String pathName = "";
- if (keySilbings.length > 1) {
- try {
- IJavaProject jp = JavaCore
- .create(resource.getProject());
- packageName = key.substring(0, key.lastIndexOf("."));
-
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- IPackageFragment pf = fr
- .getPackageFragment(packageName);
- if (pf.exists()) {
- pathName = pf.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
- }
-
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- if (pathName.trim().equals("")) {
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- if (!fr.isReadOnly()) {
- pathName = fr.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
-
- rbw.setDefaultPath(pathName);
-
- WizardDialog wd = new WizardDialog(Display.getDefault()
- .getActiveShell(), wizard);
- wd.setTitle(wizard.getWindowTitle());
- if (wd.open() == WizardDialog.OK) {
- (new I18nBuilder()).buildProject(null,
- resource.getProject());
- (new I18nBuilder()).buildResource(resource, null);
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- if (document.get().charAt(start - 1) == '"'
- && document.get().charAt(start) != '"') {
- start--;
- end++;
- }
- if (document.get().charAt(end + 1) == '"'
- && document.get().charAt(end) != '"')
- end++;
-
- document.replace(start, end - start, "\""
- + (packageName.equals("") ? "" : packageName
- + ".") + rbName + "\"");
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
- }
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
+import org.eclipse.babel.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jdt.core.IJavaProject;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jdt.core.IPackageFragmentRoot;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.wizards.IWizardDescriptor;
+
+public class CreateResourceBundle implements IMarkerResolution2 {
+
+ private IResource resource;
+ private int start;
+ private int end;
+ private String key;
+ private boolean jsfContext;
+ private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
+
+ public CreateResourceBundle(String key, IResource resource, int start,
+ int end) {
+ this.key = ResourceUtils.deriveNonExistingRBName(key,
+ ResourceBundleManager.getManager(resource.getProject()));
+ this.resource = resource;
+ this.start = start;
+ this.end = end;
+ this.jsfContext = jsfContext;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Creates a new Resource-Bundle with the id '" + key + "'";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Create Resource-Bundle '" + key + "'";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ runAction();
+ }
+
+ protected void runAction() {
+ // First see if this is a "new wizard".
+ IWizardDescriptor descriptor = PlatformUI.getWorkbench()
+ .getNewWizardRegistry().findWizard(newBunldeWizard);
+ // If not check if it is an "import wizard".
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ // Or maybe an export wizard
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ try {
+ // Then if we have a wizard, open it.
+ if (descriptor != null) {
+ IWizard wizard = descriptor.createWizard();
+ if (!(wizard instanceof IResourceBundleWizard))
+ return;
+
+ IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
+ String[] keySilbings = key.split("\\.");
+ String rbName = keySilbings[keySilbings.length - 1];
+ String packageName = "";
+
+ rbw.setBundleId(rbName);
+
+ // Set the default path according to the specified package name
+ String pathName = "";
+ if (keySilbings.length > 1) {
+ try {
+ IJavaProject jp = JavaCore
+ .create(resource.getProject());
+ packageName = key.substring(0, key.lastIndexOf("."));
+
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ IPackageFragment pf = fr
+ .getPackageFragment(packageName);
+ if (pf.exists()) {
+ pathName = pf.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+ }
+
+ try {
+ IJavaProject jp = JavaCore.create(resource.getProject());
+ if (pathName.trim().equals("")) {
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ if (!fr.isReadOnly()) {
+ pathName = fr.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+
+ rbw.setDefaultPath(pathName);
+
+ WizardDialog wd = new WizardDialog(Display.getDefault()
+ .getActiveShell(), wizard);
+ wd.setTitle(wizard.getWindowTitle());
+ if (wd.open() == WizardDialog.OK) {
+ (new I18nBuilder()).buildProject(null,
+ resource.getProject());
+ (new I18nBuilder()).buildResource(resource, null);
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ if (document.get().charAt(start - 1) == '"'
+ && document.get().charAt(start) != '"') {
+ start--;
+ end++;
+ }
+ if (document.get().charAt(end + 1) == '"'
+ && document.get().charAt(end) != '"')
+ end++;
+
+ document.replace(start, end - start, "\""
+ + (packageName.equals("") ? "" : packageName
+ + ".") + rbName + "\"");
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+ }
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/IncludeResource.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/IncludeResource.java
index c9fa093a..ec5bf19f 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/IncludeResource.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/builder/quickfix/IncludeResource.java
@@ -1,65 +1,72 @@
-package org.eclipse.babel.tapiji.tools.core.builder.quickfix;
-
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.IProgressService;
-
-
-public class IncludeResource implements IMarkerResolution2 {
-
- private String bundleName;
- private Set<IResource> bundleResources;
-
- public IncludeResource (String bundleName, Set<IResource> bundleResources) {
- this.bundleResources = bundleResources;
- this.bundleName = bundleName;
- }
-
- @Override
- public String getDescription() {
- return "The Resource-Bundle with id '" + bundleName + "' has been " +
- "excluded from Internationalization. Based on this fact, no internationalization " +
- "supoort is provided for this Resource-Bundle. Performing this action, internationalization " +
- "support for '" + bundleName + "' will be enabled";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Include excluded Resource-Bundle '" + bundleName + "'";
- }
-
- @Override
- public void run(final IMarker marker) {
- IWorkbench wb = PlatformUI.getWorkbench();
- IProgressService ps = wb.getProgressService();
- try {
- ps.busyCursorWhile(new IRunnableWithProgress() {
- public void run(IProgressMonitor pm) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(marker.getResource().getProject());
- pm.beginTask("Including resources to Internationalization", bundleResources.size());
- for (IResource resource : bundleResources) {
- manager.includeResource(resource, pm);
- pm.worked(1);
- }
- pm.done();
- }
- });
- } catch (Exception e) {}
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.builder.quickfix;
+
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.IMarkerResolution2;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.progress.IProgressService;
+
+
+public class IncludeResource implements IMarkerResolution2 {
+
+ private String bundleName;
+ private Set<IResource> bundleResources;
+
+ public IncludeResource (String bundleName, Set<IResource> bundleResources) {
+ this.bundleResources = bundleResources;
+ this.bundleName = bundleName;
+ }
+
+ @Override
+ public String getDescription() {
+ return "The Resource-Bundle with id '" + bundleName + "' has been " +
+ "excluded from Internationalization. Based on this fact, no internationalization " +
+ "supoort is provided for this Resource-Bundle. Performing this action, internationalization " +
+ "support for '" + bundleName + "' will be enabled";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Include excluded Resource-Bundle '" + bundleName + "'";
+ }
+
+ @Override
+ public void run(final IMarker marker) {
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ public void run(IProgressMonitor pm) {
+ ResourceBundleManager manager = ResourceBundleManager.getManager(marker.getResource().getProject());
+ pm.beginTask("Including resources to Internationalization", bundleResources.size());
+ for (IResource resource : bundleResources) {
+ manager.includeResource(resource, pm);
+ pm.worked(1);
+ }
+ pm.done();
+ }
+ });
+ } catch (Exception e) {}
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nAuditor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nAuditor.java
index d614f67c..26081318 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nAuditor.java
@@ -1,65 +1,72 @@
-package org.eclipse.babel.tapiji.tools.core.extensions;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-
-public abstract class I18nAuditor {
-
- /**
- * Audits a project resource for I18N problems. This method is triggered
- * during the project's build process.
- *
- * @param resource
- * The project resource
- */
- public abstract void audit(IResource resource);
-
- /**
- * Returns a characterizing identifier of the implemented auditing
- * functionality. The specified identifier is used for discriminating
- * registered builder extensions.
- *
- * @return The String id of the implemented auditing functionality
- */
- public abstract String getContextId();
-
- /**
- * Returns a list of supported file endings.
- *
- * @return The supported file endings
- */
- public abstract String[] getFileEndings();
-
-
- /**
- * Returns a list of quick fixes of a reported Internationalization problem.
- *
- * @param marker
- * The warning marker of the Internationalization problem
- * @param cause
- * The problem type
- * @return The list of marker resolution proposals
- */
- public abstract List<IMarkerResolution> getMarkerResolutions(
- IMarker marker);
-
- /**
- * Checks if the provided resource auditor is responsible for a particular
- * resource.
- *
- * @param resource
- * The resource reference
- * @return True if the resource auditor is responsible for the referenced
- * resource
- */
- public boolean isResourceOfType(IResource resource) {
- for (String ending : getFileEndings()) {
- if (resource.getFileExtension().equalsIgnoreCase(ending))
- return true;
- }
- return false;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.extensions;
+
+import java.util.List;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+public abstract class I18nAuditor {
+
+ /**
+ * Audits a project resource for I18N problems. This method is triggered
+ * during the project's build process.
+ *
+ * @param resource
+ * The project resource
+ */
+ public abstract void audit(IResource resource);
+
+ /**
+ * Returns a characterizing identifier of the implemented auditing
+ * functionality. The specified identifier is used for discriminating
+ * registered builder extensions.
+ *
+ * @return The String id of the implemented auditing functionality
+ */
+ public abstract String getContextId();
+
+ /**
+ * Returns a list of supported file endings.
+ *
+ * @return The supported file endings
+ */
+ public abstract String[] getFileEndings();
+
+
+ /**
+ * Returns a list of quick fixes of a reported Internationalization problem.
+ *
+ * @param marker
+ * The warning marker of the Internationalization problem
+ * @param cause
+ * The problem type
+ * @return The list of marker resolution proposals
+ */
+ public abstract List<IMarkerResolution> getMarkerResolutions(
+ IMarker marker);
+
+ /**
+ * Checks if the provided resource auditor is responsible for a particular
+ * resource.
+ *
+ * @param resource
+ * The resource reference
+ * @return True if the resource auditor is responsible for the referenced
+ * resource
+ */
+ public boolean isResourceOfType(IResource resource) {
+ for (String ending : getFileEndings()) {
+ if (resource.getFileExtension().equalsIgnoreCase(ending))
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nRBAuditor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nRBAuditor.java
index 70259b9d..a42841ac 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nRBAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nRBAuditor.java
@@ -1,43 +1,50 @@
-package org.eclipse.babel.tapiji.tools.core.extensions;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- *
- *
- */
-public abstract class I18nRBAuditor extends I18nAuditor{
-
- /**
- * Mark the end of a audit and reset all problemlists
- */
- public abstract void resetProblems();
-
- /**
- * Returns the list of missing keys or no specified Resource-Bundle-key
- * refernces. Each list entry describes the textual position on which this
- * type of error has been detected.
- * @return The list of positions of no specified RB-key refernces
- */
- public abstract List<ILocation> getUnspecifiedKeyReferences();
-
- /**
- * Returns the list of same Resource-Bundle-value refernces. Each list entry
- * describes the textual position on which this type of error has been
- * detected.
- * @return The list of positions of same RB-value refernces
- */
- public abstract Map<ILocation, ILocation> getSameValuesReferences();
-
- /**
- * Returns the list of missing Resource-Bundle-languages compared with the
- * Resource-Bundles of the hole project. Each list entry describes the
- * textual position on which this type of error has been detected.
- * @return
- */
- public abstract List<ILocation> getMissingLanguageReferences();
-
-
- //public abstract List<ILocation> getUnusedKeyReferences();
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.extensions;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ *
+ */
+public abstract class I18nRBAuditor extends I18nAuditor{
+
+ /**
+ * Mark the end of a audit and reset all problemlists
+ */
+ public abstract void resetProblems();
+
+ /**
+ * Returns the list of missing keys or no specified Resource-Bundle-key
+ * refernces. Each list entry describes the textual position on which this
+ * type of error has been detected.
+ * @return The list of positions of no specified RB-key refernces
+ */
+ public abstract List<ILocation> getUnspecifiedKeyReferences();
+
+ /**
+ * Returns the list of same Resource-Bundle-value refernces. Each list entry
+ * describes the textual position on which this type of error has been
+ * detected.
+ * @return The list of positions of same RB-value refernces
+ */
+ public abstract Map<ILocation, ILocation> getSameValuesReferences();
+
+ /**
+ * Returns the list of missing Resource-Bundle-languages compared with the
+ * Resource-Bundles of the hole project. Each list entry describes the
+ * textual position on which this type of error has been detected.
+ * @return
+ */
+ public abstract List<ILocation> getMissingLanguageReferences();
+
+
+ //public abstract List<ILocation> getUnusedKeyReferences();
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nResourceAuditor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nResourceAuditor.java
index 7000364a..7de52811 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nResourceAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/I18nResourceAuditor.java
@@ -1,97 +1,104 @@
-package org.eclipse.babel.tapiji.tools.core.extensions;
-
-import java.util.List;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-
-/**
- * Auditor class for finding I18N problems within source code resources. The
- * objects audit method is called for a particular resource. Found errors are
- * stored within the object's internal data structure and can be queried with
- * the help of problem categorized getter methods.
- */
-public abstract class I18nResourceAuditor extends I18nAuditor{
- /**
- * Audits a project resource for I18N problems. This method is triggered
- * during the project's build process.
- *
- * @param resource
- * The project resource
- */
- public abstract void audit(IResource resource);
-
- /**
- * Returns a list of supported file endings.
- *
- * @return The supported file endings
- */
- public abstract String[] getFileEndings();
-
- /**
- * Returns the list of found need-to-translate string literals. Each list
- * entry describes the textual position on which this type of error has been
- * detected.
- *
- * @return The list of need-to-translate string literal positions
- */
- public abstract List<ILocation> getConstantStringLiterals();
-
- /**
- * Returns the list of broken Resource-Bundle references. Each list entry
- * describes the textual position on which this type of error has been
- * detected.
- *
- * @return The list of positions of broken Resource-Bundle references
- */
- public abstract List<ILocation> getBrokenResourceReferences();
-
- /**
- * Returns the list of broken references to Resource-Bundle entries. Each
- * list entry describes the textual position on which this type of error has
- * been detected
- *
- * @return The list of positions of broken references to locale-sensitive
- * resources
- */
- public abstract List<ILocation> getBrokenBundleReferences();
-
- /**
- * Returns a characterizing identifier of the implemented auditing
- * functionality. The specified identifier is used for discriminating
- * registered builder extensions.
- *
- * @return The String id of the implemented auditing functionality
- */
- public abstract String getContextId();
-
- /**
- * Returns a list of quick fixes of a reported Internationalization problem.
- *
- * @param marker
- * The warning marker of the Internationalization problem
- * @param cause
- * The problem type
- * @return The list of marker resolution proposals
- */
- public abstract List<IMarkerResolution> getMarkerResolutions(
- IMarker marker);
-
- /**
- * Checks if the provided resource auditor is responsible for a particular
- * resource.
- *
- * @param resource
- * The resource reference
- * @return True if the resource auditor is responsible for the referenced
- * resource
- */
- public boolean isResourceOfType(IResource resource) {
- for (String ending : getFileEndings()) {
- if (resource.getFileExtension().equalsIgnoreCase(ending))
- return true;
- }
- return false;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.extensions;
+
+import java.util.List;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+/**
+ * Auditor class for finding I18N problems within source code resources. The
+ * objects audit method is called for a particular resource. Found errors are
+ * stored within the object's internal data structure and can be queried with
+ * the help of problem categorized getter methods.
+ */
+public abstract class I18nResourceAuditor extends I18nAuditor{
+ /**
+ * Audits a project resource for I18N problems. This method is triggered
+ * during the project's build process.
+ *
+ * @param resource
+ * The project resource
+ */
+ public abstract void audit(IResource resource);
+
+ /**
+ * Returns a list of supported file endings.
+ *
+ * @return The supported file endings
+ */
+ public abstract String[] getFileEndings();
+
+ /**
+ * Returns the list of found need-to-translate string literals. Each list
+ * entry describes the textual position on which this type of error has been
+ * detected.
+ *
+ * @return The list of need-to-translate string literal positions
+ */
+ public abstract List<ILocation> getConstantStringLiterals();
+
+ /**
+ * Returns the list of broken Resource-Bundle references. Each list entry
+ * describes the textual position on which this type of error has been
+ * detected.
+ *
+ * @return The list of positions of broken Resource-Bundle references
+ */
+ public abstract List<ILocation> getBrokenResourceReferences();
+
+ /**
+ * Returns the list of broken references to Resource-Bundle entries. Each
+ * list entry describes the textual position on which this type of error has
+ * been detected
+ *
+ * @return The list of positions of broken references to locale-sensitive
+ * resources
+ */
+ public abstract List<ILocation> getBrokenBundleReferences();
+
+ /**
+ * Returns a characterizing identifier of the implemented auditing
+ * functionality. The specified identifier is used for discriminating
+ * registered builder extensions.
+ *
+ * @return The String id of the implemented auditing functionality
+ */
+ public abstract String getContextId();
+
+ /**
+ * Returns a list of quick fixes of a reported Internationalization problem.
+ *
+ * @param marker
+ * The warning marker of the Internationalization problem
+ * @param cause
+ * The problem type
+ * @return The list of marker resolution proposals
+ */
+ public abstract List<IMarkerResolution> getMarkerResolutions(
+ IMarker marker);
+
+ /**
+ * Checks if the provided resource auditor is responsible for a particular
+ * resource.
+ *
+ * @param resource
+ * The resource reference
+ * @return True if the resource auditor is responsible for the referenced
+ * resource
+ */
+ public boolean isResourceOfType(IResource resource) {
+ for (String ending : getFileEndings()) {
+ if (resource.getFileExtension().equalsIgnoreCase(ending))
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java
index efb2d3cc..44514c4d 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java
@@ -1,50 +1,57 @@
-package org.eclipse.babel.tapiji.tools.core.extensions;
-
-import java.io.Serializable;
-
-import org.eclipse.core.resources.IFile;
-
-/**
- * Describes a text fragment within a source resource.
- *
- * @author Martin Reiterer
- */
-public interface ILocation {
-
- /**
- * Returns the source resource's physical location.
- *
- * @return The file within the text fragment is located
- */
- public IFile getFile();
-
- /**
- * Returns the position of the text fragments starting character.
- *
- * @return The position of the first character
- */
- public int getStartPos();
-
- /**
- * Returns the position of the text fragments last character.
- *
- * @return The position of the last character
- */
- public int getEndPos();
-
- /**
- * Returns the text fragment.
- *
- * @return The text fragment
- */
- public String getLiteral();
-
- /**
- * Returns additional metadata. The type and content of this property is not
- * specified and can be used to marshal additional data for the computation
- * of resolution proposals.
- *
- * @return The metadata associated with the text fragment
- */
- public Serializable getData();
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.extensions;
+
+import java.io.Serializable;
+
+import org.eclipse.core.resources.IFile;
+
+/**
+ * Describes a text fragment within a source resource.
+ *
+ * @author Martin Reiterer
+ */
+public interface ILocation {
+
+ /**
+ * Returns the source resource's physical location.
+ *
+ * @return The file within the text fragment is located
+ */
+ public IFile getFile();
+
+ /**
+ * Returns the position of the text fragments starting character.
+ *
+ * @return The position of the first character
+ */
+ public int getStartPos();
+
+ /**
+ * Returns the position of the text fragments last character.
+ *
+ * @return The position of the last character
+ */
+ public int getEndPos();
+
+ /**
+ * Returns the text fragment.
+ *
+ * @return The text fragment
+ */
+ public String getLiteral();
+
+ /**
+ * Returns additional metadata. The type and content of this property is not
+ * specified and can be used to marshal additional data for the computation
+ * of resolution proposals.
+ *
+ * @return The metadata associated with the text fragment
+ */
+ public Serializable getData();
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
index d73d7dec..513daaf1 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java
@@ -1,11 +1,18 @@
-package org.eclipse.babel.tapiji.tools.core.extensions;
-
-public interface IMarkerConstants {
- public static final int CAUSE_BROKEN_REFERENCE = 0;
- public static final int CAUSE_CONSTANT_LITERAL = 1;
- public static final int CAUSE_BROKEN_RB_REFERENCE = 2;
-
- public static final int CAUSE_UNSPEZIFIED_KEY = 3;
- public static final int CAUSE_SAME_VALUE = 4;
- public static final int CAUSE_MISSING_LANGUAGE = 5;
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.extensions;
+
+public interface IMarkerConstants {
+ public static final int CAUSE_BROKEN_REFERENCE = 0;
+ public static final int CAUSE_CONSTANT_LITERAL = 1;
+ public static final int CAUSE_BROKEN_RB_REFERENCE = 2;
+
+ public static final int CAUSE_UNSPEZIFIED_KEY = 3;
+ public static final int CAUSE_SAME_VALUE = 4;
+ public static final int CAUSE_MISSING_LANGUAGE = 5;
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
index 7862ff72..f8879d43 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java
@@ -1,9 +1,16 @@
-package org.eclipse.babel.tapiji.tools.core.model;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
-
-public interface IResourceBundleChangedListener {
-
- public void resourceBundleChanged (ResourceBundleChangedEvent event);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+
+public interface IResourceBundleChangedListener {
+
+ public void resourceBundleChanged (ResourceBundleChangedEvent event);
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
index 12f59826..95357f6e 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java
@@ -1,21 +1,28 @@
-package org.eclipse.babel.tapiji.tools.core.model;
-
-public interface IResourceDescriptor {
-
- public void setProjectName (String projName);
-
- public void setRelativePath (String relPath);
-
- public void setAbsolutePath (String absPath);
-
- public void setBundleId (String bundleId);
-
- public String getProjectName ();
-
- public String getRelativePath ();
-
- public String getAbsolutePath ();
-
- public String getBundleId ();
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model;
+
+public interface IResourceDescriptor {
+
+ public void setProjectName (String projName);
+
+ public void setRelativePath (String relPath);
+
+ public void setAbsolutePath (String absPath);
+
+ public void setBundleId (String bundleId);
+
+ public String getProjectName ();
+
+ public String getRelativePath ();
+
+ public String getAbsolutePath ();
+
+ public String getBundleId ();
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java
index 033f15b0..24d9eec6 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java
@@ -1,9 +1,16 @@
-package org.eclipse.babel.tapiji.tools.core.model;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceExclusionEvent;
-
-public interface IResourceExclusionListener {
-
- public void exclusionChanged(ResourceExclusionEvent event);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceExclusionEvent;
+
+public interface IResourceExclusionListener {
+
+ public void exclusionChanged(ResourceExclusionEvent event);
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
index b1cf9620..eeebd481 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java
@@ -1,75 +1,82 @@
-package org.eclipse.babel.tapiji.tools.core.model;
-
-import org.eclipse.core.resources.IResource;
-
-public class ResourceDescriptor implements IResourceDescriptor {
-
- private String projectName;
- private String relativePath;
- private String absolutePath;
- private String bundleId;
-
- public ResourceDescriptor (IResource resource) {
- projectName = resource.getProject().getName();
- relativePath = resource.getProjectRelativePath().toString();
- absolutePath = resource.getRawLocation().toString();
- }
-
- public ResourceDescriptor() {
- }
-
- @Override
- public String getAbsolutePath() {
- return absolutePath;
- }
-
- @Override
- public String getProjectName() {
- return projectName;
- }
-
- @Override
- public String getRelativePath() {
- return relativePath;
- }
-
- @Override
- public int hashCode() {
- return projectName.hashCode() + relativePath.hashCode();
- }
-
- @Override
- public boolean equals(Object other) {
- if (!(other instanceof ResourceDescriptor))
- return false;
-
- return absolutePath.equals(absolutePath);
- }
-
- @Override
- public void setAbsolutePath(String absPath) {
- this.absolutePath = absPath;
- }
-
- @Override
- public void setProjectName(String projName) {
- this.projectName = projName;
- }
-
- @Override
- public void setRelativePath(String relPath) {
- this.relativePath = relPath;
- }
-
- @Override
- public String getBundleId() {
- return this.bundleId;
- }
-
- @Override
- public void setBundleId(String bundleId) {
- this.bundleId = bundleId;
- }
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model;
+
+import org.eclipse.core.resources.IResource;
+
+public class ResourceDescriptor implements IResourceDescriptor {
+
+ private String projectName;
+ private String relativePath;
+ private String absolutePath;
+ private String bundleId;
+
+ public ResourceDescriptor (IResource resource) {
+ projectName = resource.getProject().getName();
+ relativePath = resource.getProjectRelativePath().toString();
+ absolutePath = resource.getRawLocation().toString();
+ }
+
+ public ResourceDescriptor() {
+ }
+
+ @Override
+ public String getAbsolutePath() {
+ return absolutePath;
+ }
+
+ @Override
+ public String getProjectName() {
+ return projectName;
+ }
+
+ @Override
+ public String getRelativePath() {
+ return relativePath;
+ }
+
+ @Override
+ public int hashCode() {
+ return projectName.hashCode() + relativePath.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (!(other instanceof ResourceDescriptor))
+ return false;
+
+ return absolutePath.equals(absolutePath);
+ }
+
+ @Override
+ public void setAbsolutePath(String absPath) {
+ this.absolutePath = absPath;
+ }
+
+ @Override
+ public void setProjectName(String projName) {
+ this.projectName = projName;
+ }
+
+ @Override
+ public void setRelativePath(String relPath) {
+ this.relativePath = relPath;
+ }
+
+ @Override
+ public String getBundleId() {
+ return this.bundleId;
+ }
+
+ @Override
+ public void setBundleId(String bundleId) {
+ this.bundleId = bundleId;
+ }
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
index f8a0d1d5..ba4c83e0 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java
@@ -1,53 +1,60 @@
-package org.eclipse.babel.tapiji.tools.core.model;
-
-import java.io.Serializable;
-
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.core.resources.IFile;
-
-
-public class SLLocation implements Serializable, ILocation {
-
- private static final long serialVersionUID = 1L;
- private IFile file = null;
- private int startPos = -1;
- private int endPos = -1;
- private String literal;
- private Serializable data;
-
- public SLLocation(IFile file, int startPos, int endPos, String literal) {
- super();
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.literal = literal;
- }
- public IFile getFile() {
- return file;
- }
- public void setFile(IFile file) {
- this.file = file;
- }
- public int getStartPos() {
- return startPos;
- }
- public void setStartPos(int startPos) {
- this.startPos = startPos;
- }
- public int getEndPos() {
- return endPos;
- }
- public void setEndPos(int endPos) {
- this.endPos = endPos;
- }
- public String getLiteral() {
- return literal;
- }
- public Serializable getData () {
- return data;
- }
- public void setData (Serializable data) {
- this.data = data;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model;
+
+import java.io.Serializable;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IFile;
+
+
+public class SLLocation implements Serializable, ILocation {
+
+ private static final long serialVersionUID = 1L;
+ private IFile file = null;
+ private int startPos = -1;
+ private int endPos = -1;
+ private String literal;
+ private Serializable data;
+
+ public SLLocation(IFile file, int startPos, int endPos, String literal) {
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.literal = literal;
+ }
+ public IFile getFile() {
+ return file;
+ }
+ public void setFile(IFile file) {
+ this.file = file;
+ }
+ public int getStartPos() {
+ return startPos;
+ }
+ public void setStartPos(int startPos) {
+ this.startPos = startPos;
+ }
+ public int getEndPos() {
+ return endPos;
+ }
+ public void setEndPos(int endPos) {
+ this.endPos = endPos;
+ }
+ public String getLiteral() {
+ return literal;
+ }
+ public Serializable getData () {
+ return data;
+ }
+ public void setData (Serializable data) {
+ this.data = data;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
index 319b9166..46951d73 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
@@ -1,5 +1,12 @@
-package org.eclipse.babel.tapiji.tools.core.model.exception;
-
-public class NoSuchResourceAuditorException extends Exception {
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.exception;
+
+public class NoSuchResourceAuditorException extends Exception {
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
index e1e7e939..dac5453a 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java
@@ -1,15 +1,22 @@
-package org.eclipse.babel.tapiji.tools.core.model.exception;
-
-public class ResourceBundleException extends Exception {
-
- private static final long serialVersionUID = -2039182473628481126L;
-
- public ResourceBundleException (String msg) {
- super (msg);
- }
-
- public ResourceBundleException () {
- super();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.exception;
+
+public class ResourceBundleException extends Exception {
+
+ private static final long serialVersionUID = -2039182473628481126L;
+
+ public ResourceBundleException (String msg) {
+ super (msg);
+ }
+
+ public ResourceBundleException () {
+ super();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/RBChangeListner.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/RBChangeListner.java
index 7ee78ae6..4b0f0183 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/RBChangeListner.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/RBChangeListner.java
@@ -1,32 +1,39 @@
-package org.eclipse.babel.tapiji.tools.core.model.manager;
-
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.runtime.CoreException;
-
-public class RBChangeListner implements IResourceChangeListener {
-
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- try {
- event.getDelta().accept(new IResourceDeltaVisitor() {
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
- if (RBFileUtils.isResourceBundleFile(resource)) {
-// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
- return false;
- }
- return true;
- }
- });
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.manager;
+
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.runtime.CoreException;
+
+public class RBChangeListner implements IResourceChangeListener {
+
+ @Override
+ public void resourceChanged(IResourceChangeEvent event) {
+ try {
+ event.getDelta().accept(new IResourceDeltaVisitor() {
+ @Override
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ IResource resource = delta.getResource();
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+// ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta);
+ return false;
+ }
+ return true;
+ }
+ });
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
index de54cc36..45e49081 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
@@ -1,46 +1,53 @@
-package org.eclipse.babel.tapiji.tools.core.model.manager;
-
-import org.eclipse.core.resources.IProject;
-
-public class ResourceBundleChangedEvent {
-
- public final static int ADDED = 0;
- public final static int DELETED = 1;
- public final static int MODIFIED = 2;
- public final static int EXCLUDED = 3;
- public final static int INCLUDED = 4;
-
- private IProject project;
- private String bundle = "";
- private int type = -1;
-
- public ResourceBundleChangedEvent (int type, String bundle, IProject project) {
- this.type = type;
- this.bundle = bundle;
- this.project = project;
- }
-
- public IProject getProject() {
- return project;
- }
-
- public void setProject(IProject project) {
- this.project = project;
- }
-
- public String getBundle() {
- return bundle;
- }
-
- public void setBundle(String bundle) {
- this.bundle = bundle;
- }
-
- public int getType() {
- return type;
- }
-
- public void setType(int type) {
- this.type = type;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.manager;
+
+import org.eclipse.core.resources.IProject;
+
+public class ResourceBundleChangedEvent {
+
+ public final static int ADDED = 0;
+ public final static int DELETED = 1;
+ public final static int MODIFIED = 2;
+ public final static int EXCLUDED = 3;
+ public final static int INCLUDED = 4;
+
+ private IProject project;
+ private String bundle = "";
+ private int type = -1;
+
+ public ResourceBundleChangedEvent (int type, String bundle, IProject project) {
+ this.type = type;
+ this.bundle = bundle;
+ this.project = project;
+ }
+
+ public IProject getProject() {
+ return project;
+ }
+
+ public void setProject(IProject project) {
+ this.project = project;
+ }
+
+ public String getBundle() {
+ return bundle;
+ }
+
+ public void setBundle(String bundle) {
+ this.bundle = bundle;
+ }
+
+ public int getType() {
+ return type;
+ }
+
+ public void setType(int type) {
+ this.type = type;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java
index 5ca334f4..335ce079 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java
@@ -1,5 +1,12 @@
-package org.eclipse.babel.tapiji.tools.core.model.manager;
-
-public class ResourceBundleDetector {
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.manager;
+
+public class ResourceBundleDetector {
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
index 538a801d..8ec9f452 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleManager.java
@@ -1,802 +1,809 @@
-package org.eclipse.babel.tapiji.tools.core.model.manager;
-
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.babel.core.configuration.DirtyHack;
-import org.eclipse.babel.core.message.manager.RBManager;
-import org.eclipse.babel.editor.api.MessageFactory;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
-import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipse.babel.tapiji.tools.core.builder.analyzer.ResourceBundleDetectionVisitor;
-import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
-import org.eclipse.babel.tapiji.tools.core.model.IResourceDescriptor;
-import org.eclipse.babel.tapiji.tools.core.model.IResourceExclusionListener;
-import org.eclipse.babel.tapiji.tools.core.model.ResourceDescriptor;
-import org.eclipse.babel.tapiji.tools.core.model.exception.ResourceBundleException;
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.babel.tapiji.tools.core.util.FileUtils;
-import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.XMLMemento;
-
-public class ResourceBundleManager {
-
- public static String defaultLocaleTag = "[default]"; // TODO externalize
-
- /*** CONFIG SECTION ***/
- private static boolean checkResourceExclusionRoot = false;
-
- /*** MEMBER SECTION ***/
- private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>();
-
- public static final String RESOURCE_BUNDLE_EXTENSION = ".properties";
-
- // project-specific
- private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>();
-
- private Map<String, String> bundleNames = new HashMap<String, String>();
-
- private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>();
-
- private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>();
-
- // global
- private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>();
-
- private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>();
-
- private static IResourceChangeListener changelistener;
-
- /* Host project */
- private IProject project = null;
-
- /** State-Serialization Information **/
- private static boolean state_loaded = false;
- private static final String TAG_INTERNATIONALIZATION = "Internationalization";
- private static final String TAG_EXCLUDED = "Excluded";
- private static final String TAG_RES_DESC = "ResourceDescription";
- private static final String TAG_RES_DESC_ABS = "AbsolutePath";
- private static final String TAG_RES_DESC_REL = "RelativePath";
- private static final String TAB_RES_DESC_PRO = "ProjectName";
- private static final String TAB_RES_DESC_BID = "BundleId";
-
- // Define private constructor
- private ResourceBundleManager() {
- }
-
- public static ResourceBundleManager getManager(IProject project) {
- // check if persistant state has been loaded
- if (!state_loaded)
- loadManagerState();
-
- // set host-project
- if (FragmentProjectUtils.isFragment(project))
- project = FragmentProjectUtils.getFragmentHost(project);
-
- ResourceBundleManager manager = rbmanager.get(project);
- if (manager == null) {
- manager = new ResourceBundleManager();
- manager.project = project;
- rbmanager.put(project, manager);
- manager.detectResourceBundles();
-
- }
- return manager;
- }
-
- public Set<Locale> getProvidedLocales(String bundleName) {
- RBManager instance = RBManager.getInstance(project);
-
- Set<Locale> locales = new HashSet<Locale>();
- IMessagesBundleGroup group = instance
- .getMessagesBundleGroup(bundleName);
- if (group == null)
- return locales;
-
- for (IMessagesBundle bundle : group.getMessagesBundles()) {
- locales.add(bundle.getLocale());
- }
- return locales;
- }
-
- public static String getResourceBundleName(IResource res) {
- String name = res.getName();
- String regex = "^(.*?)" //$NON-NLS-1$
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
- + res.getFileExtension() + ")$"; //$NON-NLS-1$
- return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
- }
-
- protected boolean isResourceBundleLoaded(String bundleName) {
- return RBManager.getInstance(project).containsMessagesBundleGroup(
- bundleName);
- }
-
- protected Locale getLocaleByName(String bundleName, String localeID) {
- // Check locale
- Locale locale = null;
- bundleName = bundleNames.get(bundleName);
- localeID = localeID.substring(0,
- localeID.length() - "properties".length() - 1);
- if (localeID.length() == bundleName.length()) {
- // default locale
- return null;
- } else {
- localeID = localeID.substring(bundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
-
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1],
- localeTokens[2]);
- break;
- default:
- locale = null;
- break;
- }
- }
-
- return locale;
- }
-
- protected void unloadResource(String bundleName, IResource resource) {
- // TODO implement more efficient
- unloadResourceBundle(bundleName);
- // loadResourceBundle(bundleName);
- }
-
- public static String getResourceBundleId(IResource resource) {
- String packageFragment = "";
-
- IJavaElement propertyFile = JavaCore.create(resource.getParent());
- if (propertyFile != null && propertyFile instanceof IPackageFragment)
- packageFragment = ((IPackageFragment) propertyFile)
- .getElementName();
-
- return (packageFragment.length() > 0 ? packageFragment + "." : "")
- + getResourceBundleName(resource);
- }
-
- public void addBundleResource(IResource resource) {
- if (resource.isDerived())
- return;
-
- String bundleName = getResourceBundleId(resource);
- Set<IResource> res;
-
- if (!resources.containsKey(bundleName))
- res = new HashSet<IResource>();
- else
- res = resources.get(bundleName);
-
- res.add(resource);
- resources.put(bundleName, res);
- allBundles.put(bundleName, new HashSet<IResource>(res));
- bundleNames.put(bundleName, getResourceBundleName(resource));
-
- // Fire resource changed event
- ResourceBundleChangedEvent event = new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.ADDED, bundleName,
- resource.getProject());
- this.fireResourceBundleChangedEvent(bundleName, event);
- }
-
- protected void removeAllBundleResources(String bundleName) {
- unloadResourceBundle(bundleName);
- resources.remove(bundleName);
- // allBundles.remove(bundleName);
- listeners.remove(bundleName);
- }
-
- public void unloadResourceBundle(String name) {
- RBManager instance = RBManager.getInstance(project);
- instance.deleteMessagesBundleGroup(name);
- }
-
- public IMessagesBundleGroup getResourceBundle(String name) {
- RBManager instance = RBManager.getInstance(project);
- return instance.getMessagesBundleGroup(name);
- }
-
- public Collection<IResource> getResourceBundles(String bundleName) {
- return resources.get(bundleName);
- }
-
- public List<String> getResourceBundleNames() {
- List<String> returnList = new ArrayList<String>();
-
- Iterator<String> it = resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(it.next());
- }
- return returnList;
- }
-
- public IResource getResourceFile(String file) {
- String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$";
- String bundleName = file.replaceFirst(regex, "$1");
- IResource resource = null;
-
- for (IResource res : resources.get(bundleName)) {
- if (res.getName().equalsIgnoreCase(file)) {
- resource = res;
- break;
- }
- }
-
- return resource;
- }
-
- public void fireResourceBundleChangedEvent(String bundleName,
- ResourceBundleChangedEvent event) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
-
- if (l == null)
- return;
-
- for (IResourceBundleChangedListener listener : l) {
- listener.resourceBundleChanged(event);
- }
- }
-
- public void registerResourceBundleChangeListener(String bundleName,
- IResourceBundleChangedListener listener) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null)
- l = new ArrayList<IResourceBundleChangedListener>();
- l.add(listener);
- listeners.put(bundleName, l);
- }
-
- public void unregisterResourceBundleChangeListener(String bundleName,
- IResourceBundleChangedListener listener) {
- List<IResourceBundleChangedListener> l = listeners.get(bundleName);
- if (l == null)
- return;
- l.remove(listener);
- listeners.put(bundleName, l);
- }
-
- protected void detectResourceBundles() {
- try {
- project.accept(new ResourceBundleDetectionVisitor(getProject()));
-
- IProject[] fragments = FragmentProjectUtils.lookupFragment(project);
- if (fragments != null) {
- for (IProject p : fragments) {
- p.accept(new ResourceBundleDetectionVisitor(getProject()));
- }
- }
- } catch (CoreException e) {
- }
- }
-
- public IProject getProject() {
- return project;
- }
-
- public List<String> getResourceBundleIdentifiers() {
- List<String> returnList = new ArrayList<String>();
-
- // TODO check other resource bundles that are available on the curren
- // class path
- Iterator<String> it = this.resources.keySet().iterator();
- while (it.hasNext()) {
- returnList.add(it.next());
- }
-
- return returnList;
- }
-
- public static List<String> getAllResourceBundleNames() {
- List<String> returnList = new ArrayList<String>();
-
- for (IProject p : getAllSupportedProjects()) {
- if (!FragmentProjectUtils.isFragment(p)) {
- Iterator<String> it = getManager(p).resources.keySet()
- .iterator();
- while (it.hasNext()) {
- returnList.add(p.getName() + "/" + it.next());
- }
- }
- }
- return returnList;
- }
-
- public static Set<IProject> getAllSupportedProjects() {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
- .getProjects();
- Set<IProject> projs = new HashSet<IProject>();
-
- for (IProject p : projects) {
- if (InternationalizationNature.hasNature(p))
- projs.add(p);
- }
- return projs;
- }
-
- public String getKeyHoverString(String rbName, String key) {
- try {
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup bundleGroup = instance
- .getMessagesBundleGroup(rbName);
- if (!bundleGroup.containsKey(key))
- return null;
-
- String hoverText = "<html><head></head><body>";
-
- for (IMessage message : bundleGroup.getMessages(key)) {
- String displayName = message.getLocale() == null ? "Default"
- : message.getLocale().getDisplayName();
- String value = message.getValue();
- hoverText += "<b><i>" + displayName + "</i></b><br/>"
- + value.replace("\n", "<br/>") + "<br/><br/>";
- }
- return hoverText + "</body></html>";
- } catch (Exception e) {
- // silent catch
- return "";
- }
- }
-
- public boolean isKeyBroken(String rbName, String key) {
- IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
- project).getMessagesBundleGroup(rbName);
- if (messagesBundleGroup == null) {
- return true;
- } else {
- return !messagesBundleGroup.containsKey(key);
- }
-
- // if (!resourceBundles.containsKey(rbName))
- // return true;
- // return !this.isResourceExisting(rbName, key);
- }
-
- protected void excludeSingleResource(IResource res) {
- IResourceDescriptor rd = new ResourceDescriptor(res);
- EditorUtils.deleteAuditMarkersForResource(res);
-
- // exclude resource
- excludedResources.add(rd);
- Collection<Object> changedExclusoins = new HashSet<Object>();
- changedExclusoins.add(res);
- fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins));
-
- // Check if the excluded resource represents a resource-bundle
- if (RBFileUtils.isResourceBundleFile(res)) {
- String bundleName = getResourceBundleId(res);
- Set<IResource> resSet = resources.remove(bundleName);
- if (resSet != null) {
- resSet.remove(res);
-
- if (!resSet.isEmpty()) {
- resources.put(bundleName, resSet);
- unloadResource(bundleName, res);
- } else {
- rd.setBundleId(bundleName);
- unloadResourceBundle(bundleName);
- (new I18nBuilder()).buildProject(null, res.getProject());
- }
-
- fireResourceBundleChangedEvent(getResourceBundleId(res),
- new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.EXCLUDED,
- bundleName, res.getProject()));
- }
- }
- }
-
- public void excludeResource(IResource res, IProgressMonitor monitor) {
- try {
- if (monitor == null)
- monitor = new NullProgressMonitor();
-
- final List<IResource> resourceSubTree = new ArrayList<IResource>();
- res.accept(new IResourceVisitor() {
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- Logger.logInfo("Excluding resource '"
- + resource.getFullPath().toOSString() + "'");
- resourceSubTree.add(resource);
- return true;
- }
-
- });
-
- // Iterate previously retrieved resource and exclude them from
- // Internationalization
- monitor.beginTask(
- "Exclude resources from Internationalization context",
- resourceSubTree.size());
- try {
- for (IResource resource : resourceSubTree) {
- excludeSingleResource(resource);
- EditorUtils.deleteAuditMarkersForResource(resource);
- monitor.worked(1);
- }
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- monitor.done();
- }
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public void includeResource(IResource res, IProgressMonitor monitor) {
- if (monitor == null)
- monitor = new NullProgressMonitor();
-
- final Collection<Object> changedResources = new HashSet<Object>();
- IResource resource = res;
-
- if (!excludedResources.contains(new ResourceDescriptor(res))) {
- while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) {
- if (excludedResources
- .contains(new ResourceDescriptor(resource))) {
- excludeResource(resource, monitor);
- changedResources.add(resource);
- break;
- } else
- resource = resource.getParent();
- }
- }
-
- try {
- res.accept(new IResourceVisitor() {
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- changedResources.add(resource);
- return true;
- }
- });
-
- monitor.beginTask("Add resources to Internationalization context",
- changedResources.size());
- try {
- for (Object r : changedResources) {
- excludedResources.remove(new ResourceDescriptor(
- (IResource) r));
- monitor.worked(1);
- }
-
- } catch (Exception e) {
- Logger.logError(e);
- } finally {
- monitor.done();
- }
- } catch (Exception e) {
- Logger.logError(e);
- }
-
- (new I18nBuilder()).buildResource(res, null);
-
- // Check if the included resource represents a resource-bundle
- if (RBFileUtils.isResourceBundleFile(res)) {
- String bundleName = getResourceBundleId(res);
- boolean newRB = resources.containsKey(bundleName);
-
- this.addBundleResource(res);
- this.unloadResourceBundle(bundleName);
- // this.loadResourceBundle(bundleName);
-
- if (newRB)
- (new I18nBuilder()).buildProject(null, res.getProject());
- fireResourceBundleChangedEvent(getResourceBundleId(res),
- new ResourceBundleChangedEvent(
- ResourceBundleChangedEvent.INCLUDED, bundleName,
- res.getProject()));
- }
-
- fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources));
- }
-
- protected void fireResourceExclusionEvent(ResourceExclusionEvent event) {
- for (IResourceExclusionListener listener : exclusionListeners)
- listener.exclusionChanged(event);
- }
-
- public static boolean isResourceExcluded(IResource res) {
- IResource resource = res;
-
- if (!state_loaded)
- loadManagerState();
-
- boolean isExcluded = false;
-
- do {
- if (excludedResources.contains(new ResourceDescriptor(resource))) {
- if (RBFileUtils.isResourceBundleFile(resource)) {
- Set<IResource> resources = allBundles
- .remove(getResourceBundleName(resource));
- if (resources == null)
- resources = new HashSet<IResource>();
- resources.add(resource);
- allBundles.put(getResourceBundleName(resource), resources);
- }
-
- isExcluded = true;
- break;
- }
- resource = resource.getParent();
- } while (resource != null
- && !(resource instanceof IProject || resource instanceof IWorkspaceRoot)
- && checkResourceExclusionRoot);
-
- return isExcluded; // excludedResources.contains(new
- // ResourceDescriptor(res));
- }
-
- public IFile getRandomFile(String bundleName) {
- try {
- IResource res = (resources.get(bundleName)).iterator().next();
- return res.getProject().getFile(res.getProjectRelativePath());
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private static void loadManagerState() {
- excludedResources = new HashSet<IResourceDescriptor>();
- FileReader reader = null;
- try {
- reader = new FileReader(FileUtils.getRBManagerStateFile());
- loadManagerState(XMLMemento.createReadRoot(reader));
- state_loaded = true;
- } catch (Exception e) {
- // do nothing
- }
-
- changelistener = new RBChangeListner();
- ResourcesPlugin.getWorkspace().addResourceChangeListener(
- changelistener,
- IResourceChangeEvent.PRE_DELETE
- | IResourceChangeEvent.POST_CHANGE);
- }
-
- private static void loadManagerState(XMLMemento memento) {
- IMemento excludedChild = memento.getChild(TAG_EXCLUDED);
- for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) {
- IResourceDescriptor descriptor = new ResourceDescriptor();
- descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS));
- descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL));
- descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO));
- descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID));
- excludedResources.add(descriptor);
- }
- }
-
- public static void saveManagerState() {
- if (excludedResources == null)
- return;
- XMLMemento memento = XMLMemento
- .createWriteRoot(TAG_INTERNATIONALIZATION);
- IMemento exclChild = memento.createChild(TAG_EXCLUDED);
-
- Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
- while (itExcl.hasNext()) {
- IResourceDescriptor desc = itExcl.next();
- IMemento resDesc = exclChild.createChild(TAG_RES_DESC);
- resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName());
- resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath());
- resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath());
- resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId());
- }
- FileWriter writer = null;
- try {
- writer = new FileWriter(FileUtils.getRBManagerStateFile());
- memento.save(writer);
- } catch (Exception e) {
- // do nothing
- } finally {
- try {
- if (writer != null)
- writer.close();
- } catch (Exception e) {
- // do nothing
- }
- }
- }
-
- @Deprecated
- protected static boolean isResourceExcluded(IProject project, String bname) {
- Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
- while (itExcl.hasNext()) {
- IResourceDescriptor rd = itExcl.next();
- if (project.getName().equals(rd.getProjectName())
- && bname.equals(rd.getBundleId()))
- return true;
- }
- return false;
- }
-
- public static ResourceBundleManager getManager(String projectName) {
- for (IProject p : getAllSupportedProjects()) {
- if (p.getName().equalsIgnoreCase(projectName)) {
- // check if the projectName is a fragment and return the manager
- // for the host
- if (FragmentProjectUtils.isFragment(p))
- return getManager(FragmentProjectUtils.getFragmentHost(p));
- else
- return getManager(p);
- }
- }
- return null;
- }
-
- public IFile getResourceBundleFile(String resourceBundle, Locale l) {
- IFile res = null;
- Set<IResource> resSet = resources.get(resourceBundle);
-
- if (resSet != null) {
- for (IResource resource : resSet) {
- Locale refLoc = getLocaleByName(resourceBundle,
- resource.getName());
- if (refLoc == null
- && l == null
- || (refLoc != null && refLoc.equals(l) || l != null
- && l.equals(refLoc))) {
- res = resource.getProject().getFile(
- resource.getProjectRelativePath());
- break;
- }
- }
- }
-
- return res;
- }
-
- public Set<IResource> getAllResourceBundleResources(String resourceBundle) {
- return allBundles.get(resourceBundle);
- }
-
- public void registerResourceExclusionListener(
- IResourceExclusionListener listener) {
- exclusionListeners.add(listener);
- }
-
- public void unregisterResourceExclusionListener(
- IResourceExclusionListener listener) {
- exclusionListeners.remove(listener);
- }
-
- public boolean isResourceExclusionListenerRegistered(
- IResourceExclusionListener listener) {
- return exclusionListeners.contains(listener);
- }
-
- public static void unregisterResourceExclusionListenerFromAllManagers(
- IResourceExclusionListener excludedResource) {
- for (ResourceBundleManager mgr : rbmanager.values()) {
- mgr.unregisterResourceExclusionListener(excludedResource);
- }
- }
-
- public void addResourceBundleEntry(String resourceBundleId, String key,
- Locale locale, String message) throws ResourceBundleException {
-
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup bundleGroup = instance
- .getMessagesBundleGroup(resourceBundleId);
- IMessage entry = bundleGroup.getMessage(key, locale);
-
- if (entry == null) {
- DirtyHack.setFireEnabled(false);
-
- IMessagesBundle messagesBundle = bundleGroup
- .getMessagesBundle(locale);
- IMessage m = MessageFactory.createMessage(key, locale);
- m.setText(message);
- messagesBundle.addMessage(m);
-
- instance.writeToFile(messagesBundle);
-
- DirtyHack.setFireEnabled(true);
-
- // notify the PropertyKeySelectionTree
- instance.fireEditorChanged();
- }
- }
-
- public void saveResourceBundle(String resourceBundleId,
- IMessagesBundleGroup newBundleGroup) throws ResourceBundleException {
-
- // RBManager.getInstance().
- }
-
- public void removeResourceBundleEntry(String resourceBundleId,
- List<String> keys) throws ResourceBundleException {
-
- RBManager instance = RBManager.getInstance(project);
- IMessagesBundleGroup messagesBundleGroup = instance
- .getMessagesBundleGroup(resourceBundleId);
-
- DirtyHack.setFireEnabled(false);
-
- for (String key : keys) {
- messagesBundleGroup.removeMessages(key);
- }
-
- instance.writeToFile(messagesBundleGroup);
-
- DirtyHack.setFireEnabled(true);
-
- // notify the PropertyKeySelectionTree
- instance.fireEditorChanged();
- }
-
- public boolean isResourceExisting(String bundleId, String key) {
- boolean keyExists = false;
- IMessagesBundleGroup bGroup = getResourceBundle(bundleId);
-
- if (bGroup != null) {
- keyExists = bGroup.isKey(key);
- }
-
- return keyExists;
- }
-
- public static void refreshResource(IResource resource) {
- (new I18nBuilder()).buildProject(null, resource.getProject());
- (new I18nBuilder()).buildResource(resource, null);
- }
-
- public Set<Locale> getProjectProvidedLocales() {
- Set<Locale> locales = new HashSet<Locale>();
-
- for (String bundleId : getResourceBundleNames()) {
- Set<Locale> rb_l = getProvidedLocales(bundleId);
- if (!rb_l.isEmpty()) {
- Object[] bundlelocales = rb_l.toArray();
- for (Object l : bundlelocales) {
- /* TODO check if useful to add the default */
- if (!locales.contains(l))
- locales.add((Locale) l);
- }
- }
- }
- return locales;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.manager;
+
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.babel.core.configuration.DirtyHack;
+import org.eclipse.babel.core.message.manager.RBManager;
+import org.eclipse.babel.editor.api.MessageFactory;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
+import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.core.builder.analyzer.ResourceBundleDetectionVisitor;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceDescriptor;
+import org.eclipse.babel.tapiji.tools.core.model.IResourceExclusionListener;
+import org.eclipse.babel.tapiji.tools.core.model.ResourceDescriptor;
+import org.eclipse.babel.tapiji.tools.core.model.exception.ResourceBundleException;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FileUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundle;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.jdt.core.IJavaElement;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.XMLMemento;
+
+public class ResourceBundleManager {
+
+ public static String defaultLocaleTag = "[default]"; // TODO externalize
+
+ /*** CONFIG SECTION ***/
+ private static boolean checkResourceExclusionRoot = false;
+
+ /*** MEMBER SECTION ***/
+ private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>();
+
+ public static final String RESOURCE_BUNDLE_EXTENSION = ".properties";
+
+ // project-specific
+ private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>();
+
+ private Map<String, String> bundleNames = new HashMap<String, String>();
+
+ private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>();
+
+ private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>();
+
+ // global
+ private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>();
+
+ private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>();
+
+ private static IResourceChangeListener changelistener;
+
+ /* Host project */
+ private IProject project = null;
+
+ /** State-Serialization Information **/
+ private static boolean state_loaded = false;
+ private static final String TAG_INTERNATIONALIZATION = "Internationalization";
+ private static final String TAG_EXCLUDED = "Excluded";
+ private static final String TAG_RES_DESC = "ResourceDescription";
+ private static final String TAG_RES_DESC_ABS = "AbsolutePath";
+ private static final String TAG_RES_DESC_REL = "RelativePath";
+ private static final String TAB_RES_DESC_PRO = "ProjectName";
+ private static final String TAB_RES_DESC_BID = "BundleId";
+
+ // Define private constructor
+ private ResourceBundleManager() {
+ }
+
+ public static ResourceBundleManager getManager(IProject project) {
+ // check if persistant state has been loaded
+ if (!state_loaded)
+ loadManagerState();
+
+ // set host-project
+ if (FragmentProjectUtils.isFragment(project))
+ project = FragmentProjectUtils.getFragmentHost(project);
+
+ ResourceBundleManager manager = rbmanager.get(project);
+ if (manager == null) {
+ manager = new ResourceBundleManager();
+ manager.project = project;
+ rbmanager.put(project, manager);
+ manager.detectResourceBundles();
+
+ }
+ return manager;
+ }
+
+ public Set<Locale> getProvidedLocales(String bundleName) {
+ RBManager instance = RBManager.getInstance(project);
+
+ Set<Locale> locales = new HashSet<Locale>();
+ IMessagesBundleGroup group = instance
+ .getMessagesBundleGroup(bundleName);
+ if (group == null)
+ return locales;
+
+ for (IMessagesBundle bundle : group.getMessagesBundles()) {
+ locales.add(bundle.getLocale());
+ }
+ return locales;
+ }
+
+ public static String getResourceBundleName(IResource res) {
+ String name = res.getName();
+ String regex = "^(.*?)" //$NON-NLS-1$
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$
+ + res.getFileExtension() + ")$"; //$NON-NLS-1$
+ return name.replaceFirst(regex, "$1"); //$NON-NLS-1$
+ }
+
+ protected boolean isResourceBundleLoaded(String bundleName) {
+ return RBManager.getInstance(project).containsMessagesBundleGroup(
+ bundleName);
+ }
+
+ protected Locale getLocaleByName(String bundleName, String localeID) {
+ // Check locale
+ Locale locale = null;
+ bundleName = bundleNames.get(bundleName);
+ localeID = localeID.substring(0,
+ localeID.length() - "properties".length() - 1);
+ if (localeID.length() == bundleName.length()) {
+ // default locale
+ return null;
+ } else {
+ localeID = localeID.substring(bundleName.length() + 1);
+ String[] localeTokens = localeID.split("_");
+
+ switch (localeTokens.length) {
+ case 1:
+ locale = new Locale(localeTokens[0]);
+ break;
+ case 2:
+ locale = new Locale(localeTokens[0], localeTokens[1]);
+ break;
+ case 3:
+ locale = new Locale(localeTokens[0], localeTokens[1],
+ localeTokens[2]);
+ break;
+ default:
+ locale = null;
+ break;
+ }
+ }
+
+ return locale;
+ }
+
+ protected void unloadResource(String bundleName, IResource resource) {
+ // TODO implement more efficient
+ unloadResourceBundle(bundleName);
+ // loadResourceBundle(bundleName);
+ }
+
+ public static String getResourceBundleId(IResource resource) {
+ String packageFragment = "";
+
+ IJavaElement propertyFile = JavaCore.create(resource.getParent());
+ if (propertyFile != null && propertyFile instanceof IPackageFragment)
+ packageFragment = ((IPackageFragment) propertyFile)
+ .getElementName();
+
+ return (packageFragment.length() > 0 ? packageFragment + "." : "")
+ + getResourceBundleName(resource);
+ }
+
+ public void addBundleResource(IResource resource) {
+ if (resource.isDerived())
+ return;
+
+ String bundleName = getResourceBundleId(resource);
+ Set<IResource> res;
+
+ if (!resources.containsKey(bundleName))
+ res = new HashSet<IResource>();
+ else
+ res = resources.get(bundleName);
+
+ res.add(resource);
+ resources.put(bundleName, res);
+ allBundles.put(bundleName, new HashSet<IResource>(res));
+ bundleNames.put(bundleName, getResourceBundleName(resource));
+
+ // Fire resource changed event
+ ResourceBundleChangedEvent event = new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.ADDED, bundleName,
+ resource.getProject());
+ this.fireResourceBundleChangedEvent(bundleName, event);
+ }
+
+ protected void removeAllBundleResources(String bundleName) {
+ unloadResourceBundle(bundleName);
+ resources.remove(bundleName);
+ // allBundles.remove(bundleName);
+ listeners.remove(bundleName);
+ }
+
+ public void unloadResourceBundle(String name) {
+ RBManager instance = RBManager.getInstance(project);
+ instance.deleteMessagesBundleGroup(name);
+ }
+
+ public IMessagesBundleGroup getResourceBundle(String name) {
+ RBManager instance = RBManager.getInstance(project);
+ return instance.getMessagesBundleGroup(name);
+ }
+
+ public Collection<IResource> getResourceBundles(String bundleName) {
+ return resources.get(bundleName);
+ }
+
+ public List<String> getResourceBundleNames() {
+ List<String> returnList = new ArrayList<String>();
+
+ Iterator<String> it = resources.keySet().iterator();
+ while (it.hasNext()) {
+ returnList.add(it.next());
+ }
+ return returnList;
+ }
+
+ public IResource getResourceFile(String file) {
+ String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$";
+ String bundleName = file.replaceFirst(regex, "$1");
+ IResource resource = null;
+
+ for (IResource res : resources.get(bundleName)) {
+ if (res.getName().equalsIgnoreCase(file)) {
+ resource = res;
+ break;
+ }
+ }
+
+ return resource;
+ }
+
+ public void fireResourceBundleChangedEvent(String bundleName,
+ ResourceBundleChangedEvent event) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+
+ if (l == null)
+ return;
+
+ for (IResourceBundleChangedListener listener : l) {
+ listener.resourceBundleChanged(event);
+ }
+ }
+
+ public void registerResourceBundleChangeListener(String bundleName,
+ IResourceBundleChangedListener listener) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ if (l == null)
+ l = new ArrayList<IResourceBundleChangedListener>();
+ l.add(listener);
+ listeners.put(bundleName, l);
+ }
+
+ public void unregisterResourceBundleChangeListener(String bundleName,
+ IResourceBundleChangedListener listener) {
+ List<IResourceBundleChangedListener> l = listeners.get(bundleName);
+ if (l == null)
+ return;
+ l.remove(listener);
+ listeners.put(bundleName, l);
+ }
+
+ protected void detectResourceBundles() {
+ try {
+ project.accept(new ResourceBundleDetectionVisitor(getProject()));
+
+ IProject[] fragments = FragmentProjectUtils.lookupFragment(project);
+ if (fragments != null) {
+ for (IProject p : fragments) {
+ p.accept(new ResourceBundleDetectionVisitor(getProject()));
+ }
+ }
+ } catch (CoreException e) {
+ }
+ }
+
+ public IProject getProject() {
+ return project;
+ }
+
+ public List<String> getResourceBundleIdentifiers() {
+ List<String> returnList = new ArrayList<String>();
+
+ // TODO check other resource bundles that are available on the curren
+ // class path
+ Iterator<String> it = this.resources.keySet().iterator();
+ while (it.hasNext()) {
+ returnList.add(it.next());
+ }
+
+ return returnList;
+ }
+
+ public static List<String> getAllResourceBundleNames() {
+ List<String> returnList = new ArrayList<String>();
+
+ for (IProject p : getAllSupportedProjects()) {
+ if (!FragmentProjectUtils.isFragment(p)) {
+ Iterator<String> it = getManager(p).resources.keySet()
+ .iterator();
+ while (it.hasNext()) {
+ returnList.add(p.getName() + "/" + it.next());
+ }
+ }
+ }
+ return returnList;
+ }
+
+ public static Set<IProject> getAllSupportedProjects() {
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
+ .getProjects();
+ Set<IProject> projs = new HashSet<IProject>();
+
+ for (IProject p : projects) {
+ if (InternationalizationNature.hasNature(p))
+ projs.add(p);
+ }
+ return projs;
+ }
+
+ public String getKeyHoverString(String rbName, String key) {
+ try {
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup bundleGroup = instance
+ .getMessagesBundleGroup(rbName);
+ if (!bundleGroup.containsKey(key))
+ return null;
+
+ String hoverText = "<html><head></head><body>";
+
+ for (IMessage message : bundleGroup.getMessages(key)) {
+ String displayName = message.getLocale() == null ? "Default"
+ : message.getLocale().getDisplayName();
+ String value = message.getValue();
+ hoverText += "<b><i>" + displayName + "</i></b><br/>"
+ + value.replace("\n", "<br/>") + "<br/><br/>";
+ }
+ return hoverText + "</body></html>";
+ } catch (Exception e) {
+ // silent catch
+ return "";
+ }
+ }
+
+ public boolean isKeyBroken(String rbName, String key) {
+ IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance(
+ project).getMessagesBundleGroup(rbName);
+ if (messagesBundleGroup == null) {
+ return true;
+ } else {
+ return !messagesBundleGroup.containsKey(key);
+ }
+
+ // if (!resourceBundles.containsKey(rbName))
+ // return true;
+ // return !this.isResourceExisting(rbName, key);
+ }
+
+ protected void excludeSingleResource(IResource res) {
+ IResourceDescriptor rd = new ResourceDescriptor(res);
+ EditorUtils.deleteAuditMarkersForResource(res);
+
+ // exclude resource
+ excludedResources.add(rd);
+ Collection<Object> changedExclusoins = new HashSet<Object>();
+ changedExclusoins.add(res);
+ fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins));
+
+ // Check if the excluded resource represents a resource-bundle
+ if (RBFileUtils.isResourceBundleFile(res)) {
+ String bundleName = getResourceBundleId(res);
+ Set<IResource> resSet = resources.remove(bundleName);
+ if (resSet != null) {
+ resSet.remove(res);
+
+ if (!resSet.isEmpty()) {
+ resources.put(bundleName, resSet);
+ unloadResource(bundleName, res);
+ } else {
+ rd.setBundleId(bundleName);
+ unloadResourceBundle(bundleName);
+ (new I18nBuilder()).buildProject(null, res.getProject());
+ }
+
+ fireResourceBundleChangedEvent(getResourceBundleId(res),
+ new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.EXCLUDED,
+ bundleName, res.getProject()));
+ }
+ }
+ }
+
+ public void excludeResource(IResource res, IProgressMonitor monitor) {
+ try {
+ if (monitor == null)
+ monitor = new NullProgressMonitor();
+
+ final List<IResource> resourceSubTree = new ArrayList<IResource>();
+ res.accept(new IResourceVisitor() {
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ Logger.logInfo("Excluding resource '"
+ + resource.getFullPath().toOSString() + "'");
+ resourceSubTree.add(resource);
+ return true;
+ }
+
+ });
+
+ // Iterate previously retrieved resource and exclude them from
+ // Internationalization
+ monitor.beginTask(
+ "Exclude resources from Internationalization context",
+ resourceSubTree.size());
+ try {
+ for (IResource resource : resourceSubTree) {
+ excludeSingleResource(resource);
+ EditorUtils.deleteAuditMarkersForResource(resource);
+ monitor.worked(1);
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ monitor.done();
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public void includeResource(IResource res, IProgressMonitor monitor) {
+ if (monitor == null)
+ monitor = new NullProgressMonitor();
+
+ final Collection<Object> changedResources = new HashSet<Object>();
+ IResource resource = res;
+
+ if (!excludedResources.contains(new ResourceDescriptor(res))) {
+ while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) {
+ if (excludedResources
+ .contains(new ResourceDescriptor(resource))) {
+ excludeResource(resource, monitor);
+ changedResources.add(resource);
+ break;
+ } else
+ resource = resource.getParent();
+ }
+ }
+
+ try {
+ res.accept(new IResourceVisitor() {
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ changedResources.add(resource);
+ return true;
+ }
+ });
+
+ monitor.beginTask("Add resources to Internationalization context",
+ changedResources.size());
+ try {
+ for (Object r : changedResources) {
+ excludedResources.remove(new ResourceDescriptor(
+ (IResource) r));
+ monitor.worked(1);
+ }
+
+ } catch (Exception e) {
+ Logger.logError(e);
+ } finally {
+ monitor.done();
+ }
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+
+ (new I18nBuilder()).buildResource(res, null);
+
+ // Check if the included resource represents a resource-bundle
+ if (RBFileUtils.isResourceBundleFile(res)) {
+ String bundleName = getResourceBundleId(res);
+ boolean newRB = resources.containsKey(bundleName);
+
+ this.addBundleResource(res);
+ this.unloadResourceBundle(bundleName);
+ // this.loadResourceBundle(bundleName);
+
+ if (newRB)
+ (new I18nBuilder()).buildProject(null, res.getProject());
+ fireResourceBundleChangedEvent(getResourceBundleId(res),
+ new ResourceBundleChangedEvent(
+ ResourceBundleChangedEvent.INCLUDED, bundleName,
+ res.getProject()));
+ }
+
+ fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources));
+ }
+
+ protected void fireResourceExclusionEvent(ResourceExclusionEvent event) {
+ for (IResourceExclusionListener listener : exclusionListeners)
+ listener.exclusionChanged(event);
+ }
+
+ public static boolean isResourceExcluded(IResource res) {
+ IResource resource = res;
+
+ if (!state_loaded)
+ loadManagerState();
+
+ boolean isExcluded = false;
+
+ do {
+ if (excludedResources.contains(new ResourceDescriptor(resource))) {
+ if (RBFileUtils.isResourceBundleFile(resource)) {
+ Set<IResource> resources = allBundles
+ .remove(getResourceBundleName(resource));
+ if (resources == null)
+ resources = new HashSet<IResource>();
+ resources.add(resource);
+ allBundles.put(getResourceBundleName(resource), resources);
+ }
+
+ isExcluded = true;
+ break;
+ }
+ resource = resource.getParent();
+ } while (resource != null
+ && !(resource instanceof IProject || resource instanceof IWorkspaceRoot)
+ && checkResourceExclusionRoot);
+
+ return isExcluded; // excludedResources.contains(new
+ // ResourceDescriptor(res));
+ }
+
+ public IFile getRandomFile(String bundleName) {
+ try {
+ IResource res = (resources.get(bundleName)).iterator().next();
+ return res.getProject().getFile(res.getProjectRelativePath());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ private static void loadManagerState() {
+ excludedResources = new HashSet<IResourceDescriptor>();
+ FileReader reader = null;
+ try {
+ reader = new FileReader(FileUtils.getRBManagerStateFile());
+ loadManagerState(XMLMemento.createReadRoot(reader));
+ state_loaded = true;
+ } catch (Exception e) {
+ // do nothing
+ }
+
+ changelistener = new RBChangeListner();
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(
+ changelistener,
+ IResourceChangeEvent.PRE_DELETE
+ | IResourceChangeEvent.POST_CHANGE);
+ }
+
+ private static void loadManagerState(XMLMemento memento) {
+ IMemento excludedChild = memento.getChild(TAG_EXCLUDED);
+ for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) {
+ IResourceDescriptor descriptor = new ResourceDescriptor();
+ descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS));
+ descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL));
+ descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO));
+ descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID));
+ excludedResources.add(descriptor);
+ }
+ }
+
+ public static void saveManagerState() {
+ if (excludedResources == null)
+ return;
+ XMLMemento memento = XMLMemento
+ .createWriteRoot(TAG_INTERNATIONALIZATION);
+ IMemento exclChild = memento.createChild(TAG_EXCLUDED);
+
+ Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
+ while (itExcl.hasNext()) {
+ IResourceDescriptor desc = itExcl.next();
+ IMemento resDesc = exclChild.createChild(TAG_RES_DESC);
+ resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName());
+ resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath());
+ resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath());
+ resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId());
+ }
+ FileWriter writer = null;
+ try {
+ writer = new FileWriter(FileUtils.getRBManagerStateFile());
+ memento.save(writer);
+ } catch (Exception e) {
+ // do nothing
+ } finally {
+ try {
+ if (writer != null)
+ writer.close();
+ } catch (Exception e) {
+ // do nothing
+ }
+ }
+ }
+
+ @Deprecated
+ protected static boolean isResourceExcluded(IProject project, String bname) {
+ Iterator<IResourceDescriptor> itExcl = excludedResources.iterator();
+ while (itExcl.hasNext()) {
+ IResourceDescriptor rd = itExcl.next();
+ if (project.getName().equals(rd.getProjectName())
+ && bname.equals(rd.getBundleId()))
+ return true;
+ }
+ return false;
+ }
+
+ public static ResourceBundleManager getManager(String projectName) {
+ for (IProject p : getAllSupportedProjects()) {
+ if (p.getName().equalsIgnoreCase(projectName)) {
+ // check if the projectName is a fragment and return the manager
+ // for the host
+ if (FragmentProjectUtils.isFragment(p))
+ return getManager(FragmentProjectUtils.getFragmentHost(p));
+ else
+ return getManager(p);
+ }
+ }
+ return null;
+ }
+
+ public IFile getResourceBundleFile(String resourceBundle, Locale l) {
+ IFile res = null;
+ Set<IResource> resSet = resources.get(resourceBundle);
+
+ if (resSet != null) {
+ for (IResource resource : resSet) {
+ Locale refLoc = getLocaleByName(resourceBundle,
+ resource.getName());
+ if (refLoc == null
+ && l == null
+ || (refLoc != null && refLoc.equals(l) || l != null
+ && l.equals(refLoc))) {
+ res = resource.getProject().getFile(
+ resource.getProjectRelativePath());
+ break;
+ }
+ }
+ }
+
+ return res;
+ }
+
+ public Set<IResource> getAllResourceBundleResources(String resourceBundle) {
+ return allBundles.get(resourceBundle);
+ }
+
+ public void registerResourceExclusionListener(
+ IResourceExclusionListener listener) {
+ exclusionListeners.add(listener);
+ }
+
+ public void unregisterResourceExclusionListener(
+ IResourceExclusionListener listener) {
+ exclusionListeners.remove(listener);
+ }
+
+ public boolean isResourceExclusionListenerRegistered(
+ IResourceExclusionListener listener) {
+ return exclusionListeners.contains(listener);
+ }
+
+ public static void unregisterResourceExclusionListenerFromAllManagers(
+ IResourceExclusionListener excludedResource) {
+ for (ResourceBundleManager mgr : rbmanager.values()) {
+ mgr.unregisterResourceExclusionListener(excludedResource);
+ }
+ }
+
+ public void addResourceBundleEntry(String resourceBundleId, String key,
+ Locale locale, String message) throws ResourceBundleException {
+
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup bundleGroup = instance
+ .getMessagesBundleGroup(resourceBundleId);
+ IMessage entry = bundleGroup.getMessage(key, locale);
+
+ if (entry == null) {
+ DirtyHack.setFireEnabled(false);
+
+ IMessagesBundle messagesBundle = bundleGroup
+ .getMessagesBundle(locale);
+ IMessage m = MessageFactory.createMessage(key, locale);
+ m.setText(message);
+ messagesBundle.addMessage(m);
+
+ instance.writeToFile(messagesBundle);
+
+ DirtyHack.setFireEnabled(true);
+
+ // notify the PropertyKeySelectionTree
+ instance.fireEditorChanged();
+ }
+ }
+
+ public void saveResourceBundle(String resourceBundleId,
+ IMessagesBundleGroup newBundleGroup) throws ResourceBundleException {
+
+ // RBManager.getInstance().
+ }
+
+ public void removeResourceBundleEntry(String resourceBundleId,
+ List<String> keys) throws ResourceBundleException {
+
+ RBManager instance = RBManager.getInstance(project);
+ IMessagesBundleGroup messagesBundleGroup = instance
+ .getMessagesBundleGroup(resourceBundleId);
+
+ DirtyHack.setFireEnabled(false);
+
+ for (String key : keys) {
+ messagesBundleGroup.removeMessages(key);
+ }
+
+ instance.writeToFile(messagesBundleGroup);
+
+ DirtyHack.setFireEnabled(true);
+
+ // notify the PropertyKeySelectionTree
+ instance.fireEditorChanged();
+ }
+
+ public boolean isResourceExisting(String bundleId, String key) {
+ boolean keyExists = false;
+ IMessagesBundleGroup bGroup = getResourceBundle(bundleId);
+
+ if (bGroup != null) {
+ keyExists = bGroup.isKey(key);
+ }
+
+ return keyExists;
+ }
+
+ public static void refreshResource(IResource resource) {
+ (new I18nBuilder()).buildProject(null, resource.getProject());
+ (new I18nBuilder()).buildResource(resource, null);
+ }
+
+ public Set<Locale> getProjectProvidedLocales() {
+ Set<Locale> locales = new HashSet<Locale>();
+
+ for (String bundleId : getResourceBundleNames()) {
+ Set<Locale> rb_l = getProvidedLocales(bundleId);
+ if (!rb_l.isEmpty()) {
+ Object[] bundlelocales = rb_l.toArray();
+ for (Object l : bundlelocales) {
+ /* TODO check if useful to add the default */
+ if (!locales.contains(l))
+ locales.add((Locale) l);
+ }
+ }
+ }
+ return locales;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
index a1246a3d..8b3e7020 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
@@ -1,22 +1,29 @@
-package org.eclipse.babel.tapiji.tools.core.model.manager;
-
-import java.util.Collection;
-
-public class ResourceExclusionEvent {
-
- private Collection<Object> changedResources;
-
- public ResourceExclusionEvent(Collection<Object> changedResources) {
- super();
- this.changedResources = changedResources;
- }
-
- public void setChangedResources(Collection<Object> changedResources) {
- this.changedResources = changedResources;
- }
-
- public Collection<Object> getChangedResources() {
- return changedResources;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.manager;
+
+import java.util.Collection;
+
+public class ResourceExclusionEvent {
+
+ private Collection<Object> changedResources;
+
+ public ResourceExclusionEvent(Collection<Object> changedResources) {
+ super();
+ this.changedResources = changedResources;
+ }
+
+ public void setChangedResources(Collection<Object> changedResources) {
+ this.changedResources = changedResources;
+ }
+
+ public Collection<Object> getChangedResources() {
+ return changedResources;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/CheckItem.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/CheckItem.java
index b38193b5..0b340de1 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/CheckItem.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/CheckItem.java
@@ -1,34 +1,41 @@
-package org.eclipse.babel.tapiji.tools.core.model.preferences;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-
-public class CheckItem{
- boolean checked;
- String name;
-
- public CheckItem(String item, boolean checked) {
- this.name = item;
- this.checked = checked;
- }
-
- public String getName() {
- return name;
- }
-
- public boolean getChecked() {
- return checked;
- }
-
- public TableItem toTableItem(Table table){
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(name);
- item.setChecked(checked);
- return item;
- }
-
- public boolean equals(CheckItem item){
- return name.equals(item.getName());
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.preferences;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+
+public class CheckItem{
+ boolean checked;
+ String name;
+
+ public CheckItem(String item, boolean checked) {
+ this.name = item;
+ this.checked = checked;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean getChecked() {
+ return checked;
+ }
+
+ public TableItem toTableItem(Table table){
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(name);
+ item.setChecked(checked);
+ return item;
+ }
+
+ public boolean equals(CheckItem item){
+ return name.equals(item.getName());
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java
index cbc2089a..6056a468 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferenceInitializer.java
@@ -1,35 +1,42 @@
-package org.eclipse.babel.tapiji.tools.core.model.preferences;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.jface.preference.IPreferenceStore;
-
-public class TapiJIPreferenceInitializer extends AbstractPreferenceInitializer {
-
- public TapiJIPreferenceInitializer() {
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
-
- //ResourceBundle-Settings
- List<CheckItem> patterns = new LinkedList<CheckItem>();
- patterns.add(new CheckItem("^(.)*/build\\.properties", true));
- patterns.add(new CheckItem("^(.)*/config\\.properties", true));
- patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true));
- prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN, TapiJIPreferences.convertListToString(patterns));
-
- // Builder
- prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_RB, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true);
- prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false);
- prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.preferences;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
+import org.eclipse.jface.preference.IPreferenceStore;
+
+public class TapiJIPreferenceInitializer extends AbstractPreferenceInitializer {
+
+ public TapiJIPreferenceInitializer() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public void initializeDefaultPreferences() {
+ IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
+
+ //ResourceBundle-Settings
+ List<CheckItem> patterns = new LinkedList<CheckItem>();
+ patterns.add(new CheckItem("^(.)*/build\\.properties", true));
+ patterns.add(new CheckItem("^(.)*/config\\.properties", true));
+ patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true));
+ prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN, TapiJIPreferences.convertListToString(patterns));
+
+ // Builder
+ prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_RB, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true);
+ prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false);
+ prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferences.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferences.java
index 49e6c7fd..661eb86d 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferences.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/preferences/TapiJIPreferences.java
@@ -1,102 +1,109 @@
-package org.eclipse.babel.tapiji.tools.core.model.preferences;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.eclipse.babel.core.configuration.IConfiguration;
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-
-public class TapiJIPreferences implements IConfiguration {
-
- public static final String AUDIT_SAME_VALUE = "auditSameValue";
- public static final String AUDIT_UNSPEZIFIED_KEY = "auditMissingValue";
- public static final String AUDIT_MISSING_LANGUAGE = "auditMissingLanguage";
- public static final String AUDIT_RB = "auditResourceBundle";
- public static final String AUDIT_RESOURCE = "auditResource";
-
- public static final String NON_RB_PATTERN = "NoRBPattern";
-
- private static final IPreferenceStore PREF = Activator.getDefault().getPreferenceStore();
-
- private static final String DELIMITER = ";";
- private static final String ATTRIBUTE_DELIMITER = ":";
-
- public boolean getAuditSameValue() {
- return PREF.getBoolean(AUDIT_SAME_VALUE);
- }
-
-
- public boolean getAuditMissingValue() {
- return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY);
- }
-
-
- public boolean getAuditMissingLanguage() {
- return PREF.getBoolean(AUDIT_MISSING_LANGUAGE);
- }
-
-
- public boolean getAuditRb() {
- return PREF.getBoolean(AUDIT_RB);
- }
-
-
- public boolean getAuditResource() {
- return PREF.getBoolean(AUDIT_RESOURCE);
- }
-
- public String getNonRbPattern() {
- return PREF.getString(NON_RB_PATTERN);
- }
-
- public static List<CheckItem> getNonRbPatternAsList() {
- return convertStringToList(PREF.getString(NON_RB_PATTERN));
- }
-
- public static List<CheckItem> convertStringToList(String string) {
- StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER);
- int tokenCount = tokenizer.countTokens();
- List<CheckItem> elements = new LinkedList<CheckItem>();
-
- for (int i = 0; i < tokenCount; i++) {
- StringTokenizer attribute = new StringTokenizer(tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
- String name = attribute.nextToken();
- boolean checked;
- if (attribute.nextToken().equals("true")) checked = true;
- else checked = false;
-
- elements.add(new CheckItem(name, checked));
- }
- return elements;
- }
-
-
- public static String convertListToString(List<CheckItem> patterns) {
- StringBuilder sb = new StringBuilder();
- int tokenCount = 0;
-
- for (CheckItem s : patterns){
- sb.append(s.getName());
- sb.append(ATTRIBUTE_DELIMITER);
- if(s.checked) sb.append("true");
- else sb.append("false");
-
- if (++tokenCount!=patterns.size())
- sb.append(DELIMITER);
- }
- return sb.toString();
- }
-
-
- public static void addPropertyChangeListener(IPropertyChangeListener listener){
- Activator.getDefault().getPreferenceStore().addPropertyChangeListener(listener);
- }
-
-
- public static void removePropertyChangeListener(IPropertyChangeListener listener) {
- Activator.getDefault().getPreferenceStore().removePropertyChangeListener(listener);
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.preferences;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.eclipse.babel.core.configuration.IConfiguration;
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.util.IPropertyChangeListener;
+
+public class TapiJIPreferences implements IConfiguration {
+
+ public static final String AUDIT_SAME_VALUE = "auditSameValue";
+ public static final String AUDIT_UNSPEZIFIED_KEY = "auditMissingValue";
+ public static final String AUDIT_MISSING_LANGUAGE = "auditMissingLanguage";
+ public static final String AUDIT_RB = "auditResourceBundle";
+ public static final String AUDIT_RESOURCE = "auditResource";
+
+ public static final String NON_RB_PATTERN = "NoRBPattern";
+
+ private static final IPreferenceStore PREF = Activator.getDefault().getPreferenceStore();
+
+ private static final String DELIMITER = ";";
+ private static final String ATTRIBUTE_DELIMITER = ":";
+
+ public boolean getAuditSameValue() {
+ return PREF.getBoolean(AUDIT_SAME_VALUE);
+ }
+
+
+ public boolean getAuditMissingValue() {
+ return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY);
+ }
+
+
+ public boolean getAuditMissingLanguage() {
+ return PREF.getBoolean(AUDIT_MISSING_LANGUAGE);
+ }
+
+
+ public boolean getAuditRb() {
+ return PREF.getBoolean(AUDIT_RB);
+ }
+
+
+ public boolean getAuditResource() {
+ return PREF.getBoolean(AUDIT_RESOURCE);
+ }
+
+ public String getNonRbPattern() {
+ return PREF.getString(NON_RB_PATTERN);
+ }
+
+ public static List<CheckItem> getNonRbPatternAsList() {
+ return convertStringToList(PREF.getString(NON_RB_PATTERN));
+ }
+
+ public static List<CheckItem> convertStringToList(String string) {
+ StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER);
+ int tokenCount = tokenizer.countTokens();
+ List<CheckItem> elements = new LinkedList<CheckItem>();
+
+ for (int i = 0; i < tokenCount; i++) {
+ StringTokenizer attribute = new StringTokenizer(tokenizer.nextToken(), ATTRIBUTE_DELIMITER);
+ String name = attribute.nextToken();
+ boolean checked;
+ if (attribute.nextToken().equals("true")) checked = true;
+ else checked = false;
+
+ elements.add(new CheckItem(name, checked));
+ }
+ return elements;
+ }
+
+
+ public static String convertListToString(List<CheckItem> patterns) {
+ StringBuilder sb = new StringBuilder();
+ int tokenCount = 0;
+
+ for (CheckItem s : patterns){
+ sb.append(s.getName());
+ sb.append(ATTRIBUTE_DELIMITER);
+ if(s.checked) sb.append("true");
+ else sb.append("false");
+
+ if (++tokenCount!=patterns.size())
+ sb.append(DELIMITER);
+ }
+ return sb.toString();
+ }
+
+
+ public static void addPropertyChangeListener(IPropertyChangeListener listener){
+ Activator.getDefault().getPreferenceStore().addPropertyChangeListener(listener);
+ }
+
+
+ public static void removePropertyChangeListener(IPropertyChangeListener listener) {
+ Activator.getDefault().getPreferenceStore().removePropertyChangeListener(listener);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/MessagesViewState.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/MessagesViewState.java
index 434a6902..7b04b59c 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/MessagesViewState.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/MessagesViewState.java
@@ -1,205 +1,212 @@
-package org.eclipse.babel.tapiji.tools.core.model.view;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-
-public class MessagesViewState {
-
- private static final String TAG_VISIBLE_LOCALES = "visible_locales";
- private static final String TAG_LOCALE = "locale";
- private static final String TAG_LOCALE_LANGUAGE = "language";
- private static final String TAG_LOCALE_COUNTRY = "country";
- private static final String TAG_LOCALE_VARIANT = "variant";
- private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
- private static final String TAG_MATCHING_PRECISION= "matching_precision";
- private static final String TAG_SELECTED_PROJECT = "selected_project";
- private static final String TAG_SELECTED_BUNDLE = "selected_bundle";
- private static final String TAG_ENABLED = "enabled";
- private static final String TAG_VALUE = "value";
- private static final String TAG_SEARCH_STRING = "search_string";
- private static final String TAG_EDITABLE = "editable";
-
- private List<Locale> visibleLocales;
- private SortInfo sortings;
- private boolean fuzzyMatchingEnabled;
- private float matchingPrecision = .75f;
- private String selectedProjectName;
- private String selectedBundleId;
- private String searchString;
- private boolean editable;
-
- public void saveState (IMemento memento) {
- try {
- if (memento == null)
- return;
-
- if (visibleLocales != null) {
- IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES);
- for (Locale loc : visibleLocales) {
- IMemento memLoc = memVL.createChild(TAG_LOCALE);
- memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage());
- memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry());
- memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant());
- }
- }
-
- if (sortings != null) {
- sortings.saveState(memento);
- }
-
- IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
- memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
-
- IMemento memMatchingPrec = memento.createChild(TAG_MATCHING_PRECISION);
- memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
-
- selectedProjectName = selectedProjectName != null ? selectedProjectName : "";
- selectedBundleId = selectedBundleId != null ? selectedBundleId : "";
-
- IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT);
- memSP.putString(TAG_VALUE, selectedProjectName);
-
- IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE);
- memSB.putString(TAG_VALUE, selectedBundleId);
-
- IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
- memSStr.putString(TAG_VALUE, searchString);
-
- IMemento memEditable = memento.createChild(TAG_EDITABLE);
- memEditable.putBoolean(TAG_ENABLED, editable);
- } catch (Exception e) {
-
- }
- }
-
- public void init (IMemento memento) {
- if (memento == null)
- return;
-
-
- if (memento.getChild(TAG_VISIBLE_LOCALES) != null) {
- if (visibleLocales == null)
- visibleLocales = new ArrayList<Locale>();
- IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES).getChildren(TAG_LOCALE);
- for (IMemento mLocale : mLocales) {
- if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null && mLocale.getString(TAG_LOCALE_COUNTRY) == null
- && mLocale.getString(TAG_LOCALE_VARIANT) == null) {
- continue;
- }
- Locale newLocale = new Locale (
- mLocale.getString(TAG_LOCALE_LANGUAGE),
- mLocale.getString(TAG_LOCALE_COUNTRY),
- mLocale.getString(TAG_LOCALE_VARIANT));
- if (!this.visibleLocales.contains(newLocale)) {
- visibleLocales.add(newLocale);
- }
- }
- }
-
- if (sortings == null)
- sortings = new SortInfo();
- sortings.init(memento);
-
- IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
- if (mFuzzyMatching != null)
- fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
-
- IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
- if (mMP != null)
- matchingPrecision = mMP.getFloat(TAG_VALUE);
-
- IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT);
- if (mSelProj != null)
- selectedProjectName = mSelProj.getString(TAG_VALUE);
-
- IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE);
- if (mSelBundle != null)
- selectedBundleId = mSelBundle.getString(TAG_VALUE);
-
- IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
- if (mSStr != null)
- searchString = mSStr.getString(TAG_VALUE);
-
- IMemento mEditable = memento.getChild(TAG_EDITABLE);
- if (mEditable != null)
- editable = mEditable.getBoolean(TAG_ENABLED);
- }
-
- public MessagesViewState(List<Locale> visibleLocales,
- SortInfo sortings, boolean fuzzyMatchingEnabled,
- String selectedBundleId) {
- super();
- this.visibleLocales = visibleLocales;
- this.sortings = sortings;
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- this.selectedBundleId = selectedBundleId;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
- }
-
- public SortInfo getSortings() {
- return sortings;
- }
-
- public void setSortings(SortInfo sortings) {
- this.sortings = sortings;
- }
-
- public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
- }
-
- public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- }
-
- public void setSelectedBundleId(String selectedBundleId) {
- this.selectedBundleId = selectedBundleId;
- }
-
- public void setSelectedProjectName(String selectedProjectName) {
- this.selectedProjectName = selectedProjectName;
- }
-
- public void setSearchString(String searchString) {
- this.searchString = searchString;
- }
-
- public String getSelectedBundleId() {
- return selectedBundleId;
- }
-
- public String getSelectedProjectName() {
- return selectedProjectName;
- }
-
- public String getSearchString() {
- return searchString;
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- public void setMatchingPrecision (float value) {
- this.matchingPrecision = value;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.view;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.ui.IMemento;
+
+public class MessagesViewState {
+
+ private static final String TAG_VISIBLE_LOCALES = "visible_locales";
+ private static final String TAG_LOCALE = "locale";
+ private static final String TAG_LOCALE_LANGUAGE = "language";
+ private static final String TAG_LOCALE_COUNTRY = "country";
+ private static final String TAG_LOCALE_VARIANT = "variant";
+ private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
+ private static final String TAG_MATCHING_PRECISION= "matching_precision";
+ private static final String TAG_SELECTED_PROJECT = "selected_project";
+ private static final String TAG_SELECTED_BUNDLE = "selected_bundle";
+ private static final String TAG_ENABLED = "enabled";
+ private static final String TAG_VALUE = "value";
+ private static final String TAG_SEARCH_STRING = "search_string";
+ private static final String TAG_EDITABLE = "editable";
+
+ private List<Locale> visibleLocales;
+ private SortInfo sortings;
+ private boolean fuzzyMatchingEnabled;
+ private float matchingPrecision = .75f;
+ private String selectedProjectName;
+ private String selectedBundleId;
+ private String searchString;
+ private boolean editable;
+
+ public void saveState (IMemento memento) {
+ try {
+ if (memento == null)
+ return;
+
+ if (visibleLocales != null) {
+ IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES);
+ for (Locale loc : visibleLocales) {
+ IMemento memLoc = memVL.createChild(TAG_LOCALE);
+ memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage());
+ memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry());
+ memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant());
+ }
+ }
+
+ if (sortings != null) {
+ sortings.saveState(memento);
+ }
+
+ IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
+ memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
+
+ IMemento memMatchingPrec = memento.createChild(TAG_MATCHING_PRECISION);
+ memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
+
+ selectedProjectName = selectedProjectName != null ? selectedProjectName : "";
+ selectedBundleId = selectedBundleId != null ? selectedBundleId : "";
+
+ IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT);
+ memSP.putString(TAG_VALUE, selectedProjectName);
+
+ IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE);
+ memSB.putString(TAG_VALUE, selectedBundleId);
+
+ IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
+ memSStr.putString(TAG_VALUE, searchString);
+
+ IMemento memEditable = memento.createChild(TAG_EDITABLE);
+ memEditable.putBoolean(TAG_ENABLED, editable);
+ } catch (Exception e) {
+
+ }
+ }
+
+ public void init (IMemento memento) {
+ if (memento == null)
+ return;
+
+
+ if (memento.getChild(TAG_VISIBLE_LOCALES) != null) {
+ if (visibleLocales == null)
+ visibleLocales = new ArrayList<Locale>();
+ IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES).getChildren(TAG_LOCALE);
+ for (IMemento mLocale : mLocales) {
+ if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null && mLocale.getString(TAG_LOCALE_COUNTRY) == null
+ && mLocale.getString(TAG_LOCALE_VARIANT) == null) {
+ continue;
+ }
+ Locale newLocale = new Locale (
+ mLocale.getString(TAG_LOCALE_LANGUAGE),
+ mLocale.getString(TAG_LOCALE_COUNTRY),
+ mLocale.getString(TAG_LOCALE_VARIANT));
+ if (!this.visibleLocales.contains(newLocale)) {
+ visibleLocales.add(newLocale);
+ }
+ }
+ }
+
+ if (sortings == null)
+ sortings = new SortInfo();
+ sortings.init(memento);
+
+ IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
+ if (mFuzzyMatching != null)
+ fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
+
+ IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
+ if (mMP != null)
+ matchingPrecision = mMP.getFloat(TAG_VALUE);
+
+ IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT);
+ if (mSelProj != null)
+ selectedProjectName = mSelProj.getString(TAG_VALUE);
+
+ IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE);
+ if (mSelBundle != null)
+ selectedBundleId = mSelBundle.getString(TAG_VALUE);
+
+ IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
+ if (mSStr != null)
+ searchString = mSStr.getString(TAG_VALUE);
+
+ IMemento mEditable = memento.getChild(TAG_EDITABLE);
+ if (mEditable != null)
+ editable = mEditable.getBoolean(TAG_ENABLED);
+ }
+
+ public MessagesViewState(List<Locale> visibleLocales,
+ SortInfo sortings, boolean fuzzyMatchingEnabled,
+ String selectedBundleId) {
+ super();
+ this.visibleLocales = visibleLocales;
+ this.sortings = sortings;
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ this.selectedBundleId = selectedBundleId;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public void setVisibleLocales(List<Locale> visibleLocales) {
+ this.visibleLocales = visibleLocales;
+ }
+
+ public SortInfo getSortings() {
+ return sortings;
+ }
+
+ public void setSortings(SortInfo sortings) {
+ this.sortings = sortings;
+ }
+
+ public boolean isFuzzyMatchingEnabled() {
+ return fuzzyMatchingEnabled;
+ }
+
+ public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ }
+
+ public void setSelectedBundleId(String selectedBundleId) {
+ this.selectedBundleId = selectedBundleId;
+ }
+
+ public void setSelectedProjectName(String selectedProjectName) {
+ this.selectedProjectName = selectedProjectName;
+ }
+
+ public void setSearchString(String searchString) {
+ this.searchString = searchString;
+ }
+
+ public String getSelectedBundleId() {
+ return selectedBundleId;
+ }
+
+ public String getSelectedProjectName() {
+ return selectedProjectName;
+ }
+
+ public String getSearchString() {
+ return searchString;
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ public void setMatchingPrecision (float value) {
+ this.matchingPrecision = value;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/SortInfo.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/SortInfo.java
index 3db0c882..0c55cf07 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/SortInfo.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/view/SortInfo.java
@@ -1,56 +1,63 @@
-package org.eclipse.babel.tapiji.tools.core.model.view;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-
-
-public class SortInfo {
-
- public static final String TAG_SORT_INFO = "sort_info";
- public static final String TAG_COLUMN_INDEX = "col_idx";
- public static final String TAG_ORDER = "order";
-
- private int colIdx;
- private boolean DESC;
- private List<Locale> visibleLocales;
-
- public void setDESC(boolean dESC) {
- DESC = dESC;
- }
-
- public boolean isDESC() {
- return DESC;
- }
-
- public void setColIdx(int colIdx) {
- this.colIdx = colIdx;
- }
-
- public int getColIdx() {
- return colIdx;
- }
-
- public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public void saveState (IMemento memento) {
- IMemento mCI = memento.createChild(TAG_SORT_INFO);
- mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
- mCI.putBoolean(TAG_ORDER, DESC);
- }
-
- public void init (IMemento memento) {
- IMemento mCI = memento.getChild(TAG_SORT_INFO);
- if (mCI == null)
- return;
- colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
- DESC = mCI.getBoolean(TAG_ORDER);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.model.view;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.ui.IMemento;
+
+
+public class SortInfo {
+
+ public static final String TAG_SORT_INFO = "sort_info";
+ public static final String TAG_COLUMN_INDEX = "col_idx";
+ public static final String TAG_ORDER = "order";
+
+ private int colIdx;
+ private boolean DESC;
+ private List<Locale> visibleLocales;
+
+ public void setDESC(boolean dESC) {
+ DESC = dESC;
+ }
+
+ public boolean isDESC() {
+ return DESC;
+ }
+
+ public void setColIdx(int colIdx) {
+ this.colIdx = colIdx;
+ }
+
+ public int getColIdx() {
+ return colIdx;
+ }
+
+ public void setVisibleLocales(List<Locale> visibleLocales) {
+ this.visibleLocales = visibleLocales;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public void saveState (IMemento memento) {
+ IMemento mCI = memento.createChild(TAG_SORT_INFO);
+ mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
+ mCI.putBoolean(TAG_ORDER, DESC);
+ }
+
+ public void init (IMemento memento) {
+ IMemento mCI = memento.getChild(TAG_SORT_INFO);
+ if (mCI == null)
+ return;
+ colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
+ DESC = mCI.getBoolean(TAG_ORDER);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java
index 6bc0ba52..dce8cebb 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java
@@ -1,201 +1,208 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import java.text.MessageFormat;
-import java.util.Iterator;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesEditor;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
-import org.eclipse.ui.texteditor.SimpleMarkerAnnotation;
-
-
-public class EditorUtils {
-
- /** Marker constants **/
- public static final String MARKER_ID = Activator.PLUGIN_ID
- + ".StringLiteralAuditMarker";
- public static final String RB_MARKER_ID = Activator.PLUGIN_ID + ".ResourceBundleAuditMarker";
-
- /** Error messages **/
- public static final String MESSAGE_NON_LOCALIZED_LITERAL = "Non-localized string literal ''{0}'' has been found";
- public static final String MESSAGE_BROKEN_RESOURCE_REFERENCE = "Cannot find the key ''{0}'' within the resource-bundle ''{1}''";
- public static final String MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE = "The resource bundle with id ''{0}'' cannot be found";
-
- public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''";
- public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''";
- public static final String MESSAGE_MISSING_LANGUAGE = "ResourceBundle ''{0}'' lacks a translation for ''{1}''";
-
- /** Editor ids **/
- public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
-
- public static String getFormattedMessage (String pattern, Object[] arguments) {
- String formattedMessage = "";
-
- MessageFormat formatter = new MessageFormat(pattern);
- formattedMessage = formatter.format(arguments);
-
- return formattedMessage;
- }
-
- public static IEditorPart openEditor (IWorkbenchPage page, IFile file, String editor) {
- // open the rb-editor for this file type
- try {
- return IDE.openEditor(page, file, editor);
- } catch (PartInitException e) {
- Logger.logError(e);
- }
- return null;
- }
-
- public static IEditorPart openEditor (IWorkbenchPage page, IFile file, String editor, String key) {
- // open the rb-editor for this file type and selects given msg key
- IEditorPart part = openEditor(page, file, editor);
- if (part instanceof IMessagesEditor) {
- IMessagesEditor msgEditor = (IMessagesEditor) part;
- msgEditor.setSelectedKey(key);
- }
- return part;
- }
-
- public static void reportToMarker(String string, ILocation problem, int cause, String key, ILocation data, String context) {
- try {
- IMarker marker = problem.getFile().createMarker(MARKER_ID);
- marker.setAttribute(IMarker.MESSAGE, string);
- marker.setAttribute(IMarker.CHAR_START, problem.getStartPos());
- marker.setAttribute(IMarker.CHAR_END, problem.getEndPos());
- marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
- marker.setAttribute("cause", cause);
- marker.setAttribute("key", key);
- marker.setAttribute("context", context);
- if (data != null) {
- marker.setAttribute("bundleName", data.getLiteral());
- marker.setAttribute("bundleStart", data.getStartPos());
- marker.setAttribute("bundleEnd", data.getEndPos());
- }
-
- // TODO: init attributes
- marker.setAttribute("stringLiteral", string);
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- Logger.logInfo(string);
- }
-
- public static void reportToRBMarker(String string, ILocation problem, int cause, String key, String problemPartnerFile, ILocation data, String context) {
- try {
- if (!problem.getFile().exists()) return;
- IMarker marker = problem.getFile().createMarker(RB_MARKER_ID);
- marker.setAttribute(IMarker.MESSAGE, string);
- marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); //TODO better-dirty implementation
- marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
- marker.setAttribute("cause", cause);
- marker.setAttribute("key", key);
- marker.setAttribute("context", context);
- if (data != null) {
- marker.setAttribute("language", data.getLiteral());
- marker.setAttribute("bundleLine", data.getStartPos());
- }
- marker.setAttribute("stringLiteral", string);
- marker.setAttribute("problemPartner", problemPartnerFile);
- } catch (CoreException e) {
- Logger.logError(e);
- return;
- }
-
- Logger.logInfo(string);
- }
-
- public static boolean deleteAuditMarkersForResource(IResource resource) {
- try {
- if (resource != null && resource.exists()) {
- resource.deleteMarkers(MARKER_ID, false, IResource.DEPTH_INFINITE);
- deleteAllAuditRBMarkersFromRB(resource);
- }
- } catch (CoreException e) {
- Logger.logError(e);
- return false;
- }
- return true;
- }
-
- /*
- * Delete all RB_MARKER from the hole resourcebundle
- */
- private static boolean deleteAllAuditRBMarkersFromRB(IResource resource) throws CoreException{
-// if (resource.findMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE).length > 0)
- if (RBFileUtils.isResourceBundleFile(resource)){
- String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile)resource);
- if (rbId==null) return true; //file in no resourcebundle
-
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(resource.getProject());
- for(IResource r : rbmanager.getResourceBundles(rbId))
- r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
- }
- return true;
- }
-
- public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add){
- IMarker[] old_ms = ms;
- ms = new IMarker[old_ms.length + ms_to_add.length];
-
- System.arraycopy(old_ms, 0, ms, 0, old_ms.length);
- System.arraycopy(ms_to_add, 0, ms, old_ms.length, ms_to_add.length);
-
- return ms;
- }
-
- public static void updateMarker(IMarker marker) {
- FileEditorInput input = new FileEditorInput(
- (IFile) marker.getResource());
-
- AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel)
- getAnnotationModel(marker);
- IDocument doc = JavaUI.getDocumentProvider().getDocument(input);
-
- try {
- model.updateMarker(doc, marker, getCurPosition(marker, model));
- } catch (CoreException e) {
- Logger.logError(e);
- }
- }
-
- public static IAnnotationModel getAnnotationModel(IMarker marker) {
- FileEditorInput input = new FileEditorInput(
- (IFile) marker.getResource());
-
- return JavaUI.getDocumentProvider().getAnnotationModel(input);
- }
-
- private static Position getCurPosition(IMarker marker, IAnnotationModel model) {
- Iterator iter = model.getAnnotationIterator();
- Logger.logInfo("Updates Position!");
- while (iter.hasNext()) {
- Object curr = iter.next();
- if (curr instanceof SimpleMarkerAnnotation) {
- SimpleMarkerAnnotation annot = (SimpleMarkerAnnotation) curr;
- if (marker.equals(annot.getMarker())) {
- return model.getPosition(annot);
- }
- }
- }
- return null;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.text.MessageFormat;
+import java.util.Iterator;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesEditor;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jdt.ui.JavaUI;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.Position;
+import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.ide.IDE;
+import org.eclipse.ui.part.FileEditorInput;
+import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
+import org.eclipse.ui.texteditor.SimpleMarkerAnnotation;
+
+
+public class EditorUtils {
+
+ /** Marker constants **/
+ public static final String MARKER_ID = Activator.PLUGIN_ID
+ + ".StringLiteralAuditMarker";
+ public static final String RB_MARKER_ID = Activator.PLUGIN_ID + ".ResourceBundleAuditMarker";
+
+ /** Error messages **/
+ public static final String MESSAGE_NON_LOCALIZED_LITERAL = "Non-localized string literal ''{0}'' has been found";
+ public static final String MESSAGE_BROKEN_RESOURCE_REFERENCE = "Cannot find the key ''{0}'' within the resource-bundle ''{1}''";
+ public static final String MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE = "The resource bundle with id ''{0}'' cannot be found";
+
+ public static final String MESSAGE_UNSPECIFIED_KEYS = "Missing or unspecified key ''{0}'' has been found in ''{1}''";
+ public static final String MESSAGE_SAME_VALUE = "''{0}'' and ''{1}'' have the same translation for the key ''{2}''";
+ public static final String MESSAGE_MISSING_LANGUAGE = "ResourceBundle ''{0}'' lacks a translation for ''{1}''";
+
+ /** Editor ids **/
+ public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
+
+ public static String getFormattedMessage (String pattern, Object[] arguments) {
+ String formattedMessage = "";
+
+ MessageFormat formatter = new MessageFormat(pattern);
+ formattedMessage = formatter.format(arguments);
+
+ return formattedMessage;
+ }
+
+ public static IEditorPart openEditor (IWorkbenchPage page, IFile file, String editor) {
+ // open the rb-editor for this file type
+ try {
+ return IDE.openEditor(page, file, editor);
+ } catch (PartInitException e) {
+ Logger.logError(e);
+ }
+ return null;
+ }
+
+ public static IEditorPart openEditor (IWorkbenchPage page, IFile file, String editor, String key) {
+ // open the rb-editor for this file type and selects given msg key
+ IEditorPart part = openEditor(page, file, editor);
+ if (part instanceof IMessagesEditor) {
+ IMessagesEditor msgEditor = (IMessagesEditor) part;
+ msgEditor.setSelectedKey(key);
+ }
+ return part;
+ }
+
+ public static void reportToMarker(String string, ILocation problem, int cause, String key, ILocation data, String context) {
+ try {
+ IMarker marker = problem.getFile().createMarker(MARKER_ID);
+ marker.setAttribute(IMarker.MESSAGE, string);
+ marker.setAttribute(IMarker.CHAR_START, problem.getStartPos());
+ marker.setAttribute(IMarker.CHAR_END, problem.getEndPos());
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
+ marker.setAttribute("cause", cause);
+ marker.setAttribute("key", key);
+ marker.setAttribute("context", context);
+ if (data != null) {
+ marker.setAttribute("bundleName", data.getLiteral());
+ marker.setAttribute("bundleStart", data.getStartPos());
+ marker.setAttribute("bundleEnd", data.getEndPos());
+ }
+
+ // TODO: init attributes
+ marker.setAttribute("stringLiteral", string);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ Logger.logInfo(string);
+ }
+
+ public static void reportToRBMarker(String string, ILocation problem, int cause, String key, String problemPartnerFile, ILocation data, String context) {
+ try {
+ if (!problem.getFile().exists()) return;
+ IMarker marker = problem.getFile().createMarker(RB_MARKER_ID);
+ marker.setAttribute(IMarker.MESSAGE, string);
+ marker.setAttribute(IMarker.LINE_NUMBER, problem.getStartPos()); //TODO better-dirty implementation
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
+ marker.setAttribute("cause", cause);
+ marker.setAttribute("key", key);
+ marker.setAttribute("context", context);
+ if (data != null) {
+ marker.setAttribute("language", data.getLiteral());
+ marker.setAttribute("bundleLine", data.getStartPos());
+ }
+ marker.setAttribute("stringLiteral", string);
+ marker.setAttribute("problemPartner", problemPartnerFile);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return;
+ }
+
+ Logger.logInfo(string);
+ }
+
+ public static boolean deleteAuditMarkersForResource(IResource resource) {
+ try {
+ if (resource != null && resource.exists()) {
+ resource.deleteMarkers(MARKER_ID, false, IResource.DEPTH_INFINITE);
+ deleteAllAuditRBMarkersFromRB(resource);
+ }
+ } catch (CoreException e) {
+ Logger.logError(e);
+ return false;
+ }
+ return true;
+ }
+
+ /*
+ * Delete all RB_MARKER from the hole resourcebundle
+ */
+ private static boolean deleteAllAuditRBMarkersFromRB(IResource resource) throws CoreException{
+// if (resource.findMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE).length > 0)
+ if (RBFileUtils.isResourceBundleFile(resource)){
+ String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile)resource);
+ if (rbId==null) return true; //file in no resourcebundle
+
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(resource.getProject());
+ for(IResource r : rbmanager.getResourceBundles(rbId))
+ r.deleteMarkers(RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
+ }
+ return true;
+ }
+
+ public static IMarker[] concatMarkerArray(IMarker[] ms, IMarker[] ms_to_add){
+ IMarker[] old_ms = ms;
+ ms = new IMarker[old_ms.length + ms_to_add.length];
+
+ System.arraycopy(old_ms, 0, ms, 0, old_ms.length);
+ System.arraycopy(ms_to_add, 0, ms, old_ms.length, ms_to_add.length);
+
+ return ms;
+ }
+
+ public static void updateMarker(IMarker marker) {
+ FileEditorInput input = new FileEditorInput(
+ (IFile) marker.getResource());
+
+ AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel)
+ getAnnotationModel(marker);
+ IDocument doc = JavaUI.getDocumentProvider().getDocument(input);
+
+ try {
+ model.updateMarker(doc, marker, getCurPosition(marker, model));
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+ }
+
+ public static IAnnotationModel getAnnotationModel(IMarker marker) {
+ FileEditorInput input = new FileEditorInput(
+ (IFile) marker.getResource());
+
+ return JavaUI.getDocumentProvider().getAnnotationModel(input);
+ }
+
+ private static Position getCurPosition(IMarker marker, IAnnotationModel model) {
+ Iterator iter = model.getAnnotationIterator();
+ Logger.logInfo("Updates Position!");
+ while (iter.hasNext()) {
+ Object curr = iter.next();
+ if (curr instanceof SimpleMarkerAnnotation) {
+ SimpleMarkerAnnotation annot = (SimpleMarkerAnnotation) curr;
+ if (marker.equals(annot.getMarker())) {
+ return model.getPosition(annot);
+ }
+ }
+ }
+ return null;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
index bebe3d3b..20b5553f 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java
@@ -1,66 +1,73 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileReader;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.core.internal.resources.ResourceException;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.OperationCanceledException;
-
-
-public class FileUtils {
-
- public static String readFile (IResource resource) {
- return readFileAsString(resource.getRawLocation().toFile());
- }
-
- protected static String readFileAsString(File filePath) {
- String content = "";
-
- if (!filePath.exists()) return content;
- try {
- BufferedReader fileReader = new BufferedReader(new FileReader(filePath));
- String line = "";
-
- while ((line = fileReader.readLine()) != null) {
- content += line + "\n";
- }
-
- // close filereader
- fileReader.close();
- } catch (Exception e) {
- // TODO log error output
- Logger.logError(e);
- }
-
- return content;
- }
-
- public static File getRBManagerStateFile() {
- return Activator.getDefault().getStateLocation().append("internationalization.xml").toFile();
- }
-
- /**
- * Don't use that -> causes {@link ResourceException} -> because File out of sync
- * @param file
- * @param editorContent
- * @throws CoreException
- * @throws OperationCanceledException
- */
- public synchronized void saveTextFile(IFile file, String editorContent)
- throws CoreException, OperationCanceledException {
- try {
- file.setContents(new ByteArrayInputStream(editorContent.getBytes()),
- false, true, null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileReader;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.core.internal.resources.ResourceException;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.OperationCanceledException;
+
+
+public class FileUtils {
+
+ public static String readFile (IResource resource) {
+ return readFileAsString(resource.getRawLocation().toFile());
+ }
+
+ protected static String readFileAsString(File filePath) {
+ String content = "";
+
+ if (!filePath.exists()) return content;
+ try {
+ BufferedReader fileReader = new BufferedReader(new FileReader(filePath));
+ String line = "";
+
+ while ((line = fileReader.readLine()) != null) {
+ content += line + "\n";
+ }
+
+ // close filereader
+ fileReader.close();
+ } catch (Exception e) {
+ // TODO log error output
+ Logger.logError(e);
+ }
+
+ return content;
+ }
+
+ public static File getRBManagerStateFile() {
+ return Activator.getDefault().getStateLocation().append("internationalization.xml").toFile();
+ }
+
+ /**
+ * Don't use that -> causes {@link ResourceException} -> because File out of sync
+ * @param file
+ * @param editorContent
+ * @throws CoreException
+ * @throws OperationCanceledException
+ */
+ public synchronized void saveTextFile(IFile file, String editorContent)
+ throws CoreException, OperationCanceledException {
+ try {
+ file.setContents(new ByteArrayInputStream(editorContent.getBytes()),
+ false, true, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FontUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FontUtils.java
index f5fe4510..487bf8fe 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FontUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FontUtils.java
@@ -1,80 +1,87 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-
-
-public class FontUtils {
-
- /**
- * Gets a system color.
- * @param colorId SWT constant
- * @return system color
- */
- public static Color getSystemColor(int colorId) {
- return Activator.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
- }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
- }
-
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(int style) {
- return createFont(style, 0);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(int style, int relSize) {
- Display display = Activator.getDefault().getWorkbench().getDisplay();
- FontData[] fontData = display.getSystemFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(display, fontData);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+
+
+public class FontUtils {
+
+ /**
+ * Gets a system color.
+ * @param colorId SWT constant
+ * @return system color
+ */
+ public static Color getSystemColor(int colorId) {
+ return Activator.getDefault().getWorkbench()
+ .getDisplay().getSystemColor(colorId);
+ }
+
+ /**
+ * Creates a font by altering the font associated with the given control
+ * and applying the provided style (size is unaffected).
+ * @param control control we base our font data on
+ * @param style style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style) {
+ //TODO consider dropping in favor of control-less version?
+ return createFont(control, style, 0);
+ }
+
+
+ /**
+ * Creates a font by altering the font associated with the given control
+ * and applying the provided style and relative size.
+ * @param control control we base our font data on
+ * @param style style to apply to the new font
+ * @param relSize size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style, int relSize) {
+ //TODO consider dropping in favor of control-less version?
+ FontData[] fontData = control.getFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(control.getDisplay(), fontData);
+ }
+
+ /**
+ * Creates a font by altering the system font
+ * and applying the provided style and relative size.
+ * @param style style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(int style) {
+ return createFont(style, 0);
+ }
+
+ /**
+ * Creates a font by altering the system font
+ * and applying the provided style and relative size.
+ * @param style style to apply to the new font
+ * @param relSize size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(int style, int relSize) {
+ Display display = Activator.getDefault().getWorkbench().getDisplay();
+ FontData[] fontData = display.getSystemFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(display, fontData);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
index 7b157d9c..00daacf8 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java
@@ -1,35 +1,42 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import java.util.List;
-
-import org.eclipse.babel.core.util.PDEUtils;
-import org.eclipse.core.resources.IProject;
-
-public class FragmentProjectUtils{
-
- public static String getPluginId(IProject project){
- return PDEUtils.getPluginId(project);
- }
-
-
- public static IProject[] lookupFragment(IProject pluginProject){
- return PDEUtils.lookupFragment(pluginProject);
- }
-
- public static boolean isFragment(IProject pluginProject){
- return PDEUtils.isFragment(pluginProject);
- }
-
- public static List<IProject> getFragments(IProject hostProject){
- return PDEUtils.getFragments(hostProject);
- }
-
- public static String getFragmentId(IProject project, String hostPluginId){
- return PDEUtils.getFragmentId(project, hostPluginId);
- }
-
- public static IProject getFragmentHost(IProject fragment){
- return PDEUtils.getFragmentHost(fragment);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.util.List;
+
+import org.eclipse.babel.core.util.PDEUtils;
+import org.eclipse.core.resources.IProject;
+
+public class FragmentProjectUtils{
+
+ public static String getPluginId(IProject project){
+ return PDEUtils.getPluginId(project);
+ }
+
+
+ public static IProject[] lookupFragment(IProject pluginProject){
+ return PDEUtils.lookupFragment(pluginProject);
+ }
+
+ public static boolean isFragment(IProject pluginProject){
+ return PDEUtils.isFragment(pluginProject);
+ }
+
+ public static List<IProject> getFragments(IProject hostProject){
+ return PDEUtils.getFragments(hostProject);
+ }
+
+ public static String getFragmentId(IProject project, String hostPluginId){
+ return PDEUtils.getFragmentId(project, hostPluginId);
+ }
+
+ public static IProject getFragmentHost(IProject fragment){
+ return PDEUtils.getFragmentHost(fragment);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ImageUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ImageUtils.java
index b0dfa81a..91aa4402 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ImageUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ImageUtils.java
@@ -1,68 +1,75 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.graphics.Image;
-
-
-
-/**
- * Utility methods related to application UI.
- * @author Pascal Essiembre ([email protected])
- * @version $Author: nl_carnage $ $Revision: 1.12 $ $Date: 2007/09/11 16:11:10 $
- */
-public final class ImageUtils {
-
- /** Name of resource bundle image. */
- public static final String IMAGE_RESOURCE_BUNDLE =
- "icons/resourcebundle.gif"; //$NON-NLS-1$
- /** Name of properties file image. */
- public static final String IMAGE_PROPERTIES_FILE =
- "icons/propertiesfile.gif"; //$NON-NLS-1$
- /** Name of properties file entry image */
- public static final String IMAGE_PROPERTIES_FILE_ENTRY =
- "icons/key.gif";
- /** Name of new properties file image. */
- public static final String IMAGE_NEW_PROPERTIES_FILE =
- "icons/newpropertiesfile.gif"; //$NON-NLS-1$
- /** Name of hierarchical layout image. */
- public static final String IMAGE_LAYOUT_HIERARCHICAL =
- "icons/hierarchicalLayout.gif"; //$NON-NLS-1$
- /** Name of flat layout image. */
- public static final String IMAGE_LAYOUT_FLAT =
- "icons/flatLayout.gif"; //$NON-NLS-1$
- public static final String IMAGE_INCOMPLETE_ENTRIES =
- "icons/incomplete.gif"; //$NON-NLS-1$
- public static final String IMAGE_EXCLUDED_RESOURCE_ON =
- "icons/int.gif"; //$NON-NLS-1$
- public static final String IMAGE_EXCLUDED_RESOURCE_OFF =
- "icons/exclude.png"; //$NON-NLS-1$
- public static final String ICON_RESOURCE =
- "icons/Resource16_small.png";
- public static final String ICON_RESOURCE_INCOMPLETE =
- "icons/Resource16_warning_small.png";
-
- /** Image registry. */
- private static final ImageRegistry imageRegistry = new ImageRegistry();
-
- /**
- * Constructor.
- */
- private ImageUtils() {
- super();
- }
-
- /**
- * Gets an image.
- * @param imageName image name
- * @return image
- */
- public static Image getImage(String imageName) {
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- image = Activator.getImageDescriptor(imageName).createImage();
- imageRegistry.put(imageName, image);
- }
- return image;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+
+
+
+/**
+ * Utility methods related to application UI.
+ * @author Pascal Essiembre ([email protected])
+ * @version $Author: nl_carnage $ $Revision: 1.12 $ $Date: 2007/09/11 16:11:10 $
+ */
+public final class ImageUtils {
+
+ /** Name of resource bundle image. */
+ public static final String IMAGE_RESOURCE_BUNDLE =
+ "icons/resourcebundle.gif"; //$NON-NLS-1$
+ /** Name of properties file image. */
+ public static final String IMAGE_PROPERTIES_FILE =
+ "icons/propertiesfile.gif"; //$NON-NLS-1$
+ /** Name of properties file entry image */
+ public static final String IMAGE_PROPERTIES_FILE_ENTRY =
+ "icons/key.gif";
+ /** Name of new properties file image. */
+ public static final String IMAGE_NEW_PROPERTIES_FILE =
+ "icons/newpropertiesfile.gif"; //$NON-NLS-1$
+ /** Name of hierarchical layout image. */
+ public static final String IMAGE_LAYOUT_HIERARCHICAL =
+ "icons/hierarchicalLayout.gif"; //$NON-NLS-1$
+ /** Name of flat layout image. */
+ public static final String IMAGE_LAYOUT_FLAT =
+ "icons/flatLayout.gif"; //$NON-NLS-1$
+ public static final String IMAGE_INCOMPLETE_ENTRIES =
+ "icons/incomplete.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EXCLUDED_RESOURCE_ON =
+ "icons/int.gif"; //$NON-NLS-1$
+ public static final String IMAGE_EXCLUDED_RESOURCE_OFF =
+ "icons/exclude.png"; //$NON-NLS-1$
+ public static final String ICON_RESOURCE =
+ "icons/Resource16_small.png";
+ public static final String ICON_RESOURCE_INCOMPLETE =
+ "icons/Resource16_warning_small.png";
+
+ /** Image registry. */
+ private static final ImageRegistry imageRegistry = new ImageRegistry();
+
+ /**
+ * Constructor.
+ */
+ private ImageUtils() {
+ super();
+ }
+
+ /**
+ * Gets an image.
+ * @param imageName image name
+ * @return image
+ */
+ public static Image getImage(String imageName) {
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ image = Activator.getImageDescriptor(imageName).createImage();
+ imageRegistry.put(imageName, image);
+ }
+ return image;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LanguageUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LanguageUtils.java
index 9d111dc1..7628e8ad 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LanguageUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LanguageUtils.java
@@ -1,154 +1,161 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringBufferInputStream;
-import java.util.Locale;
-
-import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-
-
-public class LanguageUtils {
- private static final String INITIALISATION_STRING = PropertiesSerializer.GENERATED_BY;
-
-
- private static IFile createFile(IContainer container, String fileName, IProgressMonitor monitor) throws CoreException, IOException {
- if (!container.exists()){
- if (container instanceof IFolder){
- ((IFolder) container).create(false, false, monitor);
- }
- }
-
- IFile file = container.getFile(new Path(fileName));
- if (!file.exists()){
- InputStream s = new StringBufferInputStream(INITIALISATION_STRING);
- file.create(s, true, monitor);
- s.close();
- }
-
- return file;
- }
-
- /**
- * Checks if ResourceBundle provides a given locale. If the locale is not
- * provided, creates a new properties-file with the ResourceBundle-basename
- * and the index of the given locale.
- * @param project
- * @param rbId
- * @param locale
- */
- public static void addLanguageToResourceBundle(IProject project, final String rbId, final Locale locale){
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- if (rbManager.getProvidedLocales(rbId).contains(locale)) return;
-
- final IResource file = rbManager.getRandomFile(rbId);
- final IContainer c = ResourceUtils.getCorrespondingFolders(file.getParent(), project);
-
- new Job("create new propertfile") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- String newFilename = ResourceBundleManager.getResourceBundleName(file);
- if (locale.getLanguage() != null && !locale.getLanguage().equalsIgnoreCase(ResourceBundleManager.defaultLocaleTag)
- && !locale.getLanguage().equals(""))
- newFilename += "_"+locale.getLanguage();
- if (locale.getCountry() != null && !locale.getCountry().equals(""))
- newFilename += "_"+locale.getCountry();
- if (locale.getVariant() != null && !locale.getCountry().equals(""))
- newFilename += "_"+locale.getVariant();
- newFilename += ".properties";
-
- createFile(c, newFilename, monitor);
- } catch (CoreException e) {
- Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e);
- } catch (IOException e) {
- Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e);
- }
- monitor.done();
- return Status.OK_STATUS;
- }
- }.schedule();
- }
-
-
- /**
- * Adds new properties-files for a given locale to all ResourceBundles of a project.
- * If a ResourceBundle already contains the language, happens nothing.
- * @param project
- * @param locale
- */
- public static void addLanguageToProject(IProject project, Locale locale){
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- //Audit if all resourecbundles provide this locale. if not - add new file
- for (String rbId : rbManager.getResourceBundleIdentifiers()){
- addLanguageToResourceBundle(project, rbId, locale);
- }
- }
-
-
- private static void deleteFile(IFile file, boolean force, IProgressMonitor monitor) throws CoreException{
- EditorUtils.deleteAuditMarkersForResource(file);
- file.delete(force, monitor);
- }
-
- /**
- * Removes the properties-file of a given locale from a ResourceBundle, if
- * the ResourceBundle provides the locale.
- * @param project
- * @param rbId
- * @param locale
- */
- public static void removeFileFromResourceBundle(IProject project, String rbId, Locale locale) {
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- if (!rbManager.getProvidedLocales(rbId).contains(locale)) return;
-
- final IFile file = rbManager.getResourceBundleFile(rbId, locale);
- final String filename = file.getName();
-
- new Job("remove properties-file") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- deleteFile(file, true, monitor);
- } catch (CoreException e) {
-// MessageDialog.openError(Display.getCurrent().getActiveShell(), "Confirm", "File could not be deleted");
- Logger.logError("File could not be deleted",e);
- }
- return Status.OK_STATUS;
- }
- }.schedule();
- }
-
- /**
- * Removes all properties-files of a given locale from all ResourceBundles of a project.
- * @param rbManager
- * @param locale
- * @return
- */
- public static void removeLanguageFromProject(IProject project, Locale locale){
- ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
-
- for (String rbId : rbManager.getResourceBundleIdentifiers()){
- removeFileFromResourceBundle(project, rbId, locale);
- }
-
- }
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringBufferInputStream;
+import java.util.Locale;
+
+import org.eclipse.babel.core.message.resource.ser.PropertiesSerializer;
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+
+
+public class LanguageUtils {
+ private static final String INITIALISATION_STRING = PropertiesSerializer.GENERATED_BY;
+
+
+ private static IFile createFile(IContainer container, String fileName, IProgressMonitor monitor) throws CoreException, IOException {
+ if (!container.exists()){
+ if (container instanceof IFolder){
+ ((IFolder) container).create(false, false, monitor);
+ }
+ }
+
+ IFile file = container.getFile(new Path(fileName));
+ if (!file.exists()){
+ InputStream s = new StringBufferInputStream(INITIALISATION_STRING);
+ file.create(s, true, monitor);
+ s.close();
+ }
+
+ return file;
+ }
+
+ /**
+ * Checks if ResourceBundle provides a given locale. If the locale is not
+ * provided, creates a new properties-file with the ResourceBundle-basename
+ * and the index of the given locale.
+ * @param project
+ * @param rbId
+ * @param locale
+ */
+ public static void addLanguageToResourceBundle(IProject project, final String rbId, final Locale locale){
+ ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
+
+ if (rbManager.getProvidedLocales(rbId).contains(locale)) return;
+
+ final IResource file = rbManager.getRandomFile(rbId);
+ final IContainer c = ResourceUtils.getCorrespondingFolders(file.getParent(), project);
+
+ new Job("create new propertfile") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ String newFilename = ResourceBundleManager.getResourceBundleName(file);
+ if (locale.getLanguage() != null && !locale.getLanguage().equalsIgnoreCase(ResourceBundleManager.defaultLocaleTag)
+ && !locale.getLanguage().equals(""))
+ newFilename += "_"+locale.getLanguage();
+ if (locale.getCountry() != null && !locale.getCountry().equals(""))
+ newFilename += "_"+locale.getCountry();
+ if (locale.getVariant() != null && !locale.getCountry().equals(""))
+ newFilename += "_"+locale.getVariant();
+ newFilename += ".properties";
+
+ createFile(c, newFilename, monitor);
+ } catch (CoreException e) {
+ Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e);
+ } catch (IOException e) {
+ Logger.logError("File for locale "+locale+" could not be created in ResourceBundle "+rbId,e);
+ }
+ monitor.done();
+ return Status.OK_STATUS;
+ }
+ }.schedule();
+ }
+
+
+ /**
+ * Adds new properties-files for a given locale to all ResourceBundles of a project.
+ * If a ResourceBundle already contains the language, happens nothing.
+ * @param project
+ * @param locale
+ */
+ public static void addLanguageToProject(IProject project, Locale locale){
+ ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
+
+ //Audit if all resourecbundles provide this locale. if not - add new file
+ for (String rbId : rbManager.getResourceBundleIdentifiers()){
+ addLanguageToResourceBundle(project, rbId, locale);
+ }
+ }
+
+
+ private static void deleteFile(IFile file, boolean force, IProgressMonitor monitor) throws CoreException{
+ EditorUtils.deleteAuditMarkersForResource(file);
+ file.delete(force, monitor);
+ }
+
+ /**
+ * Removes the properties-file of a given locale from a ResourceBundle, if
+ * the ResourceBundle provides the locale.
+ * @param project
+ * @param rbId
+ * @param locale
+ */
+ public static void removeFileFromResourceBundle(IProject project, String rbId, Locale locale) {
+ ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
+
+ if (!rbManager.getProvidedLocales(rbId).contains(locale)) return;
+
+ final IFile file = rbManager.getResourceBundleFile(rbId, locale);
+ final String filename = file.getName();
+
+ new Job("remove properties-file") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ deleteFile(file, true, monitor);
+ } catch (CoreException e) {
+// MessageDialog.openError(Display.getCurrent().getActiveShell(), "Confirm", "File could not be deleted");
+ Logger.logError("File could not be deleted",e);
+ }
+ return Status.OK_STATUS;
+ }
+ }.schedule();
+ }
+
+ /**
+ * Removes all properties-files of a given locale from all ResourceBundles of a project.
+ * @param rbManager
+ * @param locale
+ * @return
+ */
+ public static void removeLanguageFromProject(IProject project, Locale locale){
+ ResourceBundleManager rbManager = ResourceBundleManager.getManager(project);
+
+ for (String rbId : rbManager.getResourceBundleIdentifiers()){
+ removeFileFromResourceBundle(project, rbId, locale);
+ }
+
+ }
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LocaleUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LocaleUtils.java
index e4bfe009..71d22de6 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LocaleUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/LocaleUtils.java
@@ -1,32 +1,39 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-
-public class LocaleUtils {
-
- public static Locale getLocaleByDisplayName (Set<Locale> locales, String displayName) {
- for (Locale l : locales) {
- String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
- if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) {
- return l;
- }
- }
-
- return null;
- }
-
- public static boolean containsLocaleByDisplayName(Set<Locale> locales, String displayName) {
- for (Locale l : locales) {
- String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
- if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) {
- return true;
- }
- }
-
- return false;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+
+public class LocaleUtils {
+
+ public static Locale getLocaleByDisplayName (Set<Locale> locales, String displayName) {
+ for (Locale l : locales) {
+ String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
+ if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) {
+ return l;
+ }
+ }
+
+ return null;
+ }
+
+ public static boolean containsLocaleByDisplayName(Set<Locale> locales, String displayName) {
+ for (Locale l : locales) {
+ String name = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName();
+ if (name.equals(displayName) || (name.trim().length() == 0 && displayName.equals(ResourceBundleManager.defaultLocaleTag))) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
index ea15a539..dbdc1957 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java
@@ -1,55 +1,62 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import org.eclipse.jface.resource.CompositeImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-
-public class OverlayIcon extends CompositeImageDescriptor {
-
- public static final int TOP_LEFT = 0;
- public static final int TOP_RIGHT = 1;
- public static final int BOTTOM_LEFT = 2;
- public static final int BOTTOM_RIGHT = 3;
-
- private Image img;
- private Image overlay;
- private int location;
- private Point imgSize;
-
- public OverlayIcon(Image baseImage, Image overlayImage, int location) {
- super();
- this.img = baseImage;
- this.overlay = overlayImage;
- this.location = location;
- this.imgSize = new Point(baseImage.getImageData().width, baseImage.getImageData().height);
- }
-
- @Override
- protected void drawCompositeImage(int width, int height) {
- drawImage(img.getImageData(), 0, 0);
- ImageData imageData = overlay.getImageData();
-
- switch (location) {
- case TOP_LEFT:
- drawImage(imageData, 0, 0);
- break;
- case TOP_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width, 0);
- break;
- case BOTTOM_LEFT:
- drawImage(imageData, 0, imgSize.y - imageData.height);
- break;
- case BOTTOM_RIGHT:
- drawImage(imageData, imgSize.x - imageData.width, imgSize.y
- - imageData.height);
- break;
- }
- }
-
- @Override
- protected Point getSize() {
- return new Point(img.getImageData().width, img.getImageData().height);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import org.eclipse.jface.resource.CompositeImageDescriptor;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.ImageData;
+import org.eclipse.swt.graphics.Point;
+
+public class OverlayIcon extends CompositeImageDescriptor {
+
+ public static final int TOP_LEFT = 0;
+ public static final int TOP_RIGHT = 1;
+ public static final int BOTTOM_LEFT = 2;
+ public static final int BOTTOM_RIGHT = 3;
+
+ private Image img;
+ private Image overlay;
+ private int location;
+ private Point imgSize;
+
+ public OverlayIcon(Image baseImage, Image overlayImage, int location) {
+ super();
+ this.img = baseImage;
+ this.overlay = overlayImage;
+ this.location = location;
+ this.imgSize = new Point(baseImage.getImageData().width, baseImage.getImageData().height);
+ }
+
+ @Override
+ protected void drawCompositeImage(int width, int height) {
+ drawImage(img.getImageData(), 0, 0);
+ ImageData imageData = overlay.getImageData();
+
+ switch (location) {
+ case TOP_LEFT:
+ drawImage(imageData, 0, 0);
+ break;
+ case TOP_RIGHT:
+ drawImage(imageData, imgSize.x - imageData.width, 0);
+ break;
+ case BOTTOM_LEFT:
+ drawImage(imageData, 0, imgSize.y - imageData.height);
+ break;
+ case BOTTOM_RIGHT:
+ drawImage(imageData, imgSize.x - imageData.width, imgSize.y
+ - imageData.height);
+ break;
+ }
+ }
+
+ @Override
+ protected Point getSize() {
+ return new Point(img.getImageData().width, img.getImageData().height);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java
index df45b7ad..378a2b0f 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java
@@ -1,337 +1,344 @@
-/*
- * Copyright (C) 2007 Uwe Voigt
- *
- * This file is part of Essiembre ResourceBundle Editor.
- *
- * Essiembre ResourceBundle Editor 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.
- *
- * Essiembre ResourceBundle Editor 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 Essiembre ResourceBundle Editor; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
- * Boston, MA 02111-1307 USA
- */
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.osgi.framework.Constants;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- * A class that helps to find fragment and plugin projects.
- *
- * @author Uwe Voigt (http://sourceforge.net/users/uwe_ewald/)
- */
-public class PDEUtils {
-
- /** Bundle manifest name */
- public static final String OSGI_BUNDLE_MANIFEST = "META-INF/MANIFEST.MF"; //$NON-NLS-1$
- /** Plugin manifest name */
- public static final String PLUGIN_MANIFEST = "plugin.xml"; //$NON-NLS-1$
- /** Fragment manifest name */
- public static final String FRAGMENT_MANIFEST = "fragment.xml"; //$NON-NLS-1$
-
- /**
- * Returns the plugin-id of the project if it is a plugin project. Else null
- * is returned.
- *
- * @param project
- * the project
- * @return the plugin-id or null
- */
- public static String getPluginId(IProject project) {
- if (project == null) {
- return null;
- }
- IResource manifest = project.findMember(OSGI_BUNDLE_MANIFEST);
- String id = getManifestEntryValue(manifest,
- Constants.BUNDLE_SYMBOLICNAME);
- if (id != null) {
- return id;
- }
- manifest = project.findMember(PLUGIN_MANIFEST);
- if (manifest == null) {
- manifest = project.findMember(FRAGMENT_MANIFEST);
- }
- if (manifest instanceof IFile) {
- InputStream in = null;
- try {
- DocumentBuilder builder = DocumentBuilderFactory.newInstance()
- .newDocumentBuilder();
- in = ((IFile) manifest).getContents();
- Document document = builder.parse(in);
- Node node = getXMLElement(document, "plugin"); //$NON-NLS-1$
- if (node == null) {
- node = getXMLElement(document, "fragment"); //$NON-NLS-1$
- }
- if (node != null) {
- node = node.getAttributes().getNamedItem("id"); //$NON-NLS-1$
- }
- if (node != null) {
- return node.getNodeValue();
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- return null;
- }
-
- /**
- * Returns all project containing plugin/fragment of the specified project.
- * If the specified project itself is a fragment, then only this is
- * returned.
- *
- * @param pluginProject
- * the plugin project
- * @return the all project containing a fragment or null if none
- */
- public static IProject[] lookupFragment(IProject pluginProject) {
- List<IProject> fragmentIds = new ArrayList<IProject>();
-
- String pluginId = PDEUtils.getPluginId(pluginProject);
- if (pluginId == null) {
- return null;
- }
- String fragmentId = getFragmentId(pluginProject,
- getPluginId(getFragmentHost(pluginProject)));
- if (fragmentId != null) {
- fragmentIds.add(pluginProject);
- return fragmentIds.toArray(new IProject[0]);
- }
-
- IProject[] projects = pluginProject.getWorkspace().getRoot()
- .getProjects();
- for (int i = 0; i < projects.length; i++) {
- IProject project = projects[i];
- if (!project.isOpen()) {
- continue;
- }
- if (getFragmentId(project, pluginId) == null) {
- continue;
- }
- fragmentIds.add(project);
- }
-
- if (fragmentIds.size() > 0) {
- return fragmentIds.toArray(new IProject[0]);
- } else {
- return null;
- }
- }
-
- public static boolean isFragment(IProject pluginProject) {
- String pluginId = PDEUtils.getPluginId(pluginProject);
- if (pluginId == null) {
- return false;
- }
- String fragmentId = getFragmentId(pluginProject,
- getPluginId(getFragmentHost(pluginProject)));
- if (fragmentId != null) {
- return true;
- } else {
- return false;
- }
- }
-
- public static List<IProject> getFragments(IProject hostProject) {
- List<IProject> fragmentIds = new ArrayList<IProject>();
-
- String pluginId = PDEUtils.getPluginId(hostProject);
- IProject[] projects = hostProject.getWorkspace().getRoot()
- .getProjects();
-
- for (int i = 0; i < projects.length; i++) {
- IProject project = projects[i];
- if (!project.isOpen()) {
- continue;
- }
- if (getFragmentId(project, pluginId) == null) {
- continue;
- }
- fragmentIds.add(project);
- }
-
- return fragmentIds;
- }
-
- /**
- * Returns the fragment-id of the project if it is a fragment project with
- * the specified host plugin id as host. Else null is returned.
- *
- * @param project
- * the project
- * @param hostPluginId
- * the host plugin id
- * @return the plugin-id or null
- */
- public static String getFragmentId(IProject project, String hostPluginId) {
- IResource manifest = project.findMember(FRAGMENT_MANIFEST);
- Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$
- if (fragmentNode != null) {
- Node hostNode = fragmentNode.getAttributes().getNamedItem(
- "plugin-id"); //$NON-NLS-1$
- if (hostNode != null
- && hostNode.getNodeValue().equals(hostPluginId)) {
- Node idNode = fragmentNode.getAttributes().getNamedItem("id"); //$NON-NLS-1$
- if (idNode != null) {
- return idNode.getNodeValue();
- }
- }
- }
- manifest = project.findMember(OSGI_BUNDLE_MANIFEST);
- String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST);
- if (hostId != null && hostId.equals(hostPluginId)) {
- return getManifestEntryValue(manifest,
- Constants.BUNDLE_SYMBOLICNAME);
- }
- return null;
- }
-
- /**
- * Returns the host plugin project of the specified project if it contains a
- * fragment.
- *
- * @param fragment
- * the fragment project
- * @return the host plugin project or null
- */
- public static IProject getFragmentHost(IProject fragment) {
- IResource manifest = fragment.findMember(FRAGMENT_MANIFEST);
- Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$
- if (fragmentNode != null) {
- Node hostNode = fragmentNode.getAttributes().getNamedItem(
- "plugin-id"); //$NON-NLS-1$
- if (hostNode != null) {
- return fragment.getWorkspace().getRoot()
- .getProject(hostNode.getNodeValue());
- }
- }
- manifest = fragment.findMember(OSGI_BUNDLE_MANIFEST);
- String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST);
- if (hostId != null) {
- return fragment.getWorkspace().getRoot().getProject(hostId);
- }
- return null;
- }
-
- /**
- * Returns the file content as UTF8 string.
- *
- * @param file
- * @param charset
- * @return
- */
- public static String getFileContent(IFile file, String charset) {
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- InputStream in = null;
- try {
- in = file.getContents(true);
- byte[] buf = new byte[8000];
- for (int count; (count = in.read(buf)) != -1;) {
- outputStream.write(buf, 0, count);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException ignore) {
- }
- }
- }
- try {
- return outputStream.toString(charset);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- return outputStream.toString();
- }
- }
-
- private static String getManifestEntryValue(IResource manifest,
- String entryKey) {
- if (manifest instanceof IFile) {
- String content = getFileContent((IFile) manifest, "UTF8"); //$NON-NLS-1$
- int index = content.indexOf(entryKey);
- if (index != -1) {
- StringTokenizer st = new StringTokenizer(
- content.substring(index + entryKey.length()), ";:\r\n"); //$NON-NLS-1$
- return st.nextToken().trim();
- }
- }
- return null;
- }
-
- private static Document getXMLDocument(IResource resource) {
- if (!(resource instanceof IFile)) {
- return null;
- }
- InputStream in = null;
- try {
- DocumentBuilder builder = DocumentBuilderFactory.newInstance()
- .newDocumentBuilder();
- in = ((IFile) resource).getContents();
- return builder.parse(in);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- } finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
-
- private static Node getXMLElement(Document document, String name) {
- if (document == null) {
- return null;
- }
- NodeList list = document.getChildNodes();
- for (int i = 0; i < list.getLength(); i++) {
- Node node = list.item(i);
- if (node.getNodeType() != Node.ELEMENT_NODE) {
- continue;
- }
- if (name.equals(node.getNodeName())) {
- return node;
- }
- }
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * 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
+ ******************************************************************************/
+/*
+ * Copyright (C) 2007 Uwe Voigt
+ *
+ * This file is part of Essiembre ResourceBundle Editor.
+ *
+ * Essiembre ResourceBundle Editor 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.
+ *
+ * Essiembre ResourceBundle Editor 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 Essiembre ResourceBundle Editor; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307 USA
+ */
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.osgi.framework.Constants;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * A class that helps to find fragment and plugin projects.
+ *
+ * @author Uwe Voigt (http://sourceforge.net/users/uwe_ewald/)
+ */
+public class PDEUtils {
+
+ /** Bundle manifest name */
+ public static final String OSGI_BUNDLE_MANIFEST = "META-INF/MANIFEST.MF"; //$NON-NLS-1$
+ /** Plugin manifest name */
+ public static final String PLUGIN_MANIFEST = "plugin.xml"; //$NON-NLS-1$
+ /** Fragment manifest name */
+ public static final String FRAGMENT_MANIFEST = "fragment.xml"; //$NON-NLS-1$
+
+ /**
+ * Returns the plugin-id of the project if it is a plugin project. Else null
+ * is returned.
+ *
+ * @param project
+ * the project
+ * @return the plugin-id or null
+ */
+ public static String getPluginId(IProject project) {
+ if (project == null) {
+ return null;
+ }
+ IResource manifest = project.findMember(OSGI_BUNDLE_MANIFEST);
+ String id = getManifestEntryValue(manifest,
+ Constants.BUNDLE_SYMBOLICNAME);
+ if (id != null) {
+ return id;
+ }
+ manifest = project.findMember(PLUGIN_MANIFEST);
+ if (manifest == null) {
+ manifest = project.findMember(FRAGMENT_MANIFEST);
+ }
+ if (manifest instanceof IFile) {
+ InputStream in = null;
+ try {
+ DocumentBuilder builder = DocumentBuilderFactory.newInstance()
+ .newDocumentBuilder();
+ in = ((IFile) manifest).getContents();
+ Document document = builder.parse(in);
+ Node node = getXMLElement(document, "plugin"); //$NON-NLS-1$
+ if (node == null) {
+ node = getXMLElement(document, "fragment"); //$NON-NLS-1$
+ }
+ if (node != null) {
+ node = node.getAttributes().getNamedItem("id"); //$NON-NLS-1$
+ }
+ if (node != null) {
+ return node.getNodeValue();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ if (in != null) {
+ in.close();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns all project containing plugin/fragment of the specified project.
+ * If the specified project itself is a fragment, then only this is
+ * returned.
+ *
+ * @param pluginProject
+ * the plugin project
+ * @return the all project containing a fragment or null if none
+ */
+ public static IProject[] lookupFragment(IProject pluginProject) {
+ List<IProject> fragmentIds = new ArrayList<IProject>();
+
+ String pluginId = PDEUtils.getPluginId(pluginProject);
+ if (pluginId == null) {
+ return null;
+ }
+ String fragmentId = getFragmentId(pluginProject,
+ getPluginId(getFragmentHost(pluginProject)));
+ if (fragmentId != null) {
+ fragmentIds.add(pluginProject);
+ return fragmentIds.toArray(new IProject[0]);
+ }
+
+ IProject[] projects = pluginProject.getWorkspace().getRoot()
+ .getProjects();
+ for (int i = 0; i < projects.length; i++) {
+ IProject project = projects[i];
+ if (!project.isOpen()) {
+ continue;
+ }
+ if (getFragmentId(project, pluginId) == null) {
+ continue;
+ }
+ fragmentIds.add(project);
+ }
+
+ if (fragmentIds.size() > 0) {
+ return fragmentIds.toArray(new IProject[0]);
+ } else {
+ return null;
+ }
+ }
+
+ public static boolean isFragment(IProject pluginProject) {
+ String pluginId = PDEUtils.getPluginId(pluginProject);
+ if (pluginId == null) {
+ return false;
+ }
+ String fragmentId = getFragmentId(pluginProject,
+ getPluginId(getFragmentHost(pluginProject)));
+ if (fragmentId != null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public static List<IProject> getFragments(IProject hostProject) {
+ List<IProject> fragmentIds = new ArrayList<IProject>();
+
+ String pluginId = PDEUtils.getPluginId(hostProject);
+ IProject[] projects = hostProject.getWorkspace().getRoot()
+ .getProjects();
+
+ for (int i = 0; i < projects.length; i++) {
+ IProject project = projects[i];
+ if (!project.isOpen()) {
+ continue;
+ }
+ if (getFragmentId(project, pluginId) == null) {
+ continue;
+ }
+ fragmentIds.add(project);
+ }
+
+ return fragmentIds;
+ }
+
+ /**
+ * Returns the fragment-id of the project if it is a fragment project with
+ * the specified host plugin id as host. Else null is returned.
+ *
+ * @param project
+ * the project
+ * @param hostPluginId
+ * the host plugin id
+ * @return the plugin-id or null
+ */
+ public static String getFragmentId(IProject project, String hostPluginId) {
+ IResource manifest = project.findMember(FRAGMENT_MANIFEST);
+ Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$
+ if (fragmentNode != null) {
+ Node hostNode = fragmentNode.getAttributes().getNamedItem(
+ "plugin-id"); //$NON-NLS-1$
+ if (hostNode != null
+ && hostNode.getNodeValue().equals(hostPluginId)) {
+ Node idNode = fragmentNode.getAttributes().getNamedItem("id"); //$NON-NLS-1$
+ if (idNode != null) {
+ return idNode.getNodeValue();
+ }
+ }
+ }
+ manifest = project.findMember(OSGI_BUNDLE_MANIFEST);
+ String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST);
+ if (hostId != null && hostId.equals(hostPluginId)) {
+ return getManifestEntryValue(manifest,
+ Constants.BUNDLE_SYMBOLICNAME);
+ }
+ return null;
+ }
+
+ /**
+ * Returns the host plugin project of the specified project if it contains a
+ * fragment.
+ *
+ * @param fragment
+ * the fragment project
+ * @return the host plugin project or null
+ */
+ public static IProject getFragmentHost(IProject fragment) {
+ IResource manifest = fragment.findMember(FRAGMENT_MANIFEST);
+ Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$
+ if (fragmentNode != null) {
+ Node hostNode = fragmentNode.getAttributes().getNamedItem(
+ "plugin-id"); //$NON-NLS-1$
+ if (hostNode != null) {
+ return fragment.getWorkspace().getRoot()
+ .getProject(hostNode.getNodeValue());
+ }
+ }
+ manifest = fragment.findMember(OSGI_BUNDLE_MANIFEST);
+ String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST);
+ if (hostId != null) {
+ return fragment.getWorkspace().getRoot().getProject(hostId);
+ }
+ return null;
+ }
+
+ /**
+ * Returns the file content as UTF8 string.
+ *
+ * @param file
+ * @param charset
+ * @return
+ */
+ public static String getFileContent(IFile file, String charset) {
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ InputStream in = null;
+ try {
+ in = file.getContents(true);
+ byte[] buf = new byte[8000];
+ for (int count; (count = in.read(buf)) != -1;) {
+ outputStream.write(buf, 0, count);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException ignore) {
+ }
+ }
+ }
+ try {
+ return outputStream.toString(charset);
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ return outputStream.toString();
+ }
+ }
+
+ private static String getManifestEntryValue(IResource manifest,
+ String entryKey) {
+ if (manifest instanceof IFile) {
+ String content = getFileContent((IFile) manifest, "UTF8"); //$NON-NLS-1$
+ int index = content.indexOf(entryKey);
+ if (index != -1) {
+ StringTokenizer st = new StringTokenizer(
+ content.substring(index + entryKey.length()), ";:\r\n"); //$NON-NLS-1$
+ return st.nextToken().trim();
+ }
+ }
+ return null;
+ }
+
+ private static Document getXMLDocument(IResource resource) {
+ if (!(resource instanceof IFile)) {
+ return null;
+ }
+ InputStream in = null;
+ try {
+ DocumentBuilder builder = DocumentBuilderFactory.newInstance()
+ .newDocumentBuilder();
+ in = ((IFile) resource).getContents();
+ return builder.parse(in);
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ } finally {
+ try {
+ if (in != null) {
+ in.close();
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private static Node getXMLElement(Document document, String name) {
+ if (document == null) {
+ return null;
+ }
+ NodeList list = document.getChildNodes();
+ for (int i = 0; i < list.getLength(); i++) {
+ Node node = list.item(i);
+ if (node.getNodeType() != Node.ELEMENT_NODE) {
+ continue;
+ }
+ if (name.equals(node.getNodeName())) {
+ return node;
+ }
+ }
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java
index dc8718f2..ec3f5d6d 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java
@@ -1,174 +1,181 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.Activator;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.model.preferences.CheckItem;
-import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.preference.IPreferenceStore;
-
-
-/**
- *
- * @author mgasser
- *
- */
-public class RBFileUtils extends Action{
- public static final String PROPERTIES_EXT = "properties";
-
-
- /**
- * Returns true if a file is a ResourceBundle-file
- */
- public static boolean isResourceBundleFile(IResource file) {
- boolean isValied = false;
-
- if (file != null && file instanceof IFile && !file.isDerived() &&
- file.getFileExtension()!=null && file.getFileExtension().equalsIgnoreCase("properties")){
- isValied = true;
-
- //Check if file is not in the blacklist
- IPreferenceStore pref = null;
- if (Activator.getDefault() != null)
- pref = Activator.getDefault().getPreferenceStore();
-
- if (pref != null){
- List<CheckItem> list = TapiJIPreferences.getNonRbPatternAsList();
- for (CheckItem item : list){
- if (item.getChecked() && file.getFullPath().toString().matches(item.getName())){
- isValied = false;
-
- //if properties-file is not RB-file and has ResouceBundleMarker, deletes all ResouceBundleMarker of the file
- if (hasResourceBundleMarker(file))
- try {
- file.deleteMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- }
- }
- }
- }
- }
-
- return isValied;
- }
-
- /**
- * Checks whether a RB-file has a problem-marker
- */
- public static boolean hasResourceBundleMarker(IResource r){
- try {
- if(r.findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0)
- return true;
- else return false;
- } catch (CoreException e) {
- return false;
- }
- }
-
-
- /**
- * @return the locale of a given properties-file
- */
- public static Locale getLocale(IFile file){
- String localeID = file.getName();
- localeID = localeID.substring(0, localeID.length() - "properties".length() - 1);
- String baseBundleName = ResourceBundleManager.getResourceBundleName(file);
-
- Locale locale;
- if (localeID.length() == baseBundleName.length()) {
- locale = null; //Default locale
- } else {
- localeID = localeID.substring(baseBundleName.length() + 1);
- String[] localeTokens = localeID.split("_");
- switch (localeTokens.length) {
- case 1:
- locale = new Locale(localeTokens[0]);
- break;
- case 2:
- locale = new Locale(localeTokens[0], localeTokens[1]);
- break;
- case 3:
- locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]);
- break;
- default:
- locale = new Locale("");
- break;
- }
- }
- return locale;
- }
-
- /**
- * @return number of ResourceBundles in the subtree
- */
- public static int countRecursiveResourceBundle(IContainer container) {
- return getSubResourceBundle(container).size();
- }
-
-
- private static List<String> getSubResourceBundle(IContainer container){
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(container.getProject());
-
- String conatinerId = container.getFullPath().toString();
- List<String> subResourceBundles = new ArrayList<String>();
-
- for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
- for(IResource r : rbmanager.getResourceBundles(rbId)){
- if (r.getFullPath().toString().contains(conatinerId) && (!subResourceBundles.contains(rbId))){
- subResourceBundles.add(rbId);
- }
- }
- }
- return subResourceBundles;
- }
-
- /**
- * @param container
- * @return Set with all ResourceBundles in this container
- */
- public static Set<String> getResourceBundleIds (IContainer container) {
- Set<String> resourcebundles = new HashSet<String>();
-
- try {
- for(IResource r : container.members()){
- if (r instanceof IFile) {
- String resourcebundle = getCorrespondingResourceBundleId((IFile)r);
- if (resourcebundle != null) resourcebundles.add(resourcebundle);
- }
- }
- } catch (CoreException e) {/*resourcebundle.size()==0*/}
-
- return resourcebundles;
- }
-
- /**
- *
- * @param file
- * @return ResourceBundle-name or null if no ResourceBundle contains the file
- */
- //TODO integrate in ResourceBundleManager
- public static String getCorrespondingResourceBundleId (IFile file) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file.getProject());
- String possibleRBId = null;
-
- if (isResourceBundleFile((IFile) file)) {
- possibleRBId = ResourceBundleManager.getResourceBundleId(file);
-
- for (String rbId : rbmanager.getResourceBundleIdentifiers()){
- if ( possibleRBId.equals(rbId) )
- return possibleRBId;
- }
- }
- return null;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.Activator;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.model.preferences.CheckItem;
+import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.preference.IPreferenceStore;
+
+
+/**
+ *
+ * @author mgasser
+ *
+ */
+public class RBFileUtils extends Action{
+ public static final String PROPERTIES_EXT = "properties";
+
+
+ /**
+ * Returns true if a file is a ResourceBundle-file
+ */
+ public static boolean isResourceBundleFile(IResource file) {
+ boolean isValied = false;
+
+ if (file != null && file instanceof IFile && !file.isDerived() &&
+ file.getFileExtension()!=null && file.getFileExtension().equalsIgnoreCase("properties")){
+ isValied = true;
+
+ //Check if file is not in the blacklist
+ IPreferenceStore pref = null;
+ if (Activator.getDefault() != null)
+ pref = Activator.getDefault().getPreferenceStore();
+
+ if (pref != null){
+ List<CheckItem> list = TapiJIPreferences.getNonRbPatternAsList();
+ for (CheckItem item : list){
+ if (item.getChecked() && file.getFullPath().toString().matches(item.getName())){
+ isValied = false;
+
+ //if properties-file is not RB-file and has ResouceBundleMarker, deletes all ResouceBundleMarker of the file
+ if (hasResourceBundleMarker(file))
+ try {
+ file.deleteMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ }
+ }
+ }
+ }
+ }
+
+ return isValied;
+ }
+
+ /**
+ * Checks whether a RB-file has a problem-marker
+ */
+ public static boolean hasResourceBundleMarker(IResource r){
+ try {
+ if(r.findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE).length > 0)
+ return true;
+ else return false;
+ } catch (CoreException e) {
+ return false;
+ }
+ }
+
+
+ /**
+ * @return the locale of a given properties-file
+ */
+ public static Locale getLocale(IFile file){
+ String localeID = file.getName();
+ localeID = localeID.substring(0, localeID.length() - "properties".length() - 1);
+ String baseBundleName = ResourceBundleManager.getResourceBundleName(file);
+
+ Locale locale;
+ if (localeID.length() == baseBundleName.length()) {
+ locale = null; //Default locale
+ } else {
+ localeID = localeID.substring(baseBundleName.length() + 1);
+ String[] localeTokens = localeID.split("_");
+ switch (localeTokens.length) {
+ case 1:
+ locale = new Locale(localeTokens[0]);
+ break;
+ case 2:
+ locale = new Locale(localeTokens[0], localeTokens[1]);
+ break;
+ case 3:
+ locale = new Locale(localeTokens[0], localeTokens[1], localeTokens[2]);
+ break;
+ default:
+ locale = new Locale("");
+ break;
+ }
+ }
+ return locale;
+ }
+
+ /**
+ * @return number of ResourceBundles in the subtree
+ */
+ public static int countRecursiveResourceBundle(IContainer container) {
+ return getSubResourceBundle(container).size();
+ }
+
+
+ private static List<String> getSubResourceBundle(IContainer container){
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(container.getProject());
+
+ String conatinerId = container.getFullPath().toString();
+ List<String> subResourceBundles = new ArrayList<String>();
+
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()) {
+ for(IResource r : rbmanager.getResourceBundles(rbId)){
+ if (r.getFullPath().toString().contains(conatinerId) && (!subResourceBundles.contains(rbId))){
+ subResourceBundles.add(rbId);
+ }
+ }
+ }
+ return subResourceBundles;
+ }
+
+ /**
+ * @param container
+ * @return Set with all ResourceBundles in this container
+ */
+ public static Set<String> getResourceBundleIds (IContainer container) {
+ Set<String> resourcebundles = new HashSet<String>();
+
+ try {
+ for(IResource r : container.members()){
+ if (r instanceof IFile) {
+ String resourcebundle = getCorrespondingResourceBundleId((IFile)r);
+ if (resourcebundle != null) resourcebundles.add(resourcebundle);
+ }
+ }
+ } catch (CoreException e) {/*resourcebundle.size()==0*/}
+
+ return resourcebundles;
+ }
+
+ /**
+ *
+ * @param file
+ * @return ResourceBundle-name or null if no ResourceBundle contains the file
+ */
+ //TODO integrate in ResourceBundleManager
+ public static String getCorrespondingResourceBundleId (IFile file) {
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file.getProject());
+ String possibleRBId = null;
+
+ if (isResourceBundleFile((IFile) file)) {
+ possibleRBId = ResourceBundleManager.getResourceBundleId(file);
+
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()){
+ if ( possibleRBId.equals(rbId) )
+ return possibleRBId;
+ }
+ }
+ return null;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ResourceUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ResourceUtils.java
index 85dd34e9..2f8f8a2c 100644
--- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ResourceUtils.java
+++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/ResourceUtils.java
@@ -1,98 +1,105 @@
-package org.eclipse.babel.tapiji.tools.core.util;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-
-
-public class ResourceUtils {
-
- private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*";
- private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*";
-
- public static boolean isValidResourceKey (String key) {
- boolean isValid = false;
-
- if (key != null && key.trim().length() > 0) {
- isValid = key.matches(REGEXP_RESOURCE_KEY);
- }
-
- return isValid;
- }
-
- public static String deriveNonExistingRBName (String nameProposal, ResourceBundleManager manager) {
- // Adapt the proposal to the requirements for Resource-Bundle names
- nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME, "");
-
- int i = 0;
- do {
- if (manager.getResourceBundleIdentifiers().contains(nameProposal) || nameProposal.length() == 0) {
- nameProposal = nameProposal + (++i);
- } else
- break;
- } while (true);
-
- return nameProposal;
- }
-
- public static boolean isJavaCompUnit (IResource res) {
- boolean result = false;
-
- if (res.getType() == IResource.FILE && !res.isDerived() &&
- res.getFileExtension().equalsIgnoreCase("java")) {
- result = true;
- }
-
- return result;
- }
-
- public static boolean isJSPResource(IResource res) {
- boolean result = false;
-
- if (res.getType() == IResource.FILE && !res.isDerived() &&
- (res.getFileExtension().equalsIgnoreCase("jsp") ||
- res.getFileExtension().equalsIgnoreCase("xhtml"))) {
- result = true;
- }
-
- return result;
- }
-
- /**
- *
- * @param baseFolder
- * @param targetProjects Projects with a same structure
- * @return List of
- */
- public static List<IContainer> getCorrespondingFolders(IContainer baseFolder, List<IProject> targetProjects){
- List<IContainer> correspondingFolder = new ArrayList<IContainer>();
-
- for(IProject p : targetProjects){
- IContainer c = getCorrespondingFolders(baseFolder, p);
- if (c.exists()) correspondingFolder.add(c);
- }
-
- return correspondingFolder;
- }
-
- /**
- *
- * @param baseFolder
- * @param targetProject
- * @return a Container with the corresponding path as the baseFolder. The Container doesn't must exist.
- */
- public static IContainer getCorrespondingFolders(IContainer baseFolder, IProject targetProject) {
- IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo(baseFolder.getProject().getFullPath());
-
- if (!relativ_folder.isEmpty())
- return targetProject.getFolder(relativ_folder);
- else
- return targetProject;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.core.util;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IPath;
+
+
+public class ResourceUtils {
+
+ private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*";
+ private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*";
+
+ public static boolean isValidResourceKey (String key) {
+ boolean isValid = false;
+
+ if (key != null && key.trim().length() > 0) {
+ isValid = key.matches(REGEXP_RESOURCE_KEY);
+ }
+
+ return isValid;
+ }
+
+ public static String deriveNonExistingRBName (String nameProposal, ResourceBundleManager manager) {
+ // Adapt the proposal to the requirements for Resource-Bundle names
+ nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME, "");
+
+ int i = 0;
+ do {
+ if (manager.getResourceBundleIdentifiers().contains(nameProposal) || nameProposal.length() == 0) {
+ nameProposal = nameProposal + (++i);
+ } else
+ break;
+ } while (true);
+
+ return nameProposal;
+ }
+
+ public static boolean isJavaCompUnit (IResource res) {
+ boolean result = false;
+
+ if (res.getType() == IResource.FILE && !res.isDerived() &&
+ res.getFileExtension().equalsIgnoreCase("java")) {
+ result = true;
+ }
+
+ return result;
+ }
+
+ public static boolean isJSPResource(IResource res) {
+ boolean result = false;
+
+ if (res.getType() == IResource.FILE && !res.isDerived() &&
+ (res.getFileExtension().equalsIgnoreCase("jsp") ||
+ res.getFileExtension().equalsIgnoreCase("xhtml"))) {
+ result = true;
+ }
+
+ return result;
+ }
+
+ /**
+ *
+ * @param baseFolder
+ * @param targetProjects Projects with a same structure
+ * @return List of
+ */
+ public static List<IContainer> getCorrespondingFolders(IContainer baseFolder, List<IProject> targetProjects){
+ List<IContainer> correspondingFolder = new ArrayList<IContainer>();
+
+ for(IProject p : targetProjects){
+ IContainer c = getCorrespondingFolders(baseFolder, p);
+ if (c.exists()) correspondingFolder.add(c);
+ }
+
+ return correspondingFolder;
+ }
+
+ /**
+ *
+ * @param baseFolder
+ * @param targetProject
+ * @return a Container with the corresponding path as the baseFolder. The Container doesn't must exist.
+ */
+ public static IContainer getCorrespondingFolders(IContainer baseFolder, IProject targetProject) {
+ IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo(baseFolder.getProject().getFullPath());
+
+ if (!relativ_folder.isEmpty())
+ return targetProject.getFolder(relativ_folder);
+ else
+ return targetProject;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java
index 38b182b7..6e4336f0 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/JavaResourceAuditor.java
@@ -1,155 +1,162 @@
-package org.eclipse.babel.tapiji.tools.java.auditor;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.builder.quickfix.CreateResourceBundle;
-import org.eclipse.babel.tapiji.tools.core.builder.quickfix.IncludeResource;
-import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor;
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry;
-import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation;
-import org.eclipse.babel.tapiji.tools.java.quickfix.ExcludeResourceFromInternationalization;
-import org.eclipse.babel.tapiji.tools.java.quickfix.ExportToResourceBundleResolution;
-import org.eclipse.babel.tapiji.tools.java.quickfix.IgnoreStringFromInternationalization;
-import org.eclipse.babel.tapiji.tools.java.quickfix.ReplaceResourceBundleDefReference;
-import org.eclipse.babel.tapiji.tools.java.quickfix.ReplaceResourceBundleReference;
-import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.ui.IMarkerResolution;
-
-
-public class JavaResourceAuditor extends I18nResourceAuditor {
-
- protected List<SLLocation> constantLiterals = new ArrayList<SLLocation>();
- protected List<SLLocation> brokenResourceReferences = new ArrayList<SLLocation>();
- protected List<SLLocation> brokenBundleReferences = new ArrayList<SLLocation>();
-
- @Override
- public String[] getFileEndings() {
- return new String[] { "java" };
- }
-
- @Override
- public void audit(IResource resource) {
-
- ResourceAuditVisitor csav = new ResourceAuditVisitor(resource
- .getProject().getFile(resource.getProjectRelativePath()),
- resource.getProject().getName());
-
- // get a reference to the shared AST of the loaded CompilationUnit
- CompilationUnit cu = ASTutils.getCompilationUnit(resource);
- if (cu == null) {
- System.out.println("Cannot audit resource: "
- + resource.getFullPath());
- return;
- }
- cu.accept(csav);
-
- // Report all constant string literals
- constantLiterals = csav.getConstantStringLiterals();
-
- // Report all broken Resource-Bundle references
- brokenResourceReferences = csav.getBrokenResourceReferences();
-
- // Report all broken definitions to Resource-Bundle references
- brokenBundleReferences = csav.getBrokenRBReferences();
- }
-
- @Override
- public List<ILocation> getConstantStringLiterals() {
- return new ArrayList<ILocation>(constantLiterals);
- }
-
- @Override
- public List<ILocation> getBrokenResourceReferences() {
- return new ArrayList<ILocation>(brokenResourceReferences);
- }
-
- @Override
- public List<ILocation> getBrokenBundleReferences() {
- return new ArrayList<ILocation>(brokenBundleReferences);
- }
-
- @Override
- public String getContextId() {
- return "java";
- }
-
- @Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
- int cause = marker.getAttribute("cause", -1);
-
- switch (marker.getAttribute("cause", -1)) {
- case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
- resolutions.add(new IgnoreStringFromInternationalization());
- resolutions.add(new ExcludeResourceFromInternationalization());
- resolutions.add(new ExportToResourceBundleResolution());
- break;
- case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
- String dataName = marker.getAttribute("bundleName", "");
- int dataStart = marker.getAttribute("bundleStart", 0);
- int dataEnd = marker.getAttribute("bundleEnd", 0);
-
- IProject project = marker.getResource().getProject();
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(project);
-
- if (manager.getResourceBundle(dataName) != null) {
- String key = marker.getAttribute("key", "");
-
- resolutions.add(new CreateResourceBundleEntry(key,
- dataName));
- resolutions.add(new ReplaceResourceBundleReference(key,
- dataName));
- resolutions.add(new ReplaceResourceBundleDefReference(dataName,
- dataStart, dataEnd));
- } else {
- String bname = dataName;
-
- Set<IResource> bundleResources = ResourceBundleManager
- .getManager(marker.getResource().getProject())
- .getAllResourceBundleResources(bname);
-
- if (bundleResources != null && bundleResources.size() > 0)
- resolutions
- .add(new IncludeResource(bname, bundleResources));
- else
- resolutions.add(new CreateResourceBundle(bname, marker
- .getResource(), dataStart, dataEnd));
- resolutions.add(new ReplaceResourceBundleDefReference(bname,
- dataStart, dataEnd));
- }
-
- break;
- case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
- String bname = marker.getAttribute("key", "");
-
- Set<IResource> bundleResources = ResourceBundleManager.getManager(
- marker.getResource().getProject())
- .getAllResourceBundleResources(bname);
-
- if (bundleResources != null && bundleResources.size() > 0)
- resolutions.add(new IncludeResource(bname, bundleResources));
- else
- resolutions.add(new CreateResourceBundle(marker.getAttribute(
- "key", ""), marker.getResource(), marker.getAttribute(
- IMarker.CHAR_START, 0), marker.getAttribute(
- IMarker.CHAR_END, 0)));
- resolutions.add(new ReplaceResourceBundleDefReference(marker
- .getAttribute("key", ""), marker.getAttribute(
- IMarker.CHAR_START, 0), marker.getAttribute(
- IMarker.CHAR_END, 0)));
- }
-
- return resolutions;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.auditor;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.builder.quickfix.CreateResourceBundle;
+import org.eclipse.babel.tapiji.tools.core.builder.quickfix.IncludeResource;
+import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry;
+import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation;
+import org.eclipse.babel.tapiji.tools.java.quickfix.ExcludeResourceFromInternationalization;
+import org.eclipse.babel.tapiji.tools.java.quickfix.ExportToResourceBundleResolution;
+import org.eclipse.babel.tapiji.tools.java.quickfix.IgnoreStringFromInternationalization;
+import org.eclipse.babel.tapiji.tools.java.quickfix.ReplaceResourceBundleDefReference;
+import org.eclipse.babel.tapiji.tools.java.quickfix.ReplaceResourceBundleReference;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.ui.IMarkerResolution;
+
+
+public class JavaResourceAuditor extends I18nResourceAuditor {
+
+ protected List<SLLocation> constantLiterals = new ArrayList<SLLocation>();
+ protected List<SLLocation> brokenResourceReferences = new ArrayList<SLLocation>();
+ protected List<SLLocation> brokenBundleReferences = new ArrayList<SLLocation>();
+
+ @Override
+ public String[] getFileEndings() {
+ return new String[] { "java" };
+ }
+
+ @Override
+ public void audit(IResource resource) {
+
+ ResourceAuditVisitor csav = new ResourceAuditVisitor(resource
+ .getProject().getFile(resource.getProjectRelativePath()),
+ resource.getProject().getName());
+
+ // get a reference to the shared AST of the loaded CompilationUnit
+ CompilationUnit cu = ASTutils.getCompilationUnit(resource);
+ if (cu == null) {
+ System.out.println("Cannot audit resource: "
+ + resource.getFullPath());
+ return;
+ }
+ cu.accept(csav);
+
+ // Report all constant string literals
+ constantLiterals = csav.getConstantStringLiterals();
+
+ // Report all broken Resource-Bundle references
+ brokenResourceReferences = csav.getBrokenResourceReferences();
+
+ // Report all broken definitions to Resource-Bundle references
+ brokenBundleReferences = csav.getBrokenRBReferences();
+ }
+
+ @Override
+ public List<ILocation> getConstantStringLiterals() {
+ return new ArrayList<ILocation>(constantLiterals);
+ }
+
+ @Override
+ public List<ILocation> getBrokenResourceReferences() {
+ return new ArrayList<ILocation>(brokenResourceReferences);
+ }
+
+ @Override
+ public List<ILocation> getBrokenBundleReferences() {
+ return new ArrayList<ILocation>(brokenBundleReferences);
+ }
+
+ @Override
+ public String getContextId() {
+ return "java";
+ }
+
+ @Override
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
+ List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
+ int cause = marker.getAttribute("cause", -1);
+
+ switch (marker.getAttribute("cause", -1)) {
+ case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
+ resolutions.add(new IgnoreStringFromInternationalization());
+ resolutions.add(new ExcludeResourceFromInternationalization());
+ resolutions.add(new ExportToResourceBundleResolution());
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
+ String dataName = marker.getAttribute("bundleName", "");
+ int dataStart = marker.getAttribute("bundleStart", 0);
+ int dataEnd = marker.getAttribute("bundleEnd", 0);
+
+ IProject project = marker.getResource().getProject();
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(project);
+
+ if (manager.getResourceBundle(dataName) != null) {
+ String key = marker.getAttribute("key", "");
+
+ resolutions.add(new CreateResourceBundleEntry(key,
+ dataName));
+ resolutions.add(new ReplaceResourceBundleReference(key,
+ dataName));
+ resolutions.add(new ReplaceResourceBundleDefReference(dataName,
+ dataStart, dataEnd));
+ } else {
+ String bname = dataName;
+
+ Set<IResource> bundleResources = ResourceBundleManager
+ .getManager(marker.getResource().getProject())
+ .getAllResourceBundleResources(bname);
+
+ if (bundleResources != null && bundleResources.size() > 0)
+ resolutions
+ .add(new IncludeResource(bname, bundleResources));
+ else
+ resolutions.add(new CreateResourceBundle(bname, marker
+ .getResource(), dataStart, dataEnd));
+ resolutions.add(new ReplaceResourceBundleDefReference(bname,
+ dataStart, dataEnd));
+ }
+
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
+ String bname = marker.getAttribute("key", "");
+
+ Set<IResource> bundleResources = ResourceBundleManager.getManager(
+ marker.getResource().getProject())
+ .getAllResourceBundleResources(bname);
+
+ if (bundleResources != null && bundleResources.size() > 0)
+ resolutions.add(new IncludeResource(bname, bundleResources));
+ else
+ resolutions.add(new CreateResourceBundle(marker.getAttribute(
+ "key", ""), marker.getResource(), marker.getAttribute(
+ IMarker.CHAR_START, 0), marker.getAttribute(
+ IMarker.CHAR_END, 0)));
+ resolutions.add(new ReplaceResourceBundleDefReference(marker
+ .getAttribute("key", ""), marker.getAttribute(
+ IMarker.CHAR_START, 0), marker.getAttribute(
+ IMarker.CHAR_END, 0)));
+ }
+
+ return resolutions;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java
index 0228b0e3..d0694fa5 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/MethodParameterDescriptor.java
@@ -1,50 +1,57 @@
-package org.eclipse.babel.tapiji.tools.java.auditor;
-
-import java.util.List;
-
-public class MethodParameterDescriptor {
-
- private List<String> methodName;
- private String declaringClass;
- private boolean considerSuperclass;
- private int position;
-
- public MethodParameterDescriptor(List<String> methodName, String declaringClass,
- boolean considerSuperclass, int position) {
- super();
- this.setMethodName(methodName);
- this.declaringClass = declaringClass;
- this.considerSuperclass = considerSuperclass;
- this.position = position;
- }
-
- public String getDeclaringClass() {
- return declaringClass;
- }
- public void setDeclaringClass(String declaringClass) {
- this.declaringClass = declaringClass;
- }
- public boolean isConsiderSuperclass() {
- return considerSuperclass;
- }
- public void setConsiderSuperclass(boolean considerSuperclass) {
- this.considerSuperclass = considerSuperclass;
- }
- public int getPosition() {
- return position;
- }
- public void setPosition(int position) {
- this.position = position;
- }
-
- public void setMethodName(List<String> methodName) {
- this.methodName = methodName;
- }
-
- public List<String> getMethodName() {
- return methodName;
- }
-
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.auditor;
+
+import java.util.List;
+
+public class MethodParameterDescriptor {
+
+ private List<String> methodName;
+ private String declaringClass;
+ private boolean considerSuperclass;
+ private int position;
+
+ public MethodParameterDescriptor(List<String> methodName, String declaringClass,
+ boolean considerSuperclass, int position) {
+ super();
+ this.setMethodName(methodName);
+ this.declaringClass = declaringClass;
+ this.considerSuperclass = considerSuperclass;
+ this.position = position;
+ }
+
+ public String getDeclaringClass() {
+ return declaringClass;
+ }
+ public void setDeclaringClass(String declaringClass) {
+ this.declaringClass = declaringClass;
+ }
+ public boolean isConsiderSuperclass() {
+ return considerSuperclass;
+ }
+ public void setConsiderSuperclass(boolean considerSuperclass) {
+ this.considerSuperclass = considerSuperclass;
+ }
+ public int getPosition() {
+ return position;
+ }
+ public void setPosition(int position) {
+ this.position = position;
+ }
+
+ public void setMethodName(List<String> methodName) {
+ this.methodName = methodName;
+ }
+
+ public List<String> getMethodName() {
+ return methodName;
+ }
+
+
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java
index d810474e..43659d4b 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/ResourceAuditVisitor.java
@@ -1,241 +1,248 @@
-package org.eclipse.babel.tapiji.tools.java.auditor;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation;
-import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.core.dom.ASTVisitor;
-import org.eclipse.jdt.core.dom.FieldDeclaration;
-import org.eclipse.jdt.core.dom.IVariableBinding;
-import org.eclipse.jdt.core.dom.MethodInvocation;
-import org.eclipse.jdt.core.dom.StringLiteral;
-import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-
-/**
- * @author Martin
- *
- */
-public class ResourceAuditVisitor extends ASTVisitor implements
- IResourceVisitor {
-
- private List<SLLocation> constants;
- private List<SLLocation> brokenStrings;
- private List<SLLocation> brokenRBReferences;
- private SortedMap<Long, IRegion> rbDefReferences = new TreeMap<Long, IRegion>();
- private SortedMap<Long, IRegion> keyPositions = new TreeMap<Long, IRegion>();
- private Map<IRegion, String> bundleKeys = new HashMap<IRegion, String>();
- private Map<IRegion, String> bundleReferences = new HashMap<IRegion, String>();
- private IFile file;
- private Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers = new HashMap<IVariableBinding, VariableDeclarationFragment>();
- private String projectName;
-
-
- public ResourceAuditVisitor(IFile file, String projectName) {
- constants = new ArrayList<SLLocation>();
- brokenStrings = new ArrayList<SLLocation>();
- brokenRBReferences = new ArrayList<SLLocation>();
- this.file = file;
- this.projectName = projectName;
- }
-
- @Override
- public boolean visit(VariableDeclarationStatement varDeclaration) {
- for (Iterator<VariableDeclarationFragment> itFrag = varDeclaration
- .fragments().iterator(); itFrag.hasNext();) {
- VariableDeclarationFragment fragment = itFrag.next();
- parseVariableDeclarationFragment(fragment);
- }
- return true;
- }
-
- @Override
- public boolean visit(FieldDeclaration fieldDeclaration) {
- for (Iterator<VariableDeclarationFragment> itFrag = fieldDeclaration
- .fragments().iterator(); itFrag.hasNext();) {
- VariableDeclarationFragment fragment = itFrag.next();
- parseVariableDeclarationFragment(fragment);
- }
- return true;
- }
-
- protected void parseVariableDeclarationFragment(
- VariableDeclarationFragment fragment) {
- IVariableBinding vBinding = fragment.resolveBinding();
- this.variableBindingManagers.put(vBinding, fragment);
- }
-
- @Override
- public boolean visit(StringLiteral stringLiteral) {
- try {
- ASTNode parent = stringLiteral.getParent();
- ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
-
- if (parent instanceof MethodInvocation) {
- MethodInvocation methodInvocation = (MethodInvocation) parent;
-
- IRegion region = new Region(stringLiteral.getStartPosition(),
- stringLiteral.getLength());
-
- // Check if this method invokes the getString-Method on a
- // ResourceBundle Implementation
- if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
- stringLiteral, ASTutils.getRBAccessorDesc())) {
- // Check if the given Resource-Bundle reference is broken
- SLLocation rbName = ASTutils.resolveResourceBundleLocation(
- methodInvocation, ASTutils.getRBDefinitionDesc(),
- variableBindingManagers);
- if (rbName == null
- || manager.isKeyBroken(rbName.getLiteral(),
- stringLiteral.getLiteralValue())) {
- // report new problem
- SLLocation desc = new SLLocation(file,
- stringLiteral.getStartPosition(),
- stringLiteral.getStartPosition()
- + stringLiteral.getLength(),
- stringLiteral.getLiteralValue());
- desc.setData(rbName);
- brokenStrings.add(desc);
- }
-
- // store position of resource-bundle access
- keyPositions.put(
- Long.valueOf(stringLiteral.getStartPosition()),
- region);
- bundleKeys.put(region, stringLiteral.getLiteralValue());
- bundleReferences.put(region, rbName.getLiteral());
- return false;
- } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
- stringLiteral, ASTutils.getRBDefinitionDesc())) {
- rbDefReferences.put(
- Long.valueOf(stringLiteral.getStartPosition()),
- region);
- boolean referenceBroken = true;
- for (String bundle : manager.getResourceBundleIdentifiers()) {
- if (bundle.trim().equals(
- stringLiteral.getLiteralValue())) {
- referenceBroken = false;
- }
- }
- if (referenceBroken) {
- this.brokenRBReferences.add(new SLLocation(file,
- stringLiteral.getStartPosition(), stringLiteral
- .getStartPosition()
- + stringLiteral.getLength(),
- stringLiteral.getLiteralValue()));
- }
-
- return false;
- }
- }
-
- // check if string is followed by a "$NON-NLS$" line comment
- if (ASTutils.existsNonInternationalisationComment(stringLiteral)) {
- return false;
- }
-
- // constant string literal found
- constants.add(new SLLocation(file,
- stringLiteral.getStartPosition(), stringLiteral
- .getStartPosition() + stringLiteral.getLength(),
- stringLiteral.getLiteralValue()));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
- }
-
- public List<SLLocation> getConstantStringLiterals() {
- return constants;
- }
-
- public List<SLLocation> getBrokenResourceReferences() {
- return brokenStrings;
- }
-
- public List<SLLocation> getBrokenRBReferences() {
- return this.brokenRBReferences;
- }
-
- public IRegion getKeyAt(Long position) {
- IRegion reg = null;
-
- Iterator<Long> keys = keyPositions.keySet().iterator();
- while (keys.hasNext()) {
- Long startPos = keys.next();
- if (startPos > position)
- break;
-
- IRegion region = keyPositions.get(startPos);
- if (region.getOffset() <= position
- && (region.getOffset() + region.getLength()) >= position) {
- reg = region;
- break;
- }
- }
-
- return reg;
- }
-
- public String getKeyAt(IRegion region) {
- if (bundleKeys.containsKey(region))
- return bundleKeys.get(region);
- else
- return "";
- }
-
- public String getBundleReference(IRegion region) {
- return bundleReferences.get(region);
- }
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- // TODO Auto-generated method stub
- return false;
- }
-
- public Collection<String> getDefinedResourceBundles(int offset) {
- Collection<String> result = new HashSet<String>();
- for (String s : bundleReferences.values()) {
- if (s != null)
- result.add(s);
- }
- return result;
- }
-
- public IRegion getRBReferenceAt(Long offset) {
- IRegion reg = null;
-
- Iterator<Long> keys = rbDefReferences.keySet().iterator();
- while (keys.hasNext()) {
- Long startPos = keys.next();
- if (startPos > offset)
- break;
-
- IRegion region = rbDefReferences.get(startPos);
- if (region != null && region.getOffset() <= offset
- && (region.getOffset() + region.getLength()) >= offset) {
- reg = region;
- break;
- }
- }
-
- return reg;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.auditor;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceVisitor;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jdt.core.dom.ASTNode;
+import org.eclipse.jdt.core.dom.ASTVisitor;
+import org.eclipse.jdt.core.dom.FieldDeclaration;
+import org.eclipse.jdt.core.dom.IVariableBinding;
+import org.eclipse.jdt.core.dom.MethodInvocation;
+import org.eclipse.jdt.core.dom.StringLiteral;
+import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
+import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.Region;
+
+/**
+ * @author Martin
+ *
+ */
+public class ResourceAuditVisitor extends ASTVisitor implements
+ IResourceVisitor {
+
+ private List<SLLocation> constants;
+ private List<SLLocation> brokenStrings;
+ private List<SLLocation> brokenRBReferences;
+ private SortedMap<Long, IRegion> rbDefReferences = new TreeMap<Long, IRegion>();
+ private SortedMap<Long, IRegion> keyPositions = new TreeMap<Long, IRegion>();
+ private Map<IRegion, String> bundleKeys = new HashMap<IRegion, String>();
+ private Map<IRegion, String> bundleReferences = new HashMap<IRegion, String>();
+ private IFile file;
+ private Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers = new HashMap<IVariableBinding, VariableDeclarationFragment>();
+ private String projectName;
+
+
+ public ResourceAuditVisitor(IFile file, String projectName) {
+ constants = new ArrayList<SLLocation>();
+ brokenStrings = new ArrayList<SLLocation>();
+ brokenRBReferences = new ArrayList<SLLocation>();
+ this.file = file;
+ this.projectName = projectName;
+ }
+
+ @Override
+ public boolean visit(VariableDeclarationStatement varDeclaration) {
+ for (Iterator<VariableDeclarationFragment> itFrag = varDeclaration
+ .fragments().iterator(); itFrag.hasNext();) {
+ VariableDeclarationFragment fragment = itFrag.next();
+ parseVariableDeclarationFragment(fragment);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean visit(FieldDeclaration fieldDeclaration) {
+ for (Iterator<VariableDeclarationFragment> itFrag = fieldDeclaration
+ .fragments().iterator(); itFrag.hasNext();) {
+ VariableDeclarationFragment fragment = itFrag.next();
+ parseVariableDeclarationFragment(fragment);
+ }
+ return true;
+ }
+
+ protected void parseVariableDeclarationFragment(
+ VariableDeclarationFragment fragment) {
+ IVariableBinding vBinding = fragment.resolveBinding();
+ this.variableBindingManagers.put(vBinding, fragment);
+ }
+
+ @Override
+ public boolean visit(StringLiteral stringLiteral) {
+ try {
+ ASTNode parent = stringLiteral.getParent();
+ ResourceBundleManager manager = ResourceBundleManager.getManager(projectName);
+
+ if (parent instanceof MethodInvocation) {
+ MethodInvocation methodInvocation = (MethodInvocation) parent;
+
+ IRegion region = new Region(stringLiteral.getStartPosition(),
+ stringLiteral.getLength());
+
+ // Check if this method invokes the getString-Method on a
+ // ResourceBundle Implementation
+ if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
+ stringLiteral, ASTutils.getRBAccessorDesc())) {
+ // Check if the given Resource-Bundle reference is broken
+ SLLocation rbName = ASTutils.resolveResourceBundleLocation(
+ methodInvocation, ASTutils.getRBDefinitionDesc(),
+ variableBindingManagers);
+ if (rbName == null
+ || manager.isKeyBroken(rbName.getLiteral(),
+ stringLiteral.getLiteralValue())) {
+ // report new problem
+ SLLocation desc = new SLLocation(file,
+ stringLiteral.getStartPosition(),
+ stringLiteral.getStartPosition()
+ + stringLiteral.getLength(),
+ stringLiteral.getLiteralValue());
+ desc.setData(rbName);
+ brokenStrings.add(desc);
+ }
+
+ // store position of resource-bundle access
+ keyPositions.put(
+ Long.valueOf(stringLiteral.getStartPosition()),
+ region);
+ bundleKeys.put(region, stringLiteral.getLiteralValue());
+ bundleReferences.put(region, rbName.getLiteral());
+ return false;
+ } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation,
+ stringLiteral, ASTutils.getRBDefinitionDesc())) {
+ rbDefReferences.put(
+ Long.valueOf(stringLiteral.getStartPosition()),
+ region);
+ boolean referenceBroken = true;
+ for (String bundle : manager.getResourceBundleIdentifiers()) {
+ if (bundle.trim().equals(
+ stringLiteral.getLiteralValue())) {
+ referenceBroken = false;
+ }
+ }
+ if (referenceBroken) {
+ this.brokenRBReferences.add(new SLLocation(file,
+ stringLiteral.getStartPosition(), stringLiteral
+ .getStartPosition()
+ + stringLiteral.getLength(),
+ stringLiteral.getLiteralValue()));
+ }
+
+ return false;
+ }
+ }
+
+ // check if string is followed by a "$NON-NLS$" line comment
+ if (ASTutils.existsNonInternationalisationComment(stringLiteral)) {
+ return false;
+ }
+
+ // constant string literal found
+ constants.add(new SLLocation(file,
+ stringLiteral.getStartPosition(), stringLiteral
+ .getStartPosition() + stringLiteral.getLength(),
+ stringLiteral.getLiteralValue()));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return false;
+ }
+
+ public List<SLLocation> getConstantStringLiterals() {
+ return constants;
+ }
+
+ public List<SLLocation> getBrokenResourceReferences() {
+ return brokenStrings;
+ }
+
+ public List<SLLocation> getBrokenRBReferences() {
+ return this.brokenRBReferences;
+ }
+
+ public IRegion getKeyAt(Long position) {
+ IRegion reg = null;
+
+ Iterator<Long> keys = keyPositions.keySet().iterator();
+ while (keys.hasNext()) {
+ Long startPos = keys.next();
+ if (startPos > position)
+ break;
+
+ IRegion region = keyPositions.get(startPos);
+ if (region.getOffset() <= position
+ && (region.getOffset() + region.getLength()) >= position) {
+ reg = region;
+ break;
+ }
+ }
+
+ return reg;
+ }
+
+ public String getKeyAt(IRegion region) {
+ if (bundleKeys.containsKey(region))
+ return bundleKeys.get(region);
+ else
+ return "";
+ }
+
+ public String getBundleReference(IRegion region) {
+ return bundleReferences.get(region);
+ }
+
+ @Override
+ public boolean visit(IResource resource) throws CoreException {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public Collection<String> getDefinedResourceBundles(int offset) {
+ Collection<String> result = new HashSet<String>();
+ for (String s : bundleReferences.values()) {
+ if (s != null)
+ result.add(s);
+ }
+ return result;
+ }
+
+ public IRegion getRBReferenceAt(Long offset) {
+ IRegion reg = null;
+
+ Iterator<Long> keys = rbDefReferences.keySet().iterator();
+ while (keys.hasNext()) {
+ Long startPos = keys.next();
+ if (startPos > offset)
+ break;
+
+ IRegion region = rbDefReferences.get(startPos);
+ if (region != null && region.getOffset() <= offset
+ && (region.getOffset() + region.getLength()) >= offset) {
+ reg = region;
+ break;
+ }
+ }
+
+ return reg;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/model/SLLocation.java
index 9618f9c4..809b3b9e 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/model/SLLocation.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/auditor/model/SLLocation.java
@@ -1,53 +1,60 @@
-package org.eclipse.babel.tapiji.tools.java.auditor.model;
-
-import java.io.Serializable;
-
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.core.resources.IFile;
-
-
-public class SLLocation implements Serializable, ILocation {
-
- private static final long serialVersionUID = 1L;
- private IFile file = null;
- private int startPos = -1;
- private int endPos = -1;
- private String literal;
- private Serializable data;
-
- public SLLocation(IFile file, int startPos, int endPos, String literal) {
- super();
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.literal = literal;
- }
- public IFile getFile() {
- return file;
- }
- public void setFile(IFile file) {
- this.file = file;
- }
- public int getStartPos() {
- return startPos;
- }
- public void setStartPos(int startPos) {
- this.startPos = startPos;
- }
- public int getEndPos() {
- return endPos;
- }
- public void setEndPos(int endPos) {
- this.endPos = endPos;
- }
- public String getLiteral() {
- return literal;
- }
- public Serializable getData () {
- return data;
- }
- public void setData (Serializable data) {
- this.data = data;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.auditor.model;
+
+import java.io.Serializable;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IFile;
+
+
+public class SLLocation implements Serializable, ILocation {
+
+ private static final long serialVersionUID = 1L;
+ private IFile file = null;
+ private int startPos = -1;
+ private int endPos = -1;
+ private String literal;
+ private Serializable data;
+
+ public SLLocation(IFile file, int startPos, int endPos, String literal) {
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.literal = literal;
+ }
+ public IFile getFile() {
+ return file;
+ }
+ public void setFile(IFile file) {
+ this.file = file;
+ }
+ public int getStartPos() {
+ return startPos;
+ }
+ public void setStartPos(int startPos) {
+ this.startPos = startPos;
+ }
+ public int getEndPos() {
+ return endPos;
+ }
+ public void setEndPos(int endPos) {
+ this.endPos = endPos;
+ }
+ public String getLiteral() {
+ return literal;
+ }
+ public Serializable getData () {
+ return data;
+ }
+ public void setData (Serializable data) {
+ this.data = data;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java
index 7db4fca7..367a27db 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExcludeResourceFromInternationalization.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipse.babel.tapiji.tools.java.quickfix;
import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java
index 0d87bf5b..d2dc9a36 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ExportToResourceBundleResolution.java
@@ -1,90 +1,97 @@
-package org.eclipse.babel.tapiji.tools.java.quickfix;
-
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
-import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-
-
-public class ExportToResourceBundleResolution implements IMarkerResolution2 {
-
- public ExportToResourceBundleResolution () {}
-
- @Override
- public String getDescription() {
- return "Export constant string literal to a resource bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Export to Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey("");
- config.setPreselectedMessage("");
- config.setPreselectedBundle((startPos+1 < document.getLength() && endPos > 1) ? document.get(startPos+1, endPos-2) : "");
- config.setPreselectedLocale("");
- config.setProjectName(resource.getProject().getName());
-
- dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- ASTutils.insertNewBundleRef(document,
- resource,
- startPos,
- endPos,
- dialog.getSelectedResourceBundle(),
- dialog.getSelectedKey());
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
-
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+
+public class ExportToResourceBundleResolution implements IMarkerResolution2 {
+
+ public ExportToResourceBundleResolution () {}
+
+ @Override
+ public String getDescription() {
+ return "Export constant string literal to a resource bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Export to Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey("");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle((startPos+1 < document.getLength() && endPos > 1) ? document.get(startPos+1, endPos-2) : "");
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ ASTutils.insertNewBundleRef(document,
+ resource,
+ startPos,
+ endPos,
+ dialog.getSelectedResourceBundle(),
+ dialog.getSelectedKey());
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java
index 95439ba8..3343d261 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/IgnoreStringFromInternationalization.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipse.babel.tapiji.tools.java.quickfix;
import org.eclipse.babel.tapiji.tools.core.Logger;
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java
index fe01d5f4..606ac47e 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleDefReference.java
@@ -1,86 +1,93 @@
-package org.eclipse.babel.tapiji.tools.java.quickfix;
-
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-
-
-public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
-
- private String key;
- private int start;
- private int end;
-
- public ReplaceResourceBundleDefReference(String key, int start, int end) {
- this.key = key;
- this.start = start;
- this.end = end;
- }
-
- @Override
- public String getDescription() {
- return "Replaces the non-existing Resource-Bundle reference '"
- + key
- + "' with a reference to an already existing Resource-Bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Select an alternative Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = start;
- int endPos = end-start;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(Display.getDefault().getActiveShell(),
- resource.getProject());
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- key = dialog.getSelectedBundleId();
- int iSep = key.lastIndexOf("/");
- key = iSep != -1 ? key.substring(iSep+1) : key;
-
- document.replace(startPos, endPos, "\"" + key + "\"");
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+
+public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
+
+ private String key;
+ private int start;
+ private int end;
+
+ public ReplaceResourceBundleDefReference(String key, int start, int end) {
+ this.key = key;
+ this.start = start;
+ this.end = end;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Replaces the non-existing Resource-Bundle reference '"
+ + key
+ + "' with a reference to an already existing Resource-Bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Select an alternative Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = start;
+ int endPos = end-start;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(Display.getDefault().getActiveShell(),
+ resource.getProject());
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ key = dialog.getSelectedBundleId();
+ int iSep = key.lastIndexOf("/");
+ key = iSep != -1 ? key.substring(iSep+1) : key;
+
+ document.replace(startPos, endPos, "\"" + key + "\"");
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java
index 291aa1aa..ca351e26 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/quickfix/ReplaceResourceBundleReference.java
@@ -1,87 +1,94 @@
-package org.eclipse.babel.tapiji.tools.java.quickfix;
-
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-
-
-public class ReplaceResourceBundleReference implements IMarkerResolution2 {
-
- private String key;
- private String bundleId;
-
- public ReplaceResourceBundleReference(String key, String bundleId) {
- this.key = key;
- this.bundleId = bundleId;
- }
-
- @Override
- public String getDescription() {
- return "Replaces the non-existing Resource-Bundle key '"
- + key
- + "' with a reference to an already existing localized string literal.";
- }
-
- @Override
- public Image getImage() {
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Select alternative Resource-Bundle entry";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell());
-
- dialog.setProjectName(resource.getProject().getName());
- dialog.setBundleName(bundleId);
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- String key = dialog.getSelectedResource();
- Locale locale = dialog.getSelectedLocale();
-
- document.replace(startPos, endPos, "\"" + key + "\"");
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.quickfix;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+
+public class ReplaceResourceBundleReference implements IMarkerResolution2 {
+
+ private String key;
+ private String bundleId;
+
+ public ReplaceResourceBundleReference(String key, String bundleId) {
+ this.key = key;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Replaces the non-existing Resource-Bundle key '"
+ + key
+ + "' with a reference to an already existing localized string literal.";
+ }
+
+ @Override
+ public Image getImage() {
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Select alternative Resource-Bundle entry";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
+ Display.getDefault().getActiveShell());
+
+ dialog.setProjectName(resource.getProject().getName());
+ dialog.setBundleName(bundleId);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ String key = dialog.getSelectedResource();
+ Locale locale = dialog.getSelectedLocale();
+
+ document.replace(startPos, endPos, "\"" + key + "\"");
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, LocationKind.NORMALIZE, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java
index 7fc46a03..0cfbe071 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java
@@ -1,82 +1,89 @@
-package org.eclipse.babel.tapiji.tools.java.ui;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.java.auditor.ResourceAuditVisitor;
-import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
-import org.eclipse.jdt.core.ITypeRoot;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.ui.IEditorPart;
-
-
-public class ConstantStringHover implements IJavaEditorTextHover {
-
- IEditorPart editor = null;
- ResourceAuditVisitor csf = null;
- ResourceBundleManager manager = null;
-
- @Override
- public void setEditor(IEditorPart editor) {
- this.editor = editor;
- initConstantStringAuditor();
- }
-
- protected void initConstantStringAuditor () {
- // parse editor content and extract resource-bundle access strings
-
- // get the type of the currently loaded resource
- ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor
- .getEditorInput());
-
- if (typeRoot == null)
- return;
-
- CompilationUnit cu = ASTutils.getCompilationUnit(typeRoot);
-
- if (cu == null)
- return;
-
- manager = ResourceBundleManager.getManager(
- cu.getJavaElement().getResource().getProject()
- );
-
- // determine the element at the position of the cursur
- csf = new ResourceAuditVisitor(null, manager.getProject().getName());
- cu.accept(csf);
- }
-
- @Override
- public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
- initConstantStringAuditor();
- if (hoverRegion == null)
- return null;
-
- // get region for string literals
- hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset());
-
- if (hoverRegion == null)
- return null;
-
- String bundleName = csf.getBundleReference(hoverRegion);
- String key = csf.getKeyAt(hoverRegion);
-
- String hoverText = manager.getKeyHoverString(bundleName, key);
- if (hoverText == null || hoverText.equals(""))
- return null;
- else
- return hoverText;
- }
-
- @Override
- public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
- if (editor == null)
- return null;
-
- // Retrieve the property key at this position. Otherwise, null is returned.
- return csf.getKeyAt(Long.valueOf(offset));
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.java.auditor.ResourceAuditVisitor;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.jdt.core.ITypeRoot;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.ui.JavaUI;
+import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.ui.IEditorPart;
+
+
+public class ConstantStringHover implements IJavaEditorTextHover {
+
+ IEditorPart editor = null;
+ ResourceAuditVisitor csf = null;
+ ResourceBundleManager manager = null;
+
+ @Override
+ public void setEditor(IEditorPart editor) {
+ this.editor = editor;
+ initConstantStringAuditor();
+ }
+
+ protected void initConstantStringAuditor () {
+ // parse editor content and extract resource-bundle access strings
+
+ // get the type of the currently loaded resource
+ ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor
+ .getEditorInput());
+
+ if (typeRoot == null)
+ return;
+
+ CompilationUnit cu = ASTutils.getCompilationUnit(typeRoot);
+
+ if (cu == null)
+ return;
+
+ manager = ResourceBundleManager.getManager(
+ cu.getJavaElement().getResource().getProject()
+ );
+
+ // determine the element at the position of the cursur
+ csf = new ResourceAuditVisitor(null, manager.getProject().getName());
+ cu.accept(csf);
+ }
+
+ @Override
+ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
+ initConstantStringAuditor();
+ if (hoverRegion == null)
+ return null;
+
+ // get region for string literals
+ hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset());
+
+ if (hoverRegion == null)
+ return null;
+
+ String bundleName = csf.getBundleReference(hoverRegion);
+ String key = csf.getKeyAt(hoverRegion);
+
+ String hoverText = manager.getKeyHoverString(bundleName, key);
+ if (hoverText == null || hoverText.equals(""))
+ return null;
+ else
+ return hoverText;
+ }
+
+ @Override
+ public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
+ if (editor == null)
+ return null;
+
+ // Retrieve the property key at this position. Otherwise, null is returned.
+ return csf.getKeyAt(Long.valueOf(offset));
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java
index b2069088..571b1060 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java
@@ -1,236 +1,243 @@
-package org.eclipse.babel.tapiji.tools.java.ui;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.java.auditor.ResourceAuditVisitor;
-import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.CreateResourceBundleProposal;
-import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.InsertResourceBundleReferenceProposal;
-import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.MessageCompletionProposal;
-import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.NewResourceBundleEntryProposal;
-import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.NoActionProposal;
-import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jdt.core.CompletionContext;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposalComputer;
-import org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-
-public class MessageCompletionProposalComputer implements
- IJavaCompletionProposalComputer {
-
- private ResourceAuditVisitor csav;
- private IResource resource;
- private CompilationUnit cu;
- private ResourceBundleManager manager;
-
- public MessageCompletionProposalComputer() {
-
- }
-
- @Override
- public List<ICompletionProposal> computeCompletionProposals(
- ContentAssistInvocationContext context, IProgressMonitor monitor) {
-
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
-
- if (!InternationalizationNature
- .hasNature(((JavaContentAssistInvocationContext) context)
- .getCompilationUnit().getResource().getProject()))
- return completions;
-
- try {
- JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context);
- CompletionContext coreContext = javaContext.getCoreContext();
-
- int tokenStart = coreContext.getTokenStart();
- int tokenEnd = coreContext.getTokenEnd();
- int tokenOffset = coreContext.getOffset();
- boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL;
-
- if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME
- && (tokenEnd + 1) - tokenStart > 0)
- return completions;
-
- if (isStringLiteral)
- tokenStart++;
-
- if (tokenStart < 0) {
- tokenStart = tokenOffset;
- tokenEnd = tokenOffset;
- }
-
- tokenEnd = Math.max(tokenEnd, tokenStart);
-
- String fullToken = "";
-
- if (tokenStart < tokenEnd)
- fullToken = context.getDocument().get(tokenStart,
- tokenEnd - tokenStart);
-
- // Check if the string literal is up to be written within the
- // context of a resource-bundle accessor method
-
- if (cu == null) {
- manager = ResourceBundleManager.getManager(javaContext
- .getCompilationUnit().getResource().getProject());
-
- resource = javaContext.getCompilationUnit().getResource();
-
- csav = new ResourceAuditVisitor(null, manager.getProject().getName());
-
- cu = ASTutils.getCompilationUnit(resource);
-
- cu.accept(csav);
- }
-
- if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) {
- completions.addAll(getResourceBundleCompletionProposals(
- tokenStart, tokenEnd, tokenOffset, isStringLiteral,
- fullToken, manager, csav, resource));
- } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null
- && isStringLiteral) {
- completions.addAll(getRBReferenceCompletionProposals(
- tokenStart, tokenEnd, fullToken, isStringLiteral,
- manager, resource));
- } else {
- completions.addAll(getBasicJavaCompletionProposals(tokenStart,
- tokenEnd, tokenOffset, fullToken, isStringLiteral,
- manager, csav, resource));
- }
- if (completions.size() == 1)
- completions.add(new NoActionProposal());
-
- } catch (Exception e) {
- Logger.logError(e);
- }
- return completions;
- }
-
- private Collection<ICompletionProposal> getRBReferenceCompletionProposals(
- int tokenStart, int tokenEnd, String fullToken,
- boolean isStringLiteral, ResourceBundleManager manager,
- IResource resource) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
- boolean hit = false;
-
- // Show a list of available resource bundles
- List<String> resourceBundles = manager.getResourceBundleIdentifiers();
- for (String rbName : resourceBundles) {
- if (rbName.startsWith(fullToken)) {
- if (rbName.equals(fullToken))
- hit = true;
- else
- completions.add(new MessageCompletionProposal(tokenStart,
- tokenEnd - tokenStart, rbName, true));
- }
- }
-
- if (!hit && fullToken.trim().length() > 0)
- completions.add(new CreateResourceBundleProposal(fullToken,
- resource, tokenStart, tokenEnd));
-
- return completions;
- }
-
- protected List<ICompletionProposal> getBasicJavaCompletionProposals(
- int tokenStart, int tokenEnd, int tokenOffset, String fullToken,
- boolean isStringLiteral, ResourceBundleManager manager,
- ResourceAuditVisitor csav, IResource resource) {
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
-
- if (fullToken.length() == 0) {
- // If nothing has been entered
- completions.add(new InsertResourceBundleReferenceProposal(
- tokenStart, tokenEnd - tokenStart, manager.getProject().getName(), resource, csav
- .getDefinedResourceBundles(tokenOffset)));
- completions.add(new NewResourceBundleEntryProposal(resource,
- tokenStart, tokenEnd, fullToken, isStringLiteral, false,
- manager.getProject().getName(), null));
- } else {
- completions.add(new NewResourceBundleEntryProposal(resource,
- tokenStart, tokenEnd, fullToken, isStringLiteral, false,
- manager.getProject().getName(), null));
- }
- return completions;
- }
-
- protected List<ICompletionProposal> getResourceBundleCompletionProposals(
- int tokenStart, int tokenEnd, int tokenOffset,
- boolean isStringLiteral, String fullToken,
- ResourceBundleManager manager, ResourceAuditVisitor csav,
- IResource resource) {
-
- List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
- IRegion region = csav.getKeyAt(new Long(tokenOffset));
- String bundleName = csav.getBundleReference(region);
- IMessagesBundleGroup bundleGroup = manager
- .getResourceBundle(bundleName);
-
- if (fullToken.length() > 0) {
- boolean hit = false;
- // If a part of a String has already been entered
- for (String key : bundleGroup.getMessageKeys()) {
- if (key.toLowerCase().startsWith(fullToken)) {
- if (!key.equals(fullToken))
- completions.add(new MessageCompletionProposal(
- tokenStart, tokenEnd - tokenStart, key, false));
- else
- hit = true;
- }
- }
- if (!hit) {
- completions.add(new NewResourceBundleEntryProposal(resource,
- tokenStart, tokenEnd, fullToken, isStringLiteral, true,
- manager.getProject().getName(), bundleName));
-
- // TODO: reference to existing resource
- }
- } else {
- for (String key : bundleGroup.getMessageKeys()) {
- completions.add(new MessageCompletionProposal(tokenStart,
- tokenEnd - tokenStart, key, false));
- }
- completions.add(new NewResourceBundleEntryProposal(resource,
- tokenStart, tokenEnd, fullToken, isStringLiteral, true,
- manager.getProject().getName(), bundleName));
-
- }
- return completions;
- }
-
- @Override
- public List computeContextInformation(
- ContentAssistInvocationContext context, IProgressMonitor monitor) {
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- // TODO Auto-generated method stub
- return "";
- }
-
- @Override
- public void sessionEnded() {
- cu = null;
- csav = null;
- resource = null;
- manager = null;
- }
-
- @Override
- public void sessionStarted() {
-
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.java.auditor.ResourceAuditVisitor;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.CreateResourceBundleProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.InsertResourceBundleReferenceProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.MessageCompletionProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.NewResourceBundleEntryProposal;
+import org.eclipse.babel.tapiji.tools.java.ui.autocompletion.NoActionProposal;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jdt.core.CompletionContext;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposalComputer;
+import org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+
+public class MessageCompletionProposalComputer implements
+ IJavaCompletionProposalComputer {
+
+ private ResourceAuditVisitor csav;
+ private IResource resource;
+ private CompilationUnit cu;
+ private ResourceBundleManager manager;
+
+ public MessageCompletionProposalComputer() {
+
+ }
+
+ @Override
+ public List<ICompletionProposal> computeCompletionProposals(
+ ContentAssistInvocationContext context, IProgressMonitor monitor) {
+
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+
+ if (!InternationalizationNature
+ .hasNature(((JavaContentAssistInvocationContext) context)
+ .getCompilationUnit().getResource().getProject()))
+ return completions;
+
+ try {
+ JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context);
+ CompletionContext coreContext = javaContext.getCoreContext();
+
+ int tokenStart = coreContext.getTokenStart();
+ int tokenEnd = coreContext.getTokenEnd();
+ int tokenOffset = coreContext.getOffset();
+ boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL;
+
+ if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME
+ && (tokenEnd + 1) - tokenStart > 0)
+ return completions;
+
+ if (isStringLiteral)
+ tokenStart++;
+
+ if (tokenStart < 0) {
+ tokenStart = tokenOffset;
+ tokenEnd = tokenOffset;
+ }
+
+ tokenEnd = Math.max(tokenEnd, tokenStart);
+
+ String fullToken = "";
+
+ if (tokenStart < tokenEnd)
+ fullToken = context.getDocument().get(tokenStart,
+ tokenEnd - tokenStart);
+
+ // Check if the string literal is up to be written within the
+ // context of a resource-bundle accessor method
+
+ if (cu == null) {
+ manager = ResourceBundleManager.getManager(javaContext
+ .getCompilationUnit().getResource().getProject());
+
+ resource = javaContext.getCompilationUnit().getResource();
+
+ csav = new ResourceAuditVisitor(null, manager.getProject().getName());
+
+ cu = ASTutils.getCompilationUnit(resource);
+
+ cu.accept(csav);
+ }
+
+ if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) {
+ completions.addAll(getResourceBundleCompletionProposals(
+ tokenStart, tokenEnd, tokenOffset, isStringLiteral,
+ fullToken, manager, csav, resource));
+ } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null
+ && isStringLiteral) {
+ completions.addAll(getRBReferenceCompletionProposals(
+ tokenStart, tokenEnd, fullToken, isStringLiteral,
+ manager, resource));
+ } else {
+ completions.addAll(getBasicJavaCompletionProposals(tokenStart,
+ tokenEnd, tokenOffset, fullToken, isStringLiteral,
+ manager, csav, resource));
+ }
+ if (completions.size() == 1)
+ completions.add(new NoActionProposal());
+
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ return completions;
+ }
+
+ private Collection<ICompletionProposal> getRBReferenceCompletionProposals(
+ int tokenStart, int tokenEnd, String fullToken,
+ boolean isStringLiteral, ResourceBundleManager manager,
+ IResource resource) {
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+ boolean hit = false;
+
+ // Show a list of available resource bundles
+ List<String> resourceBundles = manager.getResourceBundleIdentifiers();
+ for (String rbName : resourceBundles) {
+ if (rbName.startsWith(fullToken)) {
+ if (rbName.equals(fullToken))
+ hit = true;
+ else
+ completions.add(new MessageCompletionProposal(tokenStart,
+ tokenEnd - tokenStart, rbName, true));
+ }
+ }
+
+ if (!hit && fullToken.trim().length() > 0)
+ completions.add(new CreateResourceBundleProposal(fullToken,
+ resource, tokenStart, tokenEnd));
+
+ return completions;
+ }
+
+ protected List<ICompletionProposal> getBasicJavaCompletionProposals(
+ int tokenStart, int tokenEnd, int tokenOffset, String fullToken,
+ boolean isStringLiteral, ResourceBundleManager manager,
+ ResourceAuditVisitor csav, IResource resource) {
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+
+ if (fullToken.length() == 0) {
+ // If nothing has been entered
+ completions.add(new InsertResourceBundleReferenceProposal(
+ tokenStart, tokenEnd - tokenStart, manager.getProject().getName(), resource, csav
+ .getDefinedResourceBundles(tokenOffset)));
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, false,
+ manager.getProject().getName(), null));
+ } else {
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, false,
+ manager.getProject().getName(), null));
+ }
+ return completions;
+ }
+
+ protected List<ICompletionProposal> getResourceBundleCompletionProposals(
+ int tokenStart, int tokenEnd, int tokenOffset,
+ boolean isStringLiteral, String fullToken,
+ ResourceBundleManager manager, ResourceAuditVisitor csav,
+ IResource resource) {
+
+ List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>();
+ IRegion region = csav.getKeyAt(new Long(tokenOffset));
+ String bundleName = csav.getBundleReference(region);
+ IMessagesBundleGroup bundleGroup = manager
+ .getResourceBundle(bundleName);
+
+ if (fullToken.length() > 0) {
+ boolean hit = false;
+ // If a part of a String has already been entered
+ for (String key : bundleGroup.getMessageKeys()) {
+ if (key.toLowerCase().startsWith(fullToken)) {
+ if (!key.equals(fullToken))
+ completions.add(new MessageCompletionProposal(
+ tokenStart, tokenEnd - tokenStart, key, false));
+ else
+ hit = true;
+ }
+ }
+ if (!hit) {
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, true,
+ manager.getProject().getName(), bundleName));
+
+ // TODO: reference to existing resource
+ }
+ } else {
+ for (String key : bundleGroup.getMessageKeys()) {
+ completions.add(new MessageCompletionProposal(tokenStart,
+ tokenEnd - tokenStart, key, false));
+ }
+ completions.add(new NewResourceBundleEntryProposal(resource,
+ tokenStart, tokenEnd, fullToken, isStringLiteral, true,
+ manager.getProject().getName(), bundleName));
+
+ }
+ return completions;
+ }
+
+ @Override
+ public List computeContextInformation(
+ ContentAssistInvocationContext context, IProgressMonitor monitor) {
+ return null;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ // TODO Auto-generated method stub
+ return "";
+ }
+
+ @Override
+ public void sessionEnded() {
+ cu = null;
+ csav = null;
+ resource = null;
+ manager = null;
+ }
+
+ @Override
+ public void sessionStarted() {
+
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
index 301aac8a..e5d169a0 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java
@@ -1,211 +1,218 @@
-package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
-
-import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
-import org.eclipse.babel.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.wizard.IWizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.wizards.IWizardDescriptor;
-
-public class CreateResourceBundleProposal implements IJavaCompletionProposal {
-
- private IResource resource;
- private int start;
- private int end;
- private String key;
- private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
-
- public CreateResourceBundleProposal(String key, IResource resource,
- int start, int end) {
- this.key = ResourceUtils.deriveNonExistingRBName(key,
- ResourceBundleManager.getManager(resource.getProject()));
- this.resource = resource;
- this.start = start;
- this.end = end;
- }
-
- public String getDescription() {
- return "Creates a new Resource-Bundle with the id '" + key + "'";
- }
-
- public String getLabel() {
- return "Create Resource-Bundle '" + key + "'";
- }
-
- protected void runAction() {
- // First see if this is a "new wizard".
- IWizardDescriptor descriptor = PlatformUI.getWorkbench()
- .getNewWizardRegistry().findWizard(newBunldeWizard);
- // If not check if it is an "import wizard".
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- // Or maybe an export wizard
- if (descriptor == null) {
- descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
- .findWizard(newBunldeWizard);
- }
- try {
- // Then if we have a wizard, open it.
- if (descriptor != null) {
- IWizard wizard = descriptor.createWizard();
-
- if (!(wizard instanceof IResourceBundleWizard))
- return;
-
- IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
- String[] keySilbings = key.split("\\.");
- String rbName = keySilbings[keySilbings.length - 1];
- String packageName = "";
-
- rbw.setBundleId(rbName);
-
- // Set the default path according to the specified package name
- String pathName = "";
- if (keySilbings.length > 1) {
- try {
- IJavaProject jp = JavaCore
- .create(resource.getProject());
- packageName = key.substring(0, key.lastIndexOf("."));
-
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- IPackageFragment pf = fr
- .getPackageFragment(packageName);
- if (pf.exists()) {
- pathName = pf.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
- }
-
- try {
- IJavaProject jp = JavaCore.create(resource.getProject());
- if (pathName.trim().equals("")) {
- for (IPackageFragmentRoot fr : jp
- .getAllPackageFragmentRoots()) {
- if (!fr.isReadOnly()) {
- pathName = fr.getResource().getFullPath()
- .removeFirstSegments(0).toOSString();
- break;
- }
- }
- }
- } catch (Exception e) {
- pathName = "";
- }
-
- rbw.setDefaultPath(pathName);
-
- WizardDialog wd = new WizardDialog(Display.getDefault()
- .getActiveShell(), wizard);
-
- wd.setTitle(wizard.getWindowTitle());
- if (wd.open() == WizardDialog.OK) {
- (new I18nBuilder()).buildProject(null,
- resource.getProject());
- (new I18nBuilder()).buildResource(resource, null);
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, LocationKind.NORMALIZE,
- null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path, LocationKind.NORMALIZE);
- IDocument document = textFileBuffer.getDocument();
-
- if (document.get().charAt(start - 1) == '"'
- && document.get().charAt(start) != '"') {
- start--;
- end++;
- }
- if (document.get().charAt(end + 1) == '"'
- && document.get().charAt(end) != '"')
- end++;
-
- document.replace(start, end - start, "\""
- + (packageName.equals("") ? "" : packageName
- + ".") + rbName + "\"");
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- }
- }
- }
- }
- } catch (CoreException e) {
- }
- }
-
- @Override
- public void apply(IDocument document) {
- this.runAction();
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- return getDescription();
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return getLabel();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- @Override
- public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- if (end - start == 0)
- return 99;
- else
- return 1099;
- }
-
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.builder.I18nBuilder;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
+import org.eclipse.babel.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.filebuffers.LocationKind;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jdt.core.IJavaProject;
+import org.eclipse.jdt.core.IPackageFragment;
+import org.eclipse.jdt.core.IPackageFragmentRoot;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.wizards.IWizardDescriptor;
+
+public class CreateResourceBundleProposal implements IJavaCompletionProposal {
+
+ private IResource resource;
+ private int start;
+ private int end;
+ private String key;
+ private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard";
+
+ public CreateResourceBundleProposal(String key, IResource resource,
+ int start, int end) {
+ this.key = ResourceUtils.deriveNonExistingRBName(key,
+ ResourceBundleManager.getManager(resource.getProject()));
+ this.resource = resource;
+ this.start = start;
+ this.end = end;
+ }
+
+ public String getDescription() {
+ return "Creates a new Resource-Bundle with the id '" + key + "'";
+ }
+
+ public String getLabel() {
+ return "Create Resource-Bundle '" + key + "'";
+ }
+
+ protected void runAction() {
+ // First see if this is a "new wizard".
+ IWizardDescriptor descriptor = PlatformUI.getWorkbench()
+ .getNewWizardRegistry().findWizard(newBunldeWizard);
+ // If not check if it is an "import wizard".
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getImportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ // Or maybe an export wizard
+ if (descriptor == null) {
+ descriptor = PlatformUI.getWorkbench().getExportWizardRegistry()
+ .findWizard(newBunldeWizard);
+ }
+ try {
+ // Then if we have a wizard, open it.
+ if (descriptor != null) {
+ IWizard wizard = descriptor.createWizard();
+
+ if (!(wizard instanceof IResourceBundleWizard))
+ return;
+
+ IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
+ String[] keySilbings = key.split("\\.");
+ String rbName = keySilbings[keySilbings.length - 1];
+ String packageName = "";
+
+ rbw.setBundleId(rbName);
+
+ // Set the default path according to the specified package name
+ String pathName = "";
+ if (keySilbings.length > 1) {
+ try {
+ IJavaProject jp = JavaCore
+ .create(resource.getProject());
+ packageName = key.substring(0, key.lastIndexOf("."));
+
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ IPackageFragment pf = fr
+ .getPackageFragment(packageName);
+ if (pf.exists()) {
+ pathName = pf.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+ }
+
+ try {
+ IJavaProject jp = JavaCore.create(resource.getProject());
+ if (pathName.trim().equals("")) {
+ for (IPackageFragmentRoot fr : jp
+ .getAllPackageFragmentRoots()) {
+ if (!fr.isReadOnly()) {
+ pathName = fr.getResource().getFullPath()
+ .removeFirstSegments(0).toOSString();
+ break;
+ }
+ }
+ }
+ } catch (Exception e) {
+ pathName = "";
+ }
+
+ rbw.setDefaultPath(pathName);
+
+ WizardDialog wd = new WizardDialog(Display.getDefault()
+ .getActiveShell(), wizard);
+
+ wd.setTitle(wizard.getWindowTitle());
+ if (wd.open() == WizardDialog.OK) {
+ (new I18nBuilder()).buildProject(null,
+ resource.getProject());
+ (new I18nBuilder()).buildResource(resource, null);
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, LocationKind.NORMALIZE,
+ null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path, LocationKind.NORMALIZE);
+ IDocument document = textFileBuffer.getDocument();
+
+ if (document.get().charAt(start - 1) == '"'
+ && document.get().charAt(start) != '"') {
+ start--;
+ end++;
+ }
+ if (document.get().charAt(end + 1) == '"'
+ && document.get().charAt(end) != '"')
+ end++;
+
+ document.replace(start, end - start, "\""
+ + (packageName.equals("") ? "" : packageName
+ + ".") + rbName + "\"");
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ }
+ }
+ }
+ }
+ } catch (CoreException e) {
+ }
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ this.runAction();
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ return getDescription();
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ return getLabel();
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ return null;
+ }
+
+ @Override
+ public Image getImage() {
+ return PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
+ }
+
+ @Override
+ public int getRelevance() {
+ // TODO Auto-generated method stub
+ if (end - start == 0)
+ return 99;
+ else
+ return 1099;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java
index b3ff5f1e..9d1b942a 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java
@@ -1,91 +1,98 @@
-package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
-
-import java.util.Collection;
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
-import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-public class InsertResourceBundleReferenceProposal implements
- IJavaCompletionProposal {
-
- private int offset = 0;
- private int length = 0;
- private IResource resource;
- private String reference;
- private String projectName;
-
- public InsertResourceBundleReferenceProposal(int offset, int length,
- String projectName, IResource resource, Collection<String> availableBundles) {
- this.offset = offset;
- this.length = length;
- this.resource = resource;
- this.projectName = projectName;
- }
-
- @Override
- public void apply(IDocument document) {
- ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell());
- dialog.setProjectName(projectName);
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- String resourceBundleId = dialog.getSelectedResourceBundle();
- String key = dialog.getSelectedResource();
- Locale locale = dialog.getSelectedLocale();
-
- reference = ASTutils.insertExistingBundleRef(document, resource,
- offset, length, resourceBundleId, key, locale);
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return "Insert reference to a localized string literal";
- }
-
- @Override
- public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- int referenceLength = reference == null ? 0 : reference.length();
- return new Point(offset + referenceLength, 0);
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- if (this.length == 0)
- return 97;
- else
- return 1097;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import java.util.Collection;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+public class InsertResourceBundleReferenceProposal implements
+ IJavaCompletionProposal {
+
+ private int offset = 0;
+ private int length = 0;
+ private IResource resource;
+ private String reference;
+ private String projectName;
+
+ public InsertResourceBundleReferenceProposal(int offset, int length,
+ String projectName, IResource resource, Collection<String> availableBundles) {
+ this.offset = offset;
+ this.length = length;
+ this.resource = resource;
+ this.projectName = projectName;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
+ Display.getDefault().getActiveShell());
+ dialog.setProjectName(projectName);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ String resourceBundleId = dialog.getSelectedResourceBundle();
+ String key = dialog.getSelectedResource();
+ Locale locale = dialog.getSelectedLocale();
+
+ reference = ASTutils.insertExistingBundleRef(document, resource,
+ offset, length, resourceBundleId, key, locale);
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ return "Insert reference to a localized string literal";
+ }
+
+ @Override
+ public Image getImage() {
+ return PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ // TODO Auto-generated method stub
+ int referenceLength = reference == null ? 0 : reference.length();
+ return new Point(offset + referenceLength, 0);
+ }
+
+ @Override
+ public int getRelevance() {
+ // TODO Auto-generated method stub
+ if (this.length == 0)
+ return 97;
+ else
+ return 1097;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java
index 41b81a71..434a22a6 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java
@@ -1,67 +1,74 @@
-package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-
-public class MessageCompletionProposal implements IJavaCompletionProposal {
-
- private int offset = 0;
- private int length = 0;
- private String content = "";
- private boolean messageAccessor = false;
-
- public MessageCompletionProposal(int offset, int length, String content,
- boolean messageAccessor) {
- this.offset = offset;
- this.length = length;
- this.content = content;
- this.messageAccessor = messageAccessor;
- }
-
- @Override
- public void apply(IDocument document) {
- try {
- document.replace(offset, length, content);
- } catch (Exception e) {
- Logger.logError(e);
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- return "Inserts the resource key '" + this.content + "'";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return content;
- }
-
- @Override
- public Image getImage() {
- if (messageAccessor)
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return new Point(offset + content.length() + 1, 0);
- }
-
- @Override
- public int getRelevance() {
- return 99;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+
+public class MessageCompletionProposal implements IJavaCompletionProposal {
+
+ private int offset = 0;
+ private int length = 0;
+ private String content = "";
+ private boolean messageAccessor = false;
+
+ public MessageCompletionProposal(int offset, int length, String content,
+ boolean messageAccessor) {
+ this.offset = offset;
+ this.length = length;
+ this.content = content;
+ this.messageAccessor = messageAccessor;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ try {
+ document.replace(offset, length, content);
+ } catch (Exception e) {
+ Logger.logError(e);
+ }
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ return "Inserts the resource key '" + this.content + "'";
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ return content;
+ }
+
+ @Override
+ public Image getImage() {
+ if (messageAccessor)
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ return new Point(offset + content.length() + 1, 0);
+ }
+
+ @Override
+ public int getRelevance() {
+ return 99;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java
index b0ddd0b1..cc1fdb07 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java
@@ -1,126 +1,133 @@
-package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
-import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
-
- private int startPos;
- private int endPos;
- private String value;
- private boolean bundleContext;
- private String projectName;
- private IResource resource;
- private String bundleName;
- private String reference;
-
- public NewResourceBundleEntryProposal(IResource resource, int startPos,
- int endPos, String value, boolean isStringLiteral,
- boolean bundleContext, String projectName,
- String bundleName) {
-
- this.startPos = startPos;
- this.endPos = endPos;
- this.value = value;
- this.bundleContext = bundleContext;
- this.projectName = projectName;
- this.resource = resource;
- this.bundleName = bundleName;
- }
-
- @Override
- public void apply(IDocument document) {
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(bundleContext ? value : "");
- config.setPreselectedMessage(value);
- config.setPreselectedBundle(bundleName == null ? "" : bundleName);
- config.setPreselectedLocale("");
- config.setProjectName(projectName);
-
- dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- String resourceBundleId = dialog.getSelectedResourceBundle();
- String key = dialog.getSelectedKey();
-
- try {
- if (!bundleContext)
- reference = ASTutils.insertNewBundleRef(document, resource,
- startPos, endPos - startPos, resourceBundleId, key);
- else {
- document.replace(startPos, endPos - startPos, key);
- reference = key + "\"";
- }
- ResourceBundleManager.refreshResource(resource);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- if (value != null && value.length() > 0) {
- return "Exports the focused string literal into a Java Resource-Bundle. This action results "
- + "in a Resource-Bundle reference!";
- } else
- return "";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- String displayStr = "";
- if (bundleContext)
- displayStr = "Create a new resource-bundle-entry";
- else
- displayStr = "Create a new localized string literal";
-
- if (value != null && value.length() > 0)
- displayStr += " for '" + value + "'";
-
- return displayStr;
- }
-
- @Override
- public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- int refLength = reference == null ? 0 : reference.length() - 1;
- return new Point(startPos + refLength, 0);
- }
-
- @Override
- public int getRelevance() {
- if (this.value.trim().length() == 0)
- return 96;
- else
- return 1096;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.babel.tapiji.tools.java.util.ASTutils;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
+
+ private int startPos;
+ private int endPos;
+ private String value;
+ private boolean bundleContext;
+ private String projectName;
+ private IResource resource;
+ private String bundleName;
+ private String reference;
+
+ public NewResourceBundleEntryProposal(IResource resource, int startPos,
+ int endPos, String value, boolean isStringLiteral,
+ boolean bundleContext, String projectName,
+ String bundleName) {
+
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.value = value;
+ this.bundleContext = bundleContext;
+ this.projectName = projectName;
+ this.resource = resource;
+ this.bundleName = bundleName;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(bundleContext ? value : "");
+ config.setPreselectedMessage(value);
+ config.setPreselectedBundle(bundleName == null ? "" : bundleName);
+ config.setPreselectedLocale("");
+ config.setProjectName(projectName);
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ String resourceBundleId = dialog.getSelectedResourceBundle();
+ String key = dialog.getSelectedKey();
+
+ try {
+ if (!bundleContext)
+ reference = ASTutils.insertNewBundleRef(document, resource,
+ startPos, endPos - startPos, resourceBundleId, key);
+ else {
+ document.replace(startPos, endPos - startPos, key);
+ reference = key + "\"";
+ }
+ ResourceBundleManager.refreshResource(resource);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ if (value != null && value.length() > 0) {
+ return "Exports the focused string literal into a Java Resource-Bundle. This action results "
+ + "in a Resource-Bundle reference!";
+ } else
+ return "";
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ String displayStr = "";
+ if (bundleContext)
+ displayStr = "Create a new resource-bundle-entry";
+ else
+ displayStr = "Create a new localized string literal";
+
+ if (value != null && value.length() > 0)
+ displayStr += " for '" + value + "'";
+
+ return displayStr;
+ }
+
+ @Override
+ public Image getImage() {
+ return PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage();
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ int refLength = reference == null ? 0 : reference.length() - 1;
+ return new Point(startPos + refLength, 0);
+ }
+
+ @Override
+ public int getRelevance() {
+ if (this.value.trim().length() == 0)
+ return 96;
+ else
+ return 1096;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java
index 56c38f83..c2bcffc5 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java
@@ -1,57 +1,64 @@
-package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
-
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-
-public class NoActionProposal implements IJavaCompletionProposal {
-
- public NoActionProposal () {
- super();
- }
-
- @Override
- public void apply(IDocument document) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- // TODO Auto-generated method stub
- return "No Default Proposals";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- return 100;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+
+public class NoActionProposal implements IJavaCompletionProposal {
+
+ public NoActionProposal () {
+ super();
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ // TODO Auto-generated method stub
+ return "No Default Proposals";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int getRelevance() {
+ // TODO Auto-generated method stub
+ return 100;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java
index 77a2f4a0..7774650a 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java
@@ -1,40 +1,47 @@
-package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
-
-import org.eclipse.jdt.ui.text.java.AbstractProposalSorter;
-import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-
-public class Sorter extends AbstractProposalSorter {
-
- private boolean loaded = false;
-
- public Sorter() {
- // i18n
- loaded = true;
- }
-
- @Override
- public void beginSorting(ContentAssistInvocationContext context) {
- // TODO Auto-generated method stub
- super.beginSorting(context);
- }
-
- @Override
- public int compare(ICompletionProposal prop1, ICompletionProposal prop2) {
- return getIndex(prop1) - getIndex(prop2);
- }
-
- protected int getIndex(ICompletionProposal prop) {
- if (prop instanceof NoActionProposal)
- return 1;
- else if (prop instanceof MessageCompletionProposal)
- return 2;
- else if (prop instanceof InsertResourceBundleReferenceProposal)
- return 3;
- else if (prop instanceof NewResourceBundleEntryProposal)
- return 4;
- else
- return 0;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.ui.autocompletion;
+
+import org.eclipse.jdt.ui.text.java.AbstractProposalSorter;
+import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+
+public class Sorter extends AbstractProposalSorter {
+
+ private boolean loaded = false;
+
+ public Sorter() {
+ // i18n
+ loaded = true;
+ }
+
+ @Override
+ public void beginSorting(ContentAssistInvocationContext context) {
+ // TODO Auto-generated method stub
+ super.beginSorting(context);
+ }
+
+ @Override
+ public int compare(ICompletionProposal prop1, ICompletionProposal prop2) {
+ return getIndex(prop1) - getIndex(prop2);
+ }
+
+ protected int getIndex(ICompletionProposal prop) {
+ if (prop instanceof NoActionProposal)
+ return 1;
+ else if (prop instanceof MessageCompletionProposal)
+ return 2;
+ else if (prop instanceof InsertResourceBundleReferenceProposal)
+ return 3;
+ else if (prop instanceof NewResourceBundleEntryProposal)
+ return 4;
+ else
+ return 0;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java
index 1c36df30..478a94ed 100644
--- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java
+++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java
@@ -1,1035 +1,1042 @@
-package org.eclipse.babel.tapiji.tools.java.util;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import org.eclipse.babel.tapiji.tools.core.Logger;
-import org.eclipse.babel.tapiji.tools.java.auditor.MethodParameterDescriptor;
-import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.ITypeRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.dom.AST;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.core.dom.ASTParser;
-import org.eclipse.jdt.core.dom.ASTVisitor;
-import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.jdt.core.dom.BodyDeclaration;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.core.dom.ExpressionStatement;
-import org.eclipse.jdt.core.dom.FieldDeclaration;
-import org.eclipse.jdt.core.dom.ITypeBinding;
-import org.eclipse.jdt.core.dom.IVariableBinding;
-import org.eclipse.jdt.core.dom.ImportDeclaration;
-import org.eclipse.jdt.core.dom.MethodDeclaration;
-import org.eclipse.jdt.core.dom.MethodInvocation;
-import org.eclipse.jdt.core.dom.Modifier;
-import org.eclipse.jdt.core.dom.SimpleName;
-import org.eclipse.jdt.core.dom.SimpleType;
-import org.eclipse.jdt.core.dom.StringLiteral;
-import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
-import org.eclipse.jdt.core.dom.TypeDeclaration;
-import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.jdt.ui.SharedASTProvider;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.text.edits.TextEdit;
-
-public class ASTutils {
-
- private static MethodParameterDescriptor rbDefinition;
- private static MethodParameterDescriptor rbAccessor;
-
- public static MethodParameterDescriptor getRBDefinitionDesc() {
- if (rbDefinition == null) {
- // Init descriptor for Resource-Bundle-Definition
- List<String> definition = new ArrayList<String>();
- definition.add("getBundle");
- rbDefinition = new MethodParameterDescriptor(definition,
- "java.util.ResourceBundle", true, 0);
- }
-
- return rbDefinition;
- }
-
- public static MethodParameterDescriptor getRBAccessorDesc() {
- if (rbAccessor == null) {
- // Init descriptor for Resource-Bundle-Accessors
- List<String> accessors = new ArrayList<String>();
- accessors.add("getString");
- accessors.add("getStringArray");
- rbAccessor = new MethodParameterDescriptor(accessors,
- "java.util.ResourceBundle", true, 0);
- }
-
- return rbAccessor;
- }
-
- public static CompilationUnit getCompilationUnit(IResource resource) {
- IJavaElement je = JavaCore.create(resource,
- JavaCore.create(resource.getProject()));
- // get the type of the currently loaded resource
- ITypeRoot typeRoot = ((ICompilationUnit) je);
-
- if (typeRoot == null)
- return null;
-
- return getCompilationUnit(typeRoot);
- }
-
- public static CompilationUnit getCompilationUnit(ITypeRoot typeRoot) {
- // get a reference to the shared AST of the loaded CompilationUnit
- CompilationUnit cu = SharedASTProvider.getAST(typeRoot,
- // do not wait for AST creation
- SharedASTProvider.WAIT_YES, null);
-
- return cu;
- }
-
- public static String insertExistingBundleRef(IDocument document,
- IResource resource, int offset, int length,
- String resourceBundleId, String key, Locale locale) {
- String reference = "";
- String newName = null;
-
- CompilationUnit cu = getCompilationUnit(resource);
-
- String variableName = ASTutils.resolveRBReferenceVar(document,
- resource, offset, resourceBundleId, cu);
- if (variableName == null)
- newName = ASTutils.getNonExistingRBRefName(resourceBundleId,
- document, cu);
-
- try {
- reference = ASTutils.createResourceReference(resourceBundleId, key,
- locale, resource, offset, variableName == null ? newName
- : variableName, document, cu);
-
- document.replace(offset, length, reference);
-
- // create non-internationalisation-comment
- createReplaceNonInternationalisationComment(cu, document, offset);
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
-
- // TODO retrieve cu in the same way as in createResourceReference
- // the current version does not parse method bodies
-
- if (variableName == null) {
- ASTutils.createResourceBundleReference(resource, offset, document,
- resourceBundleId, locale, true, newName, cu);
- // createReplaceNonInternationalisationComment(cu, document, pos);
- }
- return reference;
- }
-
- public static String insertNewBundleRef(IDocument document,
- IResource resource, int startPos, int endPos,
- String resourceBundleId, String key) {
- String newName = null;
- String reference = "";
-
- CompilationUnit cu = getCompilationUnit(resource);
-
- if (cu == null)
- return null;
-
- String variableName = ASTutils.resolveRBReferenceVar(document,
- resource, startPos, resourceBundleId, cu);
- if (variableName == null)
- newName = ASTutils.getNonExistingRBRefName(resourceBundleId,
- document, cu);
-
- try {
- reference = ASTutils.createResourceReference(resourceBundleId, key,
- null, resource, startPos, variableName == null ? newName
- : variableName, document, cu);
-
- if (startPos > 0 && document.get().charAt(startPos - 1) == '\"') {
- startPos--;
- endPos++;
- }
-
- if ((startPos + endPos) < document.getLength()
- && document.get().charAt(startPos + endPos) == '\"')
- endPos++;
-
- if ((startPos + endPos) < document.getLength()
- && document.get().charAt(startPos + endPos - 1) == ';')
- endPos--;
-
- document.replace(startPos, endPos, reference);
-
- // create non-internationalisation-comment
- createReplaceNonInternationalisationComment(cu, document, startPos);
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
-
- if (variableName == null) {
- // refresh reference to the shared AST of the loaded CompilationUnit
- cu = getCompilationUnit(resource);
-
- ASTutils.createResourceBundleReference(resource, startPos,
- document, resourceBundleId, null, true, newName, cu);
- // createReplaceNonInternationalisationComment(cu, document, pos);
- }
-
- return reference;
- }
-
- public static String resolveRBReferenceVar(IDocument document,
- IResource resource, int pos, final String bundleId,
- CompilationUnit cu) {
- String bundleVar;
-
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
- TypeDeclaration td = typeFinder.getEnclosingType();
- MethodDeclaration meth = typeFinder.getEnclosingMethod();
-
- if (atd == null) {
- BundleDeclarationFinder bdf = new BundleDeclarationFinder(
- bundleId,
- td,
- meth != null
- && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
- td.accept(bdf);
-
- bundleVar = bdf.getVariableName();
- } else {
- BundleDeclarationFinder bdf = new BundleDeclarationFinder(
- bundleId,
- atd,
- meth != null
- && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
- atd.accept(bdf);
-
- bundleVar = bdf.getVariableName();
- }
-
- // Check also method body
- if (meth != null) {
- try {
- InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder(
- bundleId, pos);
- typeFinder.getEnclosingMethod().accept(imbdf);
- bundleVar = imbdf.getVariableName() != null ? imbdf
- .getVariableName() : bundleVar;
- } catch (Exception e) {
- // ignore
- }
- }
-
- return bundleVar;
- }
-
- public static String getNonExistingRBRefName(String bundleId,
- IDocument document, CompilationUnit cu) {
- String referenceName = null;
- int i = 0;
-
- while (referenceName == null) {
- String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1)
- + "Ref" + (i == 0 ? "" : i);
- actRef = actRef.toLowerCase();
-
- VariableFinder vf = new VariableFinder(actRef);
- cu.accept(vf);
-
- if (!vf.isVariableFound()) {
- referenceName = actRef;
- break;
- }
-
- i++;
- }
-
- return referenceName;
- }
-
- @Deprecated
- public static String resolveResourceBundle(
- MethodInvocation methodInvocation,
- MethodParameterDescriptor rbDefinition,
- Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
- String bundleName = null;
-
- if (methodInvocation.getExpression() instanceof SimpleName) {
- SimpleName vName = (SimpleName) methodInvocation.getExpression();
- IVariableBinding vBinding = (IVariableBinding) vName
- .resolveBinding();
- VariableDeclarationFragment dec = variableBindingManagers
- .get(vBinding);
-
- if (dec.getInitializer() instanceof MethodInvocation) {
- MethodInvocation init = (MethodInvocation) dec.getInitializer();
-
- // Check declaring class
- boolean isValidClass = false;
- ITypeBinding type = init.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(
- rbDefinition.getDeclaringClass())) {
- isValidClass = true;
- break;
- } else {
- if (rbDefinition.isConsiderSuperclass())
- type = type.getSuperclass();
- else
- type = null;
- }
-
- }
- if (!isValidClass)
- return null;
-
- boolean isValidMethod = false;
- for (String mn : rbDefinition.getMethodName()) {
- if (init.getName().getFullyQualifiedName().equals(mn)) {
- isValidMethod = true;
- break;
- }
- }
- if (!isValidMethod)
- return null;
-
- // retrieve bundlename
- if (init.arguments().size() < rbDefinition.getPosition() + 1)
- return null;
-
- bundleName = ((StringLiteral) init.arguments().get(
- rbDefinition.getPosition())).getLiteralValue();
- }
- }
-
- return bundleName;
- }
-
- public static SLLocation resolveResourceBundleLocation(
- MethodInvocation methodInvocation,
- MethodParameterDescriptor rbDefinition,
- Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
- SLLocation bundleDesc = null;
-
- if (methodInvocation.getExpression() instanceof SimpleName) {
- SimpleName vName = (SimpleName) methodInvocation.getExpression();
- IVariableBinding vBinding = (IVariableBinding) vName
- .resolveBinding();
- VariableDeclarationFragment dec = variableBindingManagers
- .get(vBinding);
-
- if (dec.getInitializer() instanceof MethodInvocation) {
- MethodInvocation init = (MethodInvocation) dec.getInitializer();
-
- // Check declaring class
- boolean isValidClass = false;
- ITypeBinding type = init.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(
- rbDefinition.getDeclaringClass())) {
- isValidClass = true;
- break;
- } else {
- if (rbDefinition.isConsiderSuperclass())
- type = type.getSuperclass();
- else
- type = null;
- }
-
- }
- if (!isValidClass)
- return null;
-
- boolean isValidMethod = false;
- for (String mn : rbDefinition.getMethodName()) {
- if (init.getName().getFullyQualifiedName().equals(mn)) {
- isValidMethod = true;
- break;
- }
- }
- if (!isValidMethod)
- return null;
-
- // retrieve bundlename
- if (init.arguments().size() < rbDefinition.getPosition() + 1)
- return null;
-
- StringLiteral bundleLiteral = ((StringLiteral) init.arguments()
- .get(rbDefinition.getPosition()));
- bundleDesc = new SLLocation(null,
- bundleLiteral.getStartPosition(),
- bundleLiteral.getLength()
- + bundleLiteral.getStartPosition(),
- bundleLiteral.getLiteralValue());
- }
- }
-
- return bundleDesc;
- }
-
- private static boolean isMatchingMethodDescriptor(
- MethodInvocation methodInvocation, MethodParameterDescriptor desc) {
- boolean result = false;
-
- if (methodInvocation.resolveMethodBinding() == null)
- return false;
-
- String methodName = methodInvocation.resolveMethodBinding().getName();
-
- // Check declaring class
- ITypeBinding type = methodInvocation.resolveMethodBinding()
- .getDeclaringClass();
- while (type != null) {
- if (type.getQualifiedName().equals(desc.getDeclaringClass())) {
- result = true;
- break;
- } else {
- if (desc.isConsiderSuperclass())
- type = type.getSuperclass();
- else
- type = null;
- }
-
- }
-
- if (!result)
- return false;
-
- result = !result;
-
- // Check method name
- for (String method : desc.getMethodName()) {
- if (method.equals(methodName)) {
- result = true;
- break;
- }
- }
-
- return result;
- }
-
- public static boolean isMatchingMethodParamDesc(
- MethodInvocation methodInvocation, String literal,
- MethodParameterDescriptor desc) {
- boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
-
- if (!result)
- return false;
- else
- result = false;
-
- if (methodInvocation.arguments().size() > desc.getPosition()) {
- if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) {
- StringLiteral sl = (StringLiteral) methodInvocation.arguments()
- .get(desc.getPosition());
- if (sl.getLiteralValue().trim().toLowerCase()
- .equals(literal.toLowerCase()))
- result = true;
- }
- }
-
- return result;
- }
-
- public static boolean isMatchingMethodParamDesc(
- MethodInvocation methodInvocation, StringLiteral literal,
- MethodParameterDescriptor desc) {
- int keyParameter = desc.getPosition();
- boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
-
- if (!result)
- return false;
-
- // Check position within method call
- StructuralPropertyDescriptor spd = literal.getLocationInParent();
- if (spd.isChildListProperty()) {
- List<ASTNode> arguments = (List<ASTNode>) methodInvocation
- .getStructuralProperty(spd);
- result = (arguments.size() > keyParameter && arguments
- .get(keyParameter) == literal);
- }
-
- return result;
- }
-
- public static ICompilationUnit createCompilationUnit(IResource resource) {
- // Instantiate a new AST parser
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
-
- ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource
- .getProject().getFile(resource.getRawLocation()));
-
- return cu;
- }
-
- public static CompilationUnit createCompilationUnit(IDocument document) {
- // Instantiate a new AST parser
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setResolveBindings(true);
-
- parser.setSource(document.get().toCharArray());
- return (CompilationUnit) parser.createAST(null);
- }
-
- public static void createImport(IDocument doc, IResource resource,
- CompilationUnit cu, AST ast, ASTRewrite rewriter,
- String qualifiedClassName) throws CoreException,
- BadLocationException {
-
- ImportFinder impFinder = new ImportFinder(qualifiedClassName);
-
- cu.accept(impFinder);
-
- if (!impFinder.isImportFound()) {
- // ITextFileBufferManager bufferManager =
- // FileBuffers.getTextFileBufferManager();
- // IPath path = resource.getFullPath();
- //
- // bufferManager.connect(path, LocationKind.IFILE, null);
- // ITextFileBuffer textFileBuffer =
- // bufferManager.getTextFileBuffer(doc);
-
- // TODO create new import
- ImportDeclaration id = ast.newImportDeclaration();
- id.setName(ast.newName(qualifiedClassName.split("\\.")));
- id.setStatic(false);
-
- ListRewrite lrw = rewriter.getListRewrite(cu, cu.IMPORTS_PROPERTY);
- lrw.insertFirst(id, null);
-
- // TextEdit te = rewriter.rewriteAST(doc, null);
- // te.apply(doc);
- //
- // if (textFileBuffer != null)
- // textFileBuffer.commit(null, false);
- // else
- // FileUtils.saveTextFile(resource.getProject().getFile(resource.getProjectRelativePath()),
- // doc.get());
- // bufferManager.disconnect(path, LocationKind.IFILE, null);
- }
-
- }
-
- // TODO export initializer specification into a methodinvocationdefinition
- public static void createResourceBundleReference(IResource resource,
- int typePos, IDocument doc, String bundleId, Locale locale,
- boolean globalReference, String variableName, CompilationUnit cu) {
-
- try {
-
- if (globalReference) {
-
- // retrieve compilation unit from document
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(
- typePos);
- cu.accept(typeFinder);
- ASTNode node = typeFinder.getEnclosingType();
- ASTNode anonymNode = typeFinder.getEnclosingAnonymType();
- if (anonymNode != null)
- node = anonymNode;
-
- MethodDeclaration meth = typeFinder.getEnclosingMethod();
- AST ast = node.getAST();
-
- VariableDeclarationFragment vdf = ast
- .newVariableDeclarationFragment();
- vdf.setName(ast.newSimpleName(variableName));
-
- // set initializer
- vdf.setInitializer(createResourceBundleGetter(ast, bundleId,
- locale));
-
- FieldDeclaration fd = ast.newFieldDeclaration(vdf);
- fd.setType(ast.newSimpleType(ast
- .newName(new String[] { "ResourceBundle" })));
-
- if (meth != null
- && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
- fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC));
-
- // rewrite AST
- ASTRewrite rewriter = ASTRewrite.create(ast);
- ListRewrite lrw = rewriter
- .getListRewrite(
- node,
- node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY
- : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
- lrw.insertAt(fd, /*
- * findIndexOfLastField(node.bodyDeclarations())
- * +1
- */
- 0, null);
-
- // create import if required
- createImport(doc, resource, cu, ast, rewriter,
- getRBDefinitionDesc().getDeclaringClass());
-
- TextEdit te = rewriter.rewriteAST(doc, null);
- te.apply(doc);
- } else {
-
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- private static int findIndexOfLastField(List bodyDeclarations) {
- for (int i = bodyDeclarations.size() - 1; i >= 0; i--) {
- BodyDeclaration each = (BodyDeclaration) bodyDeclarations.get(i);
- if (each instanceof FieldDeclaration)
- return i;
- }
- return -1;
- }
-
- protected static MethodInvocation createResourceBundleGetter(AST ast,
- String bundleId, Locale locale) {
- MethodInvocation mi = ast.newMethodInvocation();
-
- mi.setName(ast.newSimpleName("getBundle"));
- mi.setExpression(ast.newName(new String[] { "ResourceBundle" }));
-
- // Add bundle argument
- StringLiteral sl = ast.newStringLiteral();
- sl.setLiteralValue(bundleId);
- mi.arguments().add(sl);
-
- // TODO Add Locale argument
-
- return mi;
- }
-
- public static ASTNode getEnclosingType(CompilationUnit cu, int pos) {
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder
- .getEnclosingAnonymType() : typeFinder.getEnclosingType();
- }
-
- public static ASTNode getEnclosingType(ASTNode cu, int pos) {
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
- cu.accept(typeFinder);
- return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder
- .getEnclosingAnonymType() : typeFinder.getEnclosingType();
- }
-
- protected static MethodInvocation referenceResource(AST ast,
- String accessorName, String key, Locale locale) {
- MethodParameterDescriptor accessorDesc = getRBAccessorDesc();
- MethodInvocation mi = ast.newMethodInvocation();
-
- mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0)));
-
- // Declare expression
- StringLiteral sl = ast.newStringLiteral();
- sl.setLiteralValue(key);
-
- // TODO define locale expression
- if (mi.arguments().size() == accessorDesc.getPosition())
- mi.arguments().add(sl);
-
- SimpleName name = ast.newSimpleName(accessorName);
- mi.setExpression(name);
-
- return mi;
- }
-
- public static String createResourceReference(String bundleId, String key,
- Locale locale, IResource resource, int typePos,
- String accessorName, IDocument doc, CompilationUnit cu) {
-
- PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos);
- cu.accept(typeFinder);
- AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
- TypeDeclaration td = typeFinder.getEnclosingType();
-
- // retrieve compilation unit from document
- ASTNode node = atd == null ? td : atd;
- AST ast = node.getAST();
-
- ExpressionStatement expressionStatement = ast
- .newExpressionStatement(referenceResource(ast, accessorName,
- key, locale));
-
- String exp = expressionStatement.toString();
-
- // remove semicolon and line break at the end of this expression
- // statement
- if (exp.endsWith(";\n"))
- exp = exp.substring(0, exp.length() - 2);
-
- return exp;
- }
-
- private static int findNonInternationalisationPosition(CompilationUnit cu,
- IDocument doc, int offset) {
- LinePreStringsFinder lsfinder = null;
- try {
- lsfinder = new LinePreStringsFinder(offset, doc);
- cu.accept(lsfinder);
- } catch (BadLocationException e) {
- Logger.logError(e);
- }
- if (lsfinder == null)
- return 1;
-
- List<StringLiteral> strings = lsfinder.getStrings();
-
- return strings.size() + 1;
- }
-
- public static void createReplaceNonInternationalisationComment(
- CompilationUnit cu, IDocument doc, int position) {
- int i = findNonInternationalisationPosition(cu, doc, position);
-
- IRegion reg;
- try {
- reg = doc.getLineInformationOfOffset(position);
- doc.replace(reg.getOffset() + reg.getLength(), 0, " //$NON-NLS-"
- + i + "$");
- } catch (BadLocationException e) {
- Logger.logError(e);
- }
- }
-
- private static void createASTNonInternationalisationComment(
- CompilationUnit cu, IDocument doc, ASTNode parent, ASTNode fd,
- ASTRewrite rewriter, ListRewrite lrw) {
- int i = 1;
-
- // ListRewrite lrw2 = rewriter.getListRewrite(node,
- // Block.STATEMENTS_PROPERTY);
- ASTNode placeHolder = rewriter.createStringPlaceholder("//$NON-NLS-"
- + i + "$", ASTNode.LINE_COMMENT);
- lrw.insertAfter(placeHolder, fd, null);
- }
-
- public static boolean existsNonInternationalisationComment(
- StringLiteral literal) throws BadLocationException {
- CompilationUnit cu = (CompilationUnit) literal.getRoot();
- ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();
-
- IDocument doc = null;
- try {
- doc = new Document(icu.getSource());
- } catch (JavaModelException e) {
- Logger.logError(e);
- }
-
- // get whole line in which string literal
- int lineNo = doc.getLineOfOffset(literal.getStartPosition());
- int lineOffset = doc.getLineOffset(lineNo);
- int lineLength = doc.getLineLength(lineNo);
- String lineOfString = doc.get(lineOffset, lineLength);
-
- // search for a line comment in this line
- int indexComment = lineOfString.indexOf("//");
-
- if (indexComment == -1)
- return false;
-
- String comment = lineOfString.substring(indexComment);
-
- // remove first "//" of line comment
- comment = comment.substring(2).toLowerCase();
-
- // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3
- String[] comments = comment.split("//");
-
- for (String commentFrag : comments) {
- commentFrag = commentFrag.trim();
-
- // if comment match format: "$non-nls$" then ignore whole line
- if (commentFrag.matches("^\\$non-nls\\$$")) {
- return true;
-
- // if comment match format: "$non-nls-{number}$" then only
- // ignore string which is on given position
- } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) {
- int iString = findNonInternationalisationPosition(cu, doc,
- literal.getStartPosition());
- int iComment = new Integer(commentFrag.substring(9, 10));
- if (iString == iComment)
- return true;
- }
- }
- return false;
- }
-
- public static StringLiteral getStringAtPos(CompilationUnit cu, int position) {
- StringFinder strFinder = new StringFinder(position);
- cu.accept(strFinder);
- return strFinder.getString();
- }
-
- static class PositionalTypeFinder extends ASTVisitor {
-
- private int position;
- private TypeDeclaration enclosingType;
- private AnonymousClassDeclaration enclosingAnonymType;
- private MethodDeclaration enclosingMethod;
-
- public PositionalTypeFinder(int pos) {
- position = pos;
- }
-
- public TypeDeclaration getEnclosingType() {
- return enclosingType;
- }
-
- public AnonymousClassDeclaration getEnclosingAnonymType() {
- return enclosingAnonymType;
- }
-
- public MethodDeclaration getEnclosingMethod() {
- return enclosingMethod;
- }
-
- @Override
- public boolean visit(MethodDeclaration node) {
- if (position >= node.getStartPosition()
- && position <= (node.getStartPosition() + node.getLength())) {
- enclosingMethod = node;
- return true;
- } else
- return false;
- }
-
- @Override
- public boolean visit(TypeDeclaration node) {
- if (position >= node.getStartPosition()
- && position <= (node.getStartPosition() + node.getLength())) {
- enclosingType = node;
- return true;
- } else
- return false;
- }
-
- @Override
- public boolean visit(AnonymousClassDeclaration node) {
- if (position >= node.getStartPosition()
- && position <= (node.getStartPosition() + node.getLength())) {
- enclosingAnonymType = node;
- return true;
- } else
- return false;
- }
- }
-
- static class ImportFinder extends ASTVisitor {
-
- String qName;
- boolean importFound = false;
-
- public ImportFinder(String qName) {
- this.qName = qName;
- }
-
- public boolean isImportFound() {
- return importFound;
- }
-
- @Override
- public boolean visit(ImportDeclaration id) {
- if (id.getName().getFullyQualifiedName().equals(qName))
- importFound = true;
-
- return true;
- }
- }
-
- static class VariableFinder extends ASTVisitor {
-
- boolean found = false;
- String variableName;
-
- public boolean isVariableFound() {
- return found;
- }
-
- public VariableFinder(String variableName) {
- this.variableName = variableName;
- }
-
- @Override
- public boolean visit(VariableDeclarationFragment vdf) {
- if (vdf.getName().getFullyQualifiedName().equals(variableName)) {
- found = true;
- return false;
- }
-
- return true;
- }
- }
-
- static class InMethodBundleDeclFinder extends ASTVisitor {
- String varName;
- String bundleId;
- int pos;
-
- public InMethodBundleDeclFinder(String bundleId, int pos) {
- this.bundleId = bundleId;
- this.pos = pos;
- }
-
- public String getVariableName() {
- return varName;
- }
-
- @Override
- public boolean visit(VariableDeclarationFragment fdvd) {
- if (fdvd.getStartPosition() > pos)
- return false;
-
- // boolean bStatic = (fdvd.resolveBinding().getModifiers() &
- // Modifier.STATIC) == Modifier.STATIC;
- // if (!bStatic && isStatic)
- // return true;
-
- String tmpVarName = fdvd.getName().getFullyQualifiedName();
-
- if (fdvd.getInitializer() instanceof MethodInvocation) {
- MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer();
- if (isMatchingMethodParamDesc(fdi, bundleId,
- getRBDefinitionDesc()))
- varName = tmpVarName;
- }
- return true;
- }
- }
-
- static class BundleDeclarationFinder extends ASTVisitor {
-
- String varName;
- String bundleId;
- ASTNode typeDef;
- boolean isStatic;
-
- public BundleDeclarationFinder(String bundleId, ASTNode td,
- boolean isStatic) {
- this.bundleId = bundleId;
- this.typeDef = td;
- this.isStatic = isStatic;
- }
-
- public String getVariableName() {
- return varName;
- }
-
- @Override
- public boolean visit(MethodDeclaration md) {
- return true;
- }
-
- @Override
- public boolean visit(FieldDeclaration fd) {
- if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef)
- return false;
-
- boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
- if (!bStatic && isStatic)
- return true;
-
- if (fd.getType() instanceof SimpleType) {
- SimpleType fdType = (SimpleType) fd.getType();
- String typeName = fdType.getName().getFullyQualifiedName();
- String referenceName = getRBDefinitionDesc()
- .getDeclaringClass();
- if (typeName.equals(referenceName)
- || (referenceName.lastIndexOf(".") >= 0 && typeName
- .equals(referenceName.substring(referenceName
- .lastIndexOf(".") + 1)))) {
- // Check VariableDeclarationFragment
- if (fd.fragments().size() == 1) {
- if (fd.fragments().get(0) instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd
- .fragments().get(0);
- String tmpVarName = fdvd.getName()
- .getFullyQualifiedName();
-
- if (fdvd.getInitializer() instanceof MethodInvocation) {
- MethodInvocation fdi = (MethodInvocation) fdvd
- .getInitializer();
- if (isMatchingMethodParamDesc(fdi, bundleId,
- getRBDefinitionDesc()))
- varName = tmpVarName;
- }
- }
- }
- }
- }
- return false;
- }
-
- }
-
- static class LinePreStringsFinder extends ASTVisitor {
- private int position;
- private int line;
- private List<StringLiteral> strings;
- private IDocument document;
-
- public LinePreStringsFinder(int position, IDocument document)
- throws BadLocationException {
- this.document = document;
- this.position = position;
- line = document.getLineOfOffset(position);
- strings = new ArrayList<StringLiteral>();
- }
-
- public List<StringLiteral> getStrings() {
- return strings;
- }
-
- @Override
- public boolean visit(StringLiteral node) {
- try {
- if (line == document.getLineOfOffset(node.getStartPosition())
- && node.getStartPosition() < position) {
- strings.add(node);
- return true;
- }
- } catch (BadLocationException e) {
- }
- return true;
- }
- }
-
- static class StringFinder extends ASTVisitor {
- private int position;
- private StringLiteral string;
-
- public StringFinder(int position) {
- this.position = position;
- }
-
- public StringLiteral getString() {
- return string;
- }
-
- @Override
- public boolean visit(StringLiteral node) {
- if (position > node.getStartPosition()
- && position < (node.getStartPosition() + node.getLength()))
- string = node;
- return true;
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.java.util;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+import org.eclipse.babel.tapiji.tools.java.auditor.MethodParameterDescriptor;
+import org.eclipse.babel.tapiji.tools.java.auditor.model.SLLocation;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jdt.core.ICompilationUnit;
+import org.eclipse.jdt.core.IJavaElement;
+import org.eclipse.jdt.core.ITypeRoot;
+import org.eclipse.jdt.core.JavaCore;
+import org.eclipse.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.AST;
+import org.eclipse.jdt.core.dom.ASTNode;
+import org.eclipse.jdt.core.dom.ASTParser;
+import org.eclipse.jdt.core.dom.ASTVisitor;
+import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
+import org.eclipse.jdt.core.dom.BodyDeclaration;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.core.dom.ExpressionStatement;
+import org.eclipse.jdt.core.dom.FieldDeclaration;
+import org.eclipse.jdt.core.dom.ITypeBinding;
+import org.eclipse.jdt.core.dom.IVariableBinding;
+import org.eclipse.jdt.core.dom.ImportDeclaration;
+import org.eclipse.jdt.core.dom.MethodDeclaration;
+import org.eclipse.jdt.core.dom.MethodInvocation;
+import org.eclipse.jdt.core.dom.Modifier;
+import org.eclipse.jdt.core.dom.SimpleName;
+import org.eclipse.jdt.core.dom.SimpleType;
+import org.eclipse.jdt.core.dom.StringLiteral;
+import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
+import org.eclipse.jdt.core.dom.TypeDeclaration;
+import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
+import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
+import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
+import org.eclipse.jdt.ui.SharedASTProvider;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.Document;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.text.edits.TextEdit;
+
+public class ASTutils {
+
+ private static MethodParameterDescriptor rbDefinition;
+ private static MethodParameterDescriptor rbAccessor;
+
+ public static MethodParameterDescriptor getRBDefinitionDesc() {
+ if (rbDefinition == null) {
+ // Init descriptor for Resource-Bundle-Definition
+ List<String> definition = new ArrayList<String>();
+ definition.add("getBundle");
+ rbDefinition = new MethodParameterDescriptor(definition,
+ "java.util.ResourceBundle", true, 0);
+ }
+
+ return rbDefinition;
+ }
+
+ public static MethodParameterDescriptor getRBAccessorDesc() {
+ if (rbAccessor == null) {
+ // Init descriptor for Resource-Bundle-Accessors
+ List<String> accessors = new ArrayList<String>();
+ accessors.add("getString");
+ accessors.add("getStringArray");
+ rbAccessor = new MethodParameterDescriptor(accessors,
+ "java.util.ResourceBundle", true, 0);
+ }
+
+ return rbAccessor;
+ }
+
+ public static CompilationUnit getCompilationUnit(IResource resource) {
+ IJavaElement je = JavaCore.create(resource,
+ JavaCore.create(resource.getProject()));
+ // get the type of the currently loaded resource
+ ITypeRoot typeRoot = ((ICompilationUnit) je);
+
+ if (typeRoot == null)
+ return null;
+
+ return getCompilationUnit(typeRoot);
+ }
+
+ public static CompilationUnit getCompilationUnit(ITypeRoot typeRoot) {
+ // get a reference to the shared AST of the loaded CompilationUnit
+ CompilationUnit cu = SharedASTProvider.getAST(typeRoot,
+ // do not wait for AST creation
+ SharedASTProvider.WAIT_YES, null);
+
+ return cu;
+ }
+
+ public static String insertExistingBundleRef(IDocument document,
+ IResource resource, int offset, int length,
+ String resourceBundleId, String key, Locale locale) {
+ String reference = "";
+ String newName = null;
+
+ CompilationUnit cu = getCompilationUnit(resource);
+
+ String variableName = ASTutils.resolveRBReferenceVar(document,
+ resource, offset, resourceBundleId, cu);
+ if (variableName == null)
+ newName = ASTutils.getNonExistingRBRefName(resourceBundleId,
+ document, cu);
+
+ try {
+ reference = ASTutils.createResourceReference(resourceBundleId, key,
+ locale, resource, offset, variableName == null ? newName
+ : variableName, document, cu);
+
+ document.replace(offset, length, reference);
+
+ // create non-internationalisation-comment
+ createReplaceNonInternationalisationComment(cu, document, offset);
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+
+ // TODO retrieve cu in the same way as in createResourceReference
+ // the current version does not parse method bodies
+
+ if (variableName == null) {
+ ASTutils.createResourceBundleReference(resource, offset, document,
+ resourceBundleId, locale, true, newName, cu);
+ // createReplaceNonInternationalisationComment(cu, document, pos);
+ }
+ return reference;
+ }
+
+ public static String insertNewBundleRef(IDocument document,
+ IResource resource, int startPos, int endPos,
+ String resourceBundleId, String key) {
+ String newName = null;
+ String reference = "";
+
+ CompilationUnit cu = getCompilationUnit(resource);
+
+ if (cu == null)
+ return null;
+
+ String variableName = ASTutils.resolveRBReferenceVar(document,
+ resource, startPos, resourceBundleId, cu);
+ if (variableName == null)
+ newName = ASTutils.getNonExistingRBRefName(resourceBundleId,
+ document, cu);
+
+ try {
+ reference = ASTutils.createResourceReference(resourceBundleId, key,
+ null, resource, startPos, variableName == null ? newName
+ : variableName, document, cu);
+
+ if (startPos > 0 && document.get().charAt(startPos - 1) == '\"') {
+ startPos--;
+ endPos++;
+ }
+
+ if ((startPos + endPos) < document.getLength()
+ && document.get().charAt(startPos + endPos) == '\"')
+ endPos++;
+
+ if ((startPos + endPos) < document.getLength()
+ && document.get().charAt(startPos + endPos - 1) == ';')
+ endPos--;
+
+ document.replace(startPos, endPos, reference);
+
+ // create non-internationalisation-comment
+ createReplaceNonInternationalisationComment(cu, document, startPos);
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+
+ if (variableName == null) {
+ // refresh reference to the shared AST of the loaded CompilationUnit
+ cu = getCompilationUnit(resource);
+
+ ASTutils.createResourceBundleReference(resource, startPos,
+ document, resourceBundleId, null, true, newName, cu);
+ // createReplaceNonInternationalisationComment(cu, document, pos);
+ }
+
+ return reference;
+ }
+
+ public static String resolveRBReferenceVar(IDocument document,
+ IResource resource, int pos, final String bundleId,
+ CompilationUnit cu) {
+ String bundleVar;
+
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
+ cu.accept(typeFinder);
+ AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
+ TypeDeclaration td = typeFinder.getEnclosingType();
+ MethodDeclaration meth = typeFinder.getEnclosingMethod();
+
+ if (atd == null) {
+ BundleDeclarationFinder bdf = new BundleDeclarationFinder(
+ bundleId,
+ td,
+ meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
+ td.accept(bdf);
+
+ bundleVar = bdf.getVariableName();
+ } else {
+ BundleDeclarationFinder bdf = new BundleDeclarationFinder(
+ bundleId,
+ atd,
+ meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC);
+ atd.accept(bdf);
+
+ bundleVar = bdf.getVariableName();
+ }
+
+ // Check also method body
+ if (meth != null) {
+ try {
+ InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder(
+ bundleId, pos);
+ typeFinder.getEnclosingMethod().accept(imbdf);
+ bundleVar = imbdf.getVariableName() != null ? imbdf
+ .getVariableName() : bundleVar;
+ } catch (Exception e) {
+ // ignore
+ }
+ }
+
+ return bundleVar;
+ }
+
+ public static String getNonExistingRBRefName(String bundleId,
+ IDocument document, CompilationUnit cu) {
+ String referenceName = null;
+ int i = 0;
+
+ while (referenceName == null) {
+ String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1)
+ + "Ref" + (i == 0 ? "" : i);
+ actRef = actRef.toLowerCase();
+
+ VariableFinder vf = new VariableFinder(actRef);
+ cu.accept(vf);
+
+ if (!vf.isVariableFound()) {
+ referenceName = actRef;
+ break;
+ }
+
+ i++;
+ }
+
+ return referenceName;
+ }
+
+ @Deprecated
+ public static String resolveResourceBundle(
+ MethodInvocation methodInvocation,
+ MethodParameterDescriptor rbDefinition,
+ Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
+ String bundleName = null;
+
+ if (methodInvocation.getExpression() instanceof SimpleName) {
+ SimpleName vName = (SimpleName) methodInvocation.getExpression();
+ IVariableBinding vBinding = (IVariableBinding) vName
+ .resolveBinding();
+ VariableDeclarationFragment dec = variableBindingManagers
+ .get(vBinding);
+
+ if (dec.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation init = (MethodInvocation) dec.getInitializer();
+
+ // Check declaring class
+ boolean isValidClass = false;
+ ITypeBinding type = init.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(
+ rbDefinition.getDeclaringClass())) {
+ isValidClass = true;
+ break;
+ } else {
+ if (rbDefinition.isConsiderSuperclass())
+ type = type.getSuperclass();
+ else
+ type = null;
+ }
+
+ }
+ if (!isValidClass)
+ return null;
+
+ boolean isValidMethod = false;
+ for (String mn : rbDefinition.getMethodName()) {
+ if (init.getName().getFullyQualifiedName().equals(mn)) {
+ isValidMethod = true;
+ break;
+ }
+ }
+ if (!isValidMethod)
+ return null;
+
+ // retrieve bundlename
+ if (init.arguments().size() < rbDefinition.getPosition() + 1)
+ return null;
+
+ bundleName = ((StringLiteral) init.arguments().get(
+ rbDefinition.getPosition())).getLiteralValue();
+ }
+ }
+
+ return bundleName;
+ }
+
+ public static SLLocation resolveResourceBundleLocation(
+ MethodInvocation methodInvocation,
+ MethodParameterDescriptor rbDefinition,
+ Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) {
+ SLLocation bundleDesc = null;
+
+ if (methodInvocation.getExpression() instanceof SimpleName) {
+ SimpleName vName = (SimpleName) methodInvocation.getExpression();
+ IVariableBinding vBinding = (IVariableBinding) vName
+ .resolveBinding();
+ VariableDeclarationFragment dec = variableBindingManagers
+ .get(vBinding);
+
+ if (dec.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation init = (MethodInvocation) dec.getInitializer();
+
+ // Check declaring class
+ boolean isValidClass = false;
+ ITypeBinding type = init.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(
+ rbDefinition.getDeclaringClass())) {
+ isValidClass = true;
+ break;
+ } else {
+ if (rbDefinition.isConsiderSuperclass())
+ type = type.getSuperclass();
+ else
+ type = null;
+ }
+
+ }
+ if (!isValidClass)
+ return null;
+
+ boolean isValidMethod = false;
+ for (String mn : rbDefinition.getMethodName()) {
+ if (init.getName().getFullyQualifiedName().equals(mn)) {
+ isValidMethod = true;
+ break;
+ }
+ }
+ if (!isValidMethod)
+ return null;
+
+ // retrieve bundlename
+ if (init.arguments().size() < rbDefinition.getPosition() + 1)
+ return null;
+
+ StringLiteral bundleLiteral = ((StringLiteral) init.arguments()
+ .get(rbDefinition.getPosition()));
+ bundleDesc = new SLLocation(null,
+ bundleLiteral.getStartPosition(),
+ bundleLiteral.getLength()
+ + bundleLiteral.getStartPosition(),
+ bundleLiteral.getLiteralValue());
+ }
+ }
+
+ return bundleDesc;
+ }
+
+ private static boolean isMatchingMethodDescriptor(
+ MethodInvocation methodInvocation, MethodParameterDescriptor desc) {
+ boolean result = false;
+
+ if (methodInvocation.resolveMethodBinding() == null)
+ return false;
+
+ String methodName = methodInvocation.resolveMethodBinding().getName();
+
+ // Check declaring class
+ ITypeBinding type = methodInvocation.resolveMethodBinding()
+ .getDeclaringClass();
+ while (type != null) {
+ if (type.getQualifiedName().equals(desc.getDeclaringClass())) {
+ result = true;
+ break;
+ } else {
+ if (desc.isConsiderSuperclass())
+ type = type.getSuperclass();
+ else
+ type = null;
+ }
+
+ }
+
+ if (!result)
+ return false;
+
+ result = !result;
+
+ // Check method name
+ for (String method : desc.getMethodName()) {
+ if (method.equals(methodName)) {
+ result = true;
+ break;
+ }
+ }
+
+ return result;
+ }
+
+ public static boolean isMatchingMethodParamDesc(
+ MethodInvocation methodInvocation, String literal,
+ MethodParameterDescriptor desc) {
+ boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
+
+ if (!result)
+ return false;
+ else
+ result = false;
+
+ if (methodInvocation.arguments().size() > desc.getPosition()) {
+ if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) {
+ StringLiteral sl = (StringLiteral) methodInvocation.arguments()
+ .get(desc.getPosition());
+ if (sl.getLiteralValue().trim().toLowerCase()
+ .equals(literal.toLowerCase()))
+ result = true;
+ }
+ }
+
+ return result;
+ }
+
+ public static boolean isMatchingMethodParamDesc(
+ MethodInvocation methodInvocation, StringLiteral literal,
+ MethodParameterDescriptor desc) {
+ int keyParameter = desc.getPosition();
+ boolean result = isMatchingMethodDescriptor(methodInvocation, desc);
+
+ if (!result)
+ return false;
+
+ // Check position within method call
+ StructuralPropertyDescriptor spd = literal.getLocationInParent();
+ if (spd.isChildListProperty()) {
+ List<ASTNode> arguments = (List<ASTNode>) methodInvocation
+ .getStructuralProperty(spd);
+ result = (arguments.size() > keyParameter && arguments
+ .get(keyParameter) == literal);
+ }
+
+ return result;
+ }
+
+ public static ICompilationUnit createCompilationUnit(IResource resource) {
+ // Instantiate a new AST parser
+ ASTParser parser = ASTParser.newParser(AST.JLS3);
+ parser.setResolveBindings(true);
+
+ ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource
+ .getProject().getFile(resource.getRawLocation()));
+
+ return cu;
+ }
+
+ public static CompilationUnit createCompilationUnit(IDocument document) {
+ // Instantiate a new AST parser
+ ASTParser parser = ASTParser.newParser(AST.JLS3);
+ parser.setResolveBindings(true);
+
+ parser.setSource(document.get().toCharArray());
+ return (CompilationUnit) parser.createAST(null);
+ }
+
+ public static void createImport(IDocument doc, IResource resource,
+ CompilationUnit cu, AST ast, ASTRewrite rewriter,
+ String qualifiedClassName) throws CoreException,
+ BadLocationException {
+
+ ImportFinder impFinder = new ImportFinder(qualifiedClassName);
+
+ cu.accept(impFinder);
+
+ if (!impFinder.isImportFound()) {
+ // ITextFileBufferManager bufferManager =
+ // FileBuffers.getTextFileBufferManager();
+ // IPath path = resource.getFullPath();
+ //
+ // bufferManager.connect(path, LocationKind.IFILE, null);
+ // ITextFileBuffer textFileBuffer =
+ // bufferManager.getTextFileBuffer(doc);
+
+ // TODO create new import
+ ImportDeclaration id = ast.newImportDeclaration();
+ id.setName(ast.newName(qualifiedClassName.split("\\.")));
+ id.setStatic(false);
+
+ ListRewrite lrw = rewriter.getListRewrite(cu, cu.IMPORTS_PROPERTY);
+ lrw.insertFirst(id, null);
+
+ // TextEdit te = rewriter.rewriteAST(doc, null);
+ // te.apply(doc);
+ //
+ // if (textFileBuffer != null)
+ // textFileBuffer.commit(null, false);
+ // else
+ // FileUtils.saveTextFile(resource.getProject().getFile(resource.getProjectRelativePath()),
+ // doc.get());
+ // bufferManager.disconnect(path, LocationKind.IFILE, null);
+ }
+
+ }
+
+ // TODO export initializer specification into a methodinvocationdefinition
+ public static void createResourceBundleReference(IResource resource,
+ int typePos, IDocument doc, String bundleId, Locale locale,
+ boolean globalReference, String variableName, CompilationUnit cu) {
+
+ try {
+
+ if (globalReference) {
+
+ // retrieve compilation unit from document
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(
+ typePos);
+ cu.accept(typeFinder);
+ ASTNode node = typeFinder.getEnclosingType();
+ ASTNode anonymNode = typeFinder.getEnclosingAnonymType();
+ if (anonymNode != null)
+ node = anonymNode;
+
+ MethodDeclaration meth = typeFinder.getEnclosingMethod();
+ AST ast = node.getAST();
+
+ VariableDeclarationFragment vdf = ast
+ .newVariableDeclarationFragment();
+ vdf.setName(ast.newSimpleName(variableName));
+
+ // set initializer
+ vdf.setInitializer(createResourceBundleGetter(ast, bundleId,
+ locale));
+
+ FieldDeclaration fd = ast.newFieldDeclaration(vdf);
+ fd.setType(ast.newSimpleType(ast
+ .newName(new String[] { "ResourceBundle" })));
+
+ if (meth != null
+ && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
+ fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC));
+
+ // rewrite AST
+ ASTRewrite rewriter = ASTRewrite.create(ast);
+ ListRewrite lrw = rewriter
+ .getListRewrite(
+ node,
+ node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY
+ : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
+ lrw.insertAt(fd, /*
+ * findIndexOfLastField(node.bodyDeclarations())
+ * +1
+ */
+ 0, null);
+
+ // create import if required
+ createImport(doc, resource, cu, ast, rewriter,
+ getRBDefinitionDesc().getDeclaringClass());
+
+ TextEdit te = rewriter.rewriteAST(doc, null);
+ te.apply(doc);
+ } else {
+
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static int findIndexOfLastField(List bodyDeclarations) {
+ for (int i = bodyDeclarations.size() - 1; i >= 0; i--) {
+ BodyDeclaration each = (BodyDeclaration) bodyDeclarations.get(i);
+ if (each instanceof FieldDeclaration)
+ return i;
+ }
+ return -1;
+ }
+
+ protected static MethodInvocation createResourceBundleGetter(AST ast,
+ String bundleId, Locale locale) {
+ MethodInvocation mi = ast.newMethodInvocation();
+
+ mi.setName(ast.newSimpleName("getBundle"));
+ mi.setExpression(ast.newName(new String[] { "ResourceBundle" }));
+
+ // Add bundle argument
+ StringLiteral sl = ast.newStringLiteral();
+ sl.setLiteralValue(bundleId);
+ mi.arguments().add(sl);
+
+ // TODO Add Locale argument
+
+ return mi;
+ }
+
+ public static ASTNode getEnclosingType(CompilationUnit cu, int pos) {
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
+ cu.accept(typeFinder);
+ return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder
+ .getEnclosingAnonymType() : typeFinder.getEnclosingType();
+ }
+
+ public static ASTNode getEnclosingType(ASTNode cu, int pos) {
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos);
+ cu.accept(typeFinder);
+ return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder
+ .getEnclosingAnonymType() : typeFinder.getEnclosingType();
+ }
+
+ protected static MethodInvocation referenceResource(AST ast,
+ String accessorName, String key, Locale locale) {
+ MethodParameterDescriptor accessorDesc = getRBAccessorDesc();
+ MethodInvocation mi = ast.newMethodInvocation();
+
+ mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0)));
+
+ // Declare expression
+ StringLiteral sl = ast.newStringLiteral();
+ sl.setLiteralValue(key);
+
+ // TODO define locale expression
+ if (mi.arguments().size() == accessorDesc.getPosition())
+ mi.arguments().add(sl);
+
+ SimpleName name = ast.newSimpleName(accessorName);
+ mi.setExpression(name);
+
+ return mi;
+ }
+
+ public static String createResourceReference(String bundleId, String key,
+ Locale locale, IResource resource, int typePos,
+ String accessorName, IDocument doc, CompilationUnit cu) {
+
+ PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos);
+ cu.accept(typeFinder);
+ AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType();
+ TypeDeclaration td = typeFinder.getEnclosingType();
+
+ // retrieve compilation unit from document
+ ASTNode node = atd == null ? td : atd;
+ AST ast = node.getAST();
+
+ ExpressionStatement expressionStatement = ast
+ .newExpressionStatement(referenceResource(ast, accessorName,
+ key, locale));
+
+ String exp = expressionStatement.toString();
+
+ // remove semicolon and line break at the end of this expression
+ // statement
+ if (exp.endsWith(";\n"))
+ exp = exp.substring(0, exp.length() - 2);
+
+ return exp;
+ }
+
+ private static int findNonInternationalisationPosition(CompilationUnit cu,
+ IDocument doc, int offset) {
+ LinePreStringsFinder lsfinder = null;
+ try {
+ lsfinder = new LinePreStringsFinder(offset, doc);
+ cu.accept(lsfinder);
+ } catch (BadLocationException e) {
+ Logger.logError(e);
+ }
+ if (lsfinder == null)
+ return 1;
+
+ List<StringLiteral> strings = lsfinder.getStrings();
+
+ return strings.size() + 1;
+ }
+
+ public static void createReplaceNonInternationalisationComment(
+ CompilationUnit cu, IDocument doc, int position) {
+ int i = findNonInternationalisationPosition(cu, doc, position);
+
+ IRegion reg;
+ try {
+ reg = doc.getLineInformationOfOffset(position);
+ doc.replace(reg.getOffset() + reg.getLength(), 0, " //$NON-NLS-"
+ + i + "$");
+ } catch (BadLocationException e) {
+ Logger.logError(e);
+ }
+ }
+
+ private static void createASTNonInternationalisationComment(
+ CompilationUnit cu, IDocument doc, ASTNode parent, ASTNode fd,
+ ASTRewrite rewriter, ListRewrite lrw) {
+ int i = 1;
+
+ // ListRewrite lrw2 = rewriter.getListRewrite(node,
+ // Block.STATEMENTS_PROPERTY);
+ ASTNode placeHolder = rewriter.createStringPlaceholder("//$NON-NLS-"
+ + i + "$", ASTNode.LINE_COMMENT);
+ lrw.insertAfter(placeHolder, fd, null);
+ }
+
+ public static boolean existsNonInternationalisationComment(
+ StringLiteral literal) throws BadLocationException {
+ CompilationUnit cu = (CompilationUnit) literal.getRoot();
+ ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();
+
+ IDocument doc = null;
+ try {
+ doc = new Document(icu.getSource());
+ } catch (JavaModelException e) {
+ Logger.logError(e);
+ }
+
+ // get whole line in which string literal
+ int lineNo = doc.getLineOfOffset(literal.getStartPosition());
+ int lineOffset = doc.getLineOffset(lineNo);
+ int lineLength = doc.getLineLength(lineNo);
+ String lineOfString = doc.get(lineOffset, lineLength);
+
+ // search for a line comment in this line
+ int indexComment = lineOfString.indexOf("//");
+
+ if (indexComment == -1)
+ return false;
+
+ String comment = lineOfString.substring(indexComment);
+
+ // remove first "//" of line comment
+ comment = comment.substring(2).toLowerCase();
+
+ // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3
+ String[] comments = comment.split("//");
+
+ for (String commentFrag : comments) {
+ commentFrag = commentFrag.trim();
+
+ // if comment match format: "$non-nls$" then ignore whole line
+ if (commentFrag.matches("^\\$non-nls\\$$")) {
+ return true;
+
+ // if comment match format: "$non-nls-{number}$" then only
+ // ignore string which is on given position
+ } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) {
+ int iString = findNonInternationalisationPosition(cu, doc,
+ literal.getStartPosition());
+ int iComment = new Integer(commentFrag.substring(9, 10));
+ if (iString == iComment)
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static StringLiteral getStringAtPos(CompilationUnit cu, int position) {
+ StringFinder strFinder = new StringFinder(position);
+ cu.accept(strFinder);
+ return strFinder.getString();
+ }
+
+ static class PositionalTypeFinder extends ASTVisitor {
+
+ private int position;
+ private TypeDeclaration enclosingType;
+ private AnonymousClassDeclaration enclosingAnonymType;
+ private MethodDeclaration enclosingMethod;
+
+ public PositionalTypeFinder(int pos) {
+ position = pos;
+ }
+
+ public TypeDeclaration getEnclosingType() {
+ return enclosingType;
+ }
+
+ public AnonymousClassDeclaration getEnclosingAnonymType() {
+ return enclosingAnonymType;
+ }
+
+ public MethodDeclaration getEnclosingMethod() {
+ return enclosingMethod;
+ }
+
+ @Override
+ public boolean visit(MethodDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingMethod = node;
+ return true;
+ } else
+ return false;
+ }
+
+ @Override
+ public boolean visit(TypeDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingType = node;
+ return true;
+ } else
+ return false;
+ }
+
+ @Override
+ public boolean visit(AnonymousClassDeclaration node) {
+ if (position >= node.getStartPosition()
+ && position <= (node.getStartPosition() + node.getLength())) {
+ enclosingAnonymType = node;
+ return true;
+ } else
+ return false;
+ }
+ }
+
+ static class ImportFinder extends ASTVisitor {
+
+ String qName;
+ boolean importFound = false;
+
+ public ImportFinder(String qName) {
+ this.qName = qName;
+ }
+
+ public boolean isImportFound() {
+ return importFound;
+ }
+
+ @Override
+ public boolean visit(ImportDeclaration id) {
+ if (id.getName().getFullyQualifiedName().equals(qName))
+ importFound = true;
+
+ return true;
+ }
+ }
+
+ static class VariableFinder extends ASTVisitor {
+
+ boolean found = false;
+ String variableName;
+
+ public boolean isVariableFound() {
+ return found;
+ }
+
+ public VariableFinder(String variableName) {
+ this.variableName = variableName;
+ }
+
+ @Override
+ public boolean visit(VariableDeclarationFragment vdf) {
+ if (vdf.getName().getFullyQualifiedName().equals(variableName)) {
+ found = true;
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ static class InMethodBundleDeclFinder extends ASTVisitor {
+ String varName;
+ String bundleId;
+ int pos;
+
+ public InMethodBundleDeclFinder(String bundleId, int pos) {
+ this.bundleId = bundleId;
+ this.pos = pos;
+ }
+
+ public String getVariableName() {
+ return varName;
+ }
+
+ @Override
+ public boolean visit(VariableDeclarationFragment fdvd) {
+ if (fdvd.getStartPosition() > pos)
+ return false;
+
+ // boolean bStatic = (fdvd.resolveBinding().getModifiers() &
+ // Modifier.STATIC) == Modifier.STATIC;
+ // if (!bStatic && isStatic)
+ // return true;
+
+ String tmpVarName = fdvd.getName().getFullyQualifiedName();
+
+ if (fdvd.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer();
+ if (isMatchingMethodParamDesc(fdi, bundleId,
+ getRBDefinitionDesc()))
+ varName = tmpVarName;
+ }
+ return true;
+ }
+ }
+
+ static class BundleDeclarationFinder extends ASTVisitor {
+
+ String varName;
+ String bundleId;
+ ASTNode typeDef;
+ boolean isStatic;
+
+ public BundleDeclarationFinder(String bundleId, ASTNode td,
+ boolean isStatic) {
+ this.bundleId = bundleId;
+ this.typeDef = td;
+ this.isStatic = isStatic;
+ }
+
+ public String getVariableName() {
+ return varName;
+ }
+
+ @Override
+ public boolean visit(MethodDeclaration md) {
+ return true;
+ }
+
+ @Override
+ public boolean visit(FieldDeclaration fd) {
+ if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef)
+ return false;
+
+ boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
+ if (!bStatic && isStatic)
+ return true;
+
+ if (fd.getType() instanceof SimpleType) {
+ SimpleType fdType = (SimpleType) fd.getType();
+ String typeName = fdType.getName().getFullyQualifiedName();
+ String referenceName = getRBDefinitionDesc()
+ .getDeclaringClass();
+ if (typeName.equals(referenceName)
+ || (referenceName.lastIndexOf(".") >= 0 && typeName
+ .equals(referenceName.substring(referenceName
+ .lastIndexOf(".") + 1)))) {
+ // Check VariableDeclarationFragment
+ if (fd.fragments().size() == 1) {
+ if (fd.fragments().get(0) instanceof VariableDeclarationFragment) {
+ VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd
+ .fragments().get(0);
+ String tmpVarName = fdvd.getName()
+ .getFullyQualifiedName();
+
+ if (fdvd.getInitializer() instanceof MethodInvocation) {
+ MethodInvocation fdi = (MethodInvocation) fdvd
+ .getInitializer();
+ if (isMatchingMethodParamDesc(fdi, bundleId,
+ getRBDefinitionDesc()))
+ varName = tmpVarName;
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ }
+
+ static class LinePreStringsFinder extends ASTVisitor {
+ private int position;
+ private int line;
+ private List<StringLiteral> strings;
+ private IDocument document;
+
+ public LinePreStringsFinder(int position, IDocument document)
+ throws BadLocationException {
+ this.document = document;
+ this.position = position;
+ line = document.getLineOfOffset(position);
+ strings = new ArrayList<StringLiteral>();
+ }
+
+ public List<StringLiteral> getStrings() {
+ return strings;
+ }
+
+ @Override
+ public boolean visit(StringLiteral node) {
+ try {
+ if (line == document.getLineOfOffset(node.getStartPosition())
+ && node.getStartPosition() < position) {
+ strings.add(node);
+ return true;
+ }
+ } catch (BadLocationException e) {
+ }
+ return true;
+ }
+ }
+
+ static class StringFinder extends ASTVisitor {
+ private int position;
+ private StringLiteral string;
+
+ public StringFinder(int position) {
+ this.position = position;
+ }
+
+ public StringLiteral getString() {
+ return string;
+ }
+
+ @Override
+ public boolean visit(StringLiteral node) {
+ if (position > node.getStartPosition()
+ && position < (node.getStartPosition() + node.getLength()))
+ string = node;
+ return true;
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java
index 4f2201bb..e7833c63 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java
@@ -1,101 +1,108 @@
-package org.eclipse.babel.tapiji.tools.rbmanager;
-
-import java.io.File;
-import java.net.URISyntaxException;
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.util.OverlayIcon;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.swt.graphics.Image;
-
-public class ImageUtils {
- private static final ImageRegistry imageRegistry = new ImageRegistry();
-
- private static final String WARNING_FLAG_IMAGE = "warning_flag.gif";
- private static final String FRAGMENT_FLAG_IMAGE = "fragment_flag.gif";
- public static final String WARNING_IMAGE = "warning.gif";
- public static final String FRAGMENT_PROJECT_IMAGE = "fragmentproject.gif";
- public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif";
- public static final String EXPAND = "expand.gif";
- public static final String DEFAULT_LOCALICON = File.separatorChar+"countries"+File.separatorChar+"_f.gif";
- public static final String LOCATION_WITHOUT_ICON = File.separatorChar+"countries"+File.separatorChar+"un.gif";
-
- /**
- * @return a Image from the folder 'icons'
- * @throws URISyntaxException
- */
- public static Image getBaseImage(String imageName){
- Image image = imageRegistry.get(imageName);
- if (image == null) {
- ImageDescriptor descriptor = RBManagerActivator.getImageDescriptor(imageName);
-
- if (descriptor.getImageData() != null){
- image = descriptor.createImage(false);
- imageRegistry.put(imageName, image);
- }
- }
-
- return image;
- }
-
- /**
- * @param baseImage
- * @return baseImage with a overlay warning-image
- */
- public static Image getImageWithWarning(Image baseImage){
- String imageWithWarningId = baseImage.toString()+".w";
- Image imageWithWarning = imageRegistry.get(imageWithWarningId);
-
- if (imageWithWarning==null){
- Image warningImage = getBaseImage(WARNING_FLAG_IMAGE);
- imageWithWarning = new OverlayIcon(baseImage, warningImage, OverlayIcon.BOTTOM_LEFT).createImage();
- imageRegistry.put(imageWithWarningId, imageWithWarning);
- }
-
- return imageWithWarning;
- }
-
- /**
- *
- * @param baseImage
- * @return baseImage with a overlay fragment-image
- */
- public static Image getImageWithFragment(Image baseImage){
- String imageWithFragmentId = baseImage.toString()+".f";
- Image imageWithFragment = imageRegistry.get(imageWithFragmentId);
-
- if (imageWithFragment==null){
- Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE);
- imageWithFragment = new OverlayIcon(baseImage, fragement, OverlayIcon.BOTTOM_RIGHT).createImage();
- imageRegistry.put(imageWithFragmentId, imageWithFragment);
- }
-
- return imageWithFragment;
- }
-
- /**
- * @return a Image with a flag of the given country
- */
- public static Image getLocalIcon(Locale locale) {
- String imageName;
- Image image = null;
-
- if (locale != null && !locale.getCountry().equals("")){
- imageName = File.separatorChar+"countries"+File.separatorChar+ locale.getCountry().toLowerCase() +".gif";
- image = getBaseImage(imageName);
- }else {
- if (locale != null){
- imageName = File.separatorChar+"countries"+File.separatorChar+"l_"+locale.getLanguage().toLowerCase()+".gif";
- image = getBaseImage(imageName);
- }else {
- imageName = DEFAULT_LOCALICON.toLowerCase(); //Default locale icon
- image = getBaseImage(imageName);
- }
- }
-
- if (image == null) image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase());
- return image;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager;
+
+import java.io.File;
+import java.net.URISyntaxException;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.util.OverlayIcon;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.ImageRegistry;
+import org.eclipse.swt.graphics.Image;
+
+public class ImageUtils {
+ private static final ImageRegistry imageRegistry = new ImageRegistry();
+
+ private static final String WARNING_FLAG_IMAGE = "warning_flag.gif";
+ private static final String FRAGMENT_FLAG_IMAGE = "fragment_flag.gif";
+ public static final String WARNING_IMAGE = "warning.gif";
+ public static final String FRAGMENT_PROJECT_IMAGE = "fragmentproject.gif";
+ public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif";
+ public static final String EXPAND = "expand.gif";
+ public static final String DEFAULT_LOCALICON = File.separatorChar+"countries"+File.separatorChar+"_f.gif";
+ public static final String LOCATION_WITHOUT_ICON = File.separatorChar+"countries"+File.separatorChar+"un.gif";
+
+ /**
+ * @return a Image from the folder 'icons'
+ * @throws URISyntaxException
+ */
+ public static Image getBaseImage(String imageName){
+ Image image = imageRegistry.get(imageName);
+ if (image == null) {
+ ImageDescriptor descriptor = RBManagerActivator.getImageDescriptor(imageName);
+
+ if (descriptor.getImageData() != null){
+ image = descriptor.createImage(false);
+ imageRegistry.put(imageName, image);
+ }
+ }
+
+ return image;
+ }
+
+ /**
+ * @param baseImage
+ * @return baseImage with a overlay warning-image
+ */
+ public static Image getImageWithWarning(Image baseImage){
+ String imageWithWarningId = baseImage.toString()+".w";
+ Image imageWithWarning = imageRegistry.get(imageWithWarningId);
+
+ if (imageWithWarning==null){
+ Image warningImage = getBaseImage(WARNING_FLAG_IMAGE);
+ imageWithWarning = new OverlayIcon(baseImage, warningImage, OverlayIcon.BOTTOM_LEFT).createImage();
+ imageRegistry.put(imageWithWarningId, imageWithWarning);
+ }
+
+ return imageWithWarning;
+ }
+
+ /**
+ *
+ * @param baseImage
+ * @return baseImage with a overlay fragment-image
+ */
+ public static Image getImageWithFragment(Image baseImage){
+ String imageWithFragmentId = baseImage.toString()+".f";
+ Image imageWithFragment = imageRegistry.get(imageWithFragmentId);
+
+ if (imageWithFragment==null){
+ Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE);
+ imageWithFragment = new OverlayIcon(baseImage, fragement, OverlayIcon.BOTTOM_RIGHT).createImage();
+ imageRegistry.put(imageWithFragmentId, imageWithFragment);
+ }
+
+ return imageWithFragment;
+ }
+
+ /**
+ * @return a Image with a flag of the given country
+ */
+ public static Image getLocalIcon(Locale locale) {
+ String imageName;
+ Image image = null;
+
+ if (locale != null && !locale.getCountry().equals("")){
+ imageName = File.separatorChar+"countries"+File.separatorChar+ locale.getCountry().toLowerCase() +".gif";
+ image = getBaseImage(imageName);
+ }else {
+ if (locale != null){
+ imageName = File.separatorChar+"countries"+File.separatorChar+"l_"+locale.getLanguage().toLowerCase()+".gif";
+ image = getBaseImage(imageName);
+ }else {
+ imageName = DEFAULT_LOCALICON.toLowerCase(); //Default locale icon
+ image = getBaseImage(imageName);
+ }
+ }
+
+ if (image == null) image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase());
+ return image;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java
index 635f1eee..e4ac257f 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java
@@ -1,56 +1,63 @@
-package org.eclipse.babel.tapiji.tools.rbmanager;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class RBManagerActivator extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.rbmanager"; //$NON-NLS-1$
- // The shared instance
- private static RBManagerActivator plugin;
-
-
- /**
- * The constructor
- */
- public RBManagerActivator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static RBManagerActivator getDefault() {
- return plugin;
- }
-
- public static ImageDescriptor getImageDescriptor(String name){
- String path = "icons/" + name;
-
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class RBManagerActivator extends AbstractUIPlugin {
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.rbmanager"; //$NON-NLS-1$
+ // The shared instance
+ private static RBManagerActivator plugin;
+
+
+ /**
+ * The constructor
+ */
+ public RBManagerActivator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static RBManagerActivator getDefault() {
+ return plugin;
+ }
+
+ public static ImageDescriptor getImageDescriptor(String name){
+ String path = "icons/" + name;
+
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
index ee1f7d9a..2c016bca 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java
@@ -1,60 +1,67 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.auditor;
-
-import java.io.Serializable;
-
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.core.resources.IFile;
-
-public class RBLocation implements ILocation {
- private IFile file;
- private int startPos, endPos;
- private String language;
- private Serializable data;
- private ILocation sameValuePartner;
-
-
- public RBLocation(IFile file, int startPos, int endPos, String language) {
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.language = language;
- }
-
- public RBLocation(IFile file, int startPos, int endPos, String language, ILocation sameValuePartner) {
- this(file, startPos, endPos, language);
- this.sameValuePartner=sameValuePartner;
- }
-
- @Override
- public IFile getFile() {
- return file;
- }
-
- @Override
- public int getStartPos() {
- return startPos;
- }
-
- @Override
- public int getEndPos() {
- return endPos;
- }
-
- @Override
- public String getLiteral() {
- return language;
- }
-
- @Override
- public Serializable getData () {
- return data;
- }
-
- public void setData (Serializable data) {
- this.data = data;
- }
-
- public ILocation getSameValuePartner(){
- return sameValuePartner;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.auditor;
+
+import java.io.Serializable;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IFile;
+
+public class RBLocation implements ILocation {
+ private IFile file;
+ private int startPos, endPos;
+ private String language;
+ private Serializable data;
+ private ILocation sameValuePartner;
+
+
+ public RBLocation(IFile file, int startPos, int endPos, String language) {
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.language = language;
+ }
+
+ public RBLocation(IFile file, int startPos, int endPos, String language, ILocation sameValuePartner) {
+ this(file, startPos, endPos, language);
+ this.sameValuePartner=sameValuePartner;
+ }
+
+ @Override
+ public IFile getFile() {
+ return file;
+ }
+
+ @Override
+ public int getStartPos() {
+ return startPos;
+ }
+
+ @Override
+ public int getEndPos() {
+ return endPos;
+ }
+
+ @Override
+ public String getLiteral() {
+ return language;
+ }
+
+ @Override
+ public Serializable getData () {
+ return data;
+ }
+
+ public void setData (Serializable data) {
+ this.data = data;
+ }
+
+ public ILocation getSameValuePartner(){
+ return sameValuePartner;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
index fb525107..5328590c 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java
@@ -1,243 +1,250 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.auditor;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.babel.core.configuration.ConfigurationManager;
-import org.eclipse.babel.core.configuration.IConfiguration;
-import org.eclipse.babel.tapiji.tools.core.extensions.I18nRBAuditor;
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.auditor.quickfix.MissingLanguageResolution;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ui.IMarkerResolution;
-
-/**
- *
- */
-public class ResourceBundleAuditor extends I18nRBAuditor {
- private static final String LANGUAGE_ATTRIBUTE = "key";
-
- private List<ILocation> unspecifiedKeys = new LinkedList<ILocation>();
- private Map<ILocation, ILocation> sameValues = new HashMap<ILocation, ILocation>();
- private List<ILocation> missingLanguages = new LinkedList<ILocation>();
- private List<String> seenRBs = new LinkedList<String>();
-
-
- @Override
- public String[] getFileEndings() {
- return new String[] { "properties" };
- }
-
- @Override
- public String getContextId() {
- return "resourcebundle";
- }
-
- @Override
- public List<ILocation> getUnspecifiedKeyReferences() {
- return unspecifiedKeys;
- }
-
- @Override
- public Map<ILocation, ILocation> getSameValuesReferences() {
- return sameValues;
- }
-
- @Override
- public List<ILocation> getMissingLanguageReferences() {
- return missingLanguages;
- }
-
- /*
- * Forgets all save rbIds in seenRB and reset all problem-lists
- */
- @Override
- public void resetProblems() {
- unspecifiedKeys = new LinkedList<ILocation>();
- sameValues = new HashMap<ILocation, ILocation>();
- missingLanguages = new LinkedList<ILocation>();
- seenRBs = new LinkedList<String>();
- }
-
- /*
- * Finds the corresponding ResouceBundle for the resource. Checks if the
- * ResourceBundle is already audit and it is not already executed audit the
- * hole ResourceBundle and save the rbId in seenRB
- */
- @Override
- public void audit(IResource resource) {
- if (!RBFileUtils.isResourceBundleFile(resource))
- return;
-
- IFile file = (IFile) resource;
- String rbId = RBFileUtils.getCorrespondingResourceBundleId(file);
-
- if (!seenRBs.contains(rbId)) {
- ResourceBundleManager rbmanager = ResourceBundleManager
- .getManager(file.getProject());
- audit(rbId, rbmanager);
- seenRBs.add(rbId);
- } else
- return;
- }
-
- /*
- * audits all files of a resourcebundle
- */
- public void audit(String rbId, ResourceBundleManager rbmanager) {
- IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration();
- IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId);
- Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId);
- String[] keys = bundlegroup.getMessageKeys();
-
-
- for (IResource r : bundlefile) {
- IFile f1 = (IFile) r;
-
- for (String key : keys) {
- // check if all keys have a value
-
- if (auditUnspecifiedKey(f1, key, bundlegroup)){
- /* do nothing - all just done*/
- }else {
- // check if a key has the same value like a key of an other properties-file
- if (configuration.getAuditSameValue() && bundlefile.size() > 1)
- for (IResource r2 : bundlefile) {
- IFile f2 = (IFile) r2;
- auditSameValues(f1, f2, key, bundlegroup);
- }
- }
- }
- }
-
- if (configuration.getAuditMissingLanguage()){
- // checks if the resourcebundle supports all project-languages
- Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId);
- Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales();
-
- auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId);
- }
- }
-
- /*
- * Audits the file if the key is not specified. If the value is null reports a
- * problem.
- */
- private boolean auditUnspecifiedKey(IFile f1, String key,
- IMessagesBundleGroup bundlegroup) {
- if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) {
- int pos = calculateKeyLine(key, f1);
- unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key));
- return true;
- } else
- return false;
- }
-
- /*
- * Compares a key in different files and reports a problem, if the values are
- * same. It doesn't compare the files if one file is the Default-file
- */
- private void auditSameValues(IFile f1, IFile f2, String key,
- IMessagesBundleGroup bundlegroup) {
- Locale l1 = RBFileUtils.getLocale(f1);
- Locale l2 = RBFileUtils.getLocale(f2);
-
- if (!l2.equals(l1) && !(l1.toString().equals("")||l2.toString().equals(""))) {
- IMessage message = bundlegroup.getMessage(key, l2);
-
- if (message != null)
- if (bundlegroup.getMessage(key, l1).getValue()
- .equals(message.getValue())) {
- int pos1 = calculateKeyLine(key, f1);
- int pos2 = calculateKeyLine(key, f2);
- sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key),
- new RBLocation(f2, pos2, pos2 + 1, key));
- }
- }
- }
-
- /*
- * Checks if the resourcebundle supports all project-languages and report
- * missing languages.
- */
- private void auditMissingLanguage(Set<Locale> rbLocales,
- Set<Locale> projectLocales, ResourceBundleManager rbmanager,
- String rbId) {
- for (Locale pLocale : projectLocales) {
- if (!rbLocales.contains(pLocale)) {
- String language = pLocale != null ? pLocale.toString() : ResourceBundleManager.defaultLocaleTag;
-
- // Add Warning to default-file or a random chosen file
- IResource representative = rbmanager.getResourceBundleFile(
- rbId, null);
- if (representative == null)
- representative = rbmanager.getRandomFile(rbId);
- missingLanguages.add(new RBLocation((IFile) representative, 1,
- 2, language));
- }
- }
- }
-
- /*
- * Finds a position where the key is located or missing
- */
- private int calculateKeyLine(String key, IFile file) {
- int linenumber = 1;
- try {
-// if (!Boolean.valueOf(System.getProperty("dirty"))) {
-// System.setProperty("dirty", "true");
- file.refreshLocal(IFile.DEPTH_ZERO, null);
- InputStream is = file.getContents();
- BufferedReader bf = new BufferedReader(new InputStreamReader(is));
- String line;
- while ((line = bf.readLine()) != null) {
- if ((!line.isEmpty()) && (!line.startsWith("#"))
- && (line.compareTo(key) > 0))
- return linenumber;
- linenumber++;
- }
-// System.setProperty("dirty", "false");
-// }
- } catch (CoreException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return linenumber;
- }
-
- @Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
-
- switch (marker.getAttribute("cause", -1)) {
- case IMarkerConstants.CAUSE_MISSING_LANGUAGE:
- Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO
- // change
- // Name
- resolutions.add(new MissingLanguageResolution(l));
- break;
- }
-
- return resolutions;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.auditor;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.babel.core.configuration.ConfigurationManager;
+import org.eclipse.babel.core.configuration.IConfiguration;
+import org.eclipse.babel.tapiji.tools.core.extensions.I18nRBAuditor;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.auditor.quickfix.MissingLanguageResolution;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.ui.IMarkerResolution;
+
+/**
+ *
+ */
+public class ResourceBundleAuditor extends I18nRBAuditor {
+ private static final String LANGUAGE_ATTRIBUTE = "key";
+
+ private List<ILocation> unspecifiedKeys = new LinkedList<ILocation>();
+ private Map<ILocation, ILocation> sameValues = new HashMap<ILocation, ILocation>();
+ private List<ILocation> missingLanguages = new LinkedList<ILocation>();
+ private List<String> seenRBs = new LinkedList<String>();
+
+
+ @Override
+ public String[] getFileEndings() {
+ return new String[] { "properties" };
+ }
+
+ @Override
+ public String getContextId() {
+ return "resourcebundle";
+ }
+
+ @Override
+ public List<ILocation> getUnspecifiedKeyReferences() {
+ return unspecifiedKeys;
+ }
+
+ @Override
+ public Map<ILocation, ILocation> getSameValuesReferences() {
+ return sameValues;
+ }
+
+ @Override
+ public List<ILocation> getMissingLanguageReferences() {
+ return missingLanguages;
+ }
+
+ /*
+ * Forgets all save rbIds in seenRB and reset all problem-lists
+ */
+ @Override
+ public void resetProblems() {
+ unspecifiedKeys = new LinkedList<ILocation>();
+ sameValues = new HashMap<ILocation, ILocation>();
+ missingLanguages = new LinkedList<ILocation>();
+ seenRBs = new LinkedList<String>();
+ }
+
+ /*
+ * Finds the corresponding ResouceBundle for the resource. Checks if the
+ * ResourceBundle is already audit and it is not already executed audit the
+ * hole ResourceBundle and save the rbId in seenRB
+ */
+ @Override
+ public void audit(IResource resource) {
+ if (!RBFileUtils.isResourceBundleFile(resource))
+ return;
+
+ IFile file = (IFile) resource;
+ String rbId = RBFileUtils.getCorrespondingResourceBundleId(file);
+
+ if (!seenRBs.contains(rbId)) {
+ ResourceBundleManager rbmanager = ResourceBundleManager
+ .getManager(file.getProject());
+ audit(rbId, rbmanager);
+ seenRBs.add(rbId);
+ } else
+ return;
+ }
+
+ /*
+ * audits all files of a resourcebundle
+ */
+ public void audit(String rbId, ResourceBundleManager rbmanager) {
+ IConfiguration configuration = ConfigurationManager.getInstance().getConfiguration();
+ IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId);
+ Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId);
+ String[] keys = bundlegroup.getMessageKeys();
+
+
+ for (IResource r : bundlefile) {
+ IFile f1 = (IFile) r;
+
+ for (String key : keys) {
+ // check if all keys have a value
+
+ if (auditUnspecifiedKey(f1, key, bundlegroup)){
+ /* do nothing - all just done*/
+ }else {
+ // check if a key has the same value like a key of an other properties-file
+ if (configuration.getAuditSameValue() && bundlefile.size() > 1)
+ for (IResource r2 : bundlefile) {
+ IFile f2 = (IFile) r2;
+ auditSameValues(f1, f2, key, bundlegroup);
+ }
+ }
+ }
+ }
+
+ if (configuration.getAuditMissingLanguage()){
+ // checks if the resourcebundle supports all project-languages
+ Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId);
+ Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales();
+
+ auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId);
+ }
+ }
+
+ /*
+ * Audits the file if the key is not specified. If the value is null reports a
+ * problem.
+ */
+ private boolean auditUnspecifiedKey(IFile f1, String key,
+ IMessagesBundleGroup bundlegroup) {
+ if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) {
+ int pos = calculateKeyLine(key, f1);
+ unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key));
+ return true;
+ } else
+ return false;
+ }
+
+ /*
+ * Compares a key in different files and reports a problem, if the values are
+ * same. It doesn't compare the files if one file is the Default-file
+ */
+ private void auditSameValues(IFile f1, IFile f2, String key,
+ IMessagesBundleGroup bundlegroup) {
+ Locale l1 = RBFileUtils.getLocale(f1);
+ Locale l2 = RBFileUtils.getLocale(f2);
+
+ if (!l2.equals(l1) && !(l1.toString().equals("")||l2.toString().equals(""))) {
+ IMessage message = bundlegroup.getMessage(key, l2);
+
+ if (message != null)
+ if (bundlegroup.getMessage(key, l1).getValue()
+ .equals(message.getValue())) {
+ int pos1 = calculateKeyLine(key, f1);
+ int pos2 = calculateKeyLine(key, f2);
+ sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key),
+ new RBLocation(f2, pos2, pos2 + 1, key));
+ }
+ }
+ }
+
+ /*
+ * Checks if the resourcebundle supports all project-languages and report
+ * missing languages.
+ */
+ private void auditMissingLanguage(Set<Locale> rbLocales,
+ Set<Locale> projectLocales, ResourceBundleManager rbmanager,
+ String rbId) {
+ for (Locale pLocale : projectLocales) {
+ if (!rbLocales.contains(pLocale)) {
+ String language = pLocale != null ? pLocale.toString() : ResourceBundleManager.defaultLocaleTag;
+
+ // Add Warning to default-file or a random chosen file
+ IResource representative = rbmanager.getResourceBundleFile(
+ rbId, null);
+ if (representative == null)
+ representative = rbmanager.getRandomFile(rbId);
+ missingLanguages.add(new RBLocation((IFile) representative, 1,
+ 2, language));
+ }
+ }
+ }
+
+ /*
+ * Finds a position where the key is located or missing
+ */
+ private int calculateKeyLine(String key, IFile file) {
+ int linenumber = 1;
+ try {
+// if (!Boolean.valueOf(System.getProperty("dirty"))) {
+// System.setProperty("dirty", "true");
+ file.refreshLocal(IFile.DEPTH_ZERO, null);
+ InputStream is = file.getContents();
+ BufferedReader bf = new BufferedReader(new InputStreamReader(is));
+ String line;
+ while ((line = bf.readLine()) != null) {
+ if ((!line.isEmpty()) && (!line.startsWith("#"))
+ && (line.compareTo(key) > 0))
+ return linenumber;
+ linenumber++;
+ }
+// System.setProperty("dirty", "false");
+// }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return linenumber;
+ }
+
+ @Override
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
+ List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
+
+ switch (marker.getAttribute("cause", -1)) {
+ case IMarkerConstants.CAUSE_MISSING_LANGUAGE:
+ Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO
+ // change
+ // Name
+ resolutions.add(new MissingLanguageResolution(l));
+ break;
+ }
+
+ return resolutions;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
index c96d24a9..b8cbe530 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java
@@ -1,42 +1,49 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.auditor.quickfix;
-
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.LanguageUtils;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IMarkerResolution2;
-
-public class MissingLanguageResolution implements IMarkerResolution2 {
-
- private Locale language;
-
- public MissingLanguageResolution(Locale language){
- this.language = language;
- }
-
- @Override
- public String getLabel() {
- return "Add missing language '"+ language +"'";
- }
-
- @Override
- public void run(IMarker marker) {
- IResource res = marker.getResource();
- String rbId = ResourceBundleManager.getResourceBundleId(res);
- LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId, language);
- }
-
- @Override
- public String getDescription() {
- return "Creates a new localized properties-file with the same basename as the resourcebundle";
- }
-
- @Override
- public Image getImage() {
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.auditor.quickfix;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.LanguageUtils;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class MissingLanguageResolution implements IMarkerResolution2 {
+
+ private Locale language;
+
+ public MissingLanguageResolution(Locale language){
+ this.language = language;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Add missing language '"+ language +"'";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ IResource res = marker.getResource();
+ String rbId = ResourceBundleManager.getResourceBundleId(res);
+ LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId, language);
+ }
+
+ @Override
+ public String getDescription() {
+ return "Creates a new localized properties-file with the same basename as the resourcebundle";
+ }
+
+ @Override
+ public Image getImage() {
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java
index 1c405f23..3ea8a638 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java
@@ -1,61 +1,68 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.model;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-
-public class VirtualContainer {
- protected ResourceBundleManager rbmanager;
- protected IContainer container;
- protected int rbCount;
-
- public VirtualContainer(IContainer container1, boolean countResourceBundles){
- this.container = container1;
- rbmanager = ResourceBundleManager.getManager(container.getProject());
- if (countResourceBundles){
- rbCount=1;
- new Job("count ResourceBundles"){
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- recount();
- return Status.OK_STATUS;
- }
- }.schedule();
- }else rbCount = 0;
- }
-
- protected VirtualContainer(IContainer container){
- this.container = container;
- }
-
- public VirtualContainer(IContainer container, int rbCount) {
- this(container, false);
- this.rbCount = rbCount;
- }
-
- public ResourceBundleManager getResourceBundleManager(){
- if (rbmanager == null)
- rbmanager = ResourceBundleManager.getManager(container.getProject());
- return rbmanager;
- }
-
- public IContainer getContainer() {
- return container;
- }
-
- public void setRbCounter(int rbCount){
- this.rbCount = rbCount;
- }
-
- public int getRbCount() {
- return rbCount;
- }
-
- public void recount(){
- rbCount = RBFileUtils.countRecursiveResourceBundle(container);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.model;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+
+public class VirtualContainer {
+ protected ResourceBundleManager rbmanager;
+ protected IContainer container;
+ protected int rbCount;
+
+ public VirtualContainer(IContainer container1, boolean countResourceBundles){
+ this.container = container1;
+ rbmanager = ResourceBundleManager.getManager(container.getProject());
+ if (countResourceBundles){
+ rbCount=1;
+ new Job("count ResourceBundles"){
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ recount();
+ return Status.OK_STATUS;
+ }
+ }.schedule();
+ }else rbCount = 0;
+ }
+
+ protected VirtualContainer(IContainer container){
+ this.container = container;
+ }
+
+ public VirtualContainer(IContainer container, int rbCount) {
+ this(container, false);
+ this.rbCount = rbCount;
+ }
+
+ public ResourceBundleManager getResourceBundleManager(){
+ if (rbmanager == null)
+ rbmanager = ResourceBundleManager.getManager(container.getProject());
+ return rbmanager;
+ }
+
+ public IContainer getContainer() {
+ return container;
+ }
+
+ public void setRbCounter(int rbCount){
+ this.rbCount = rbCount;
+ }
+
+ public int getRbCount() {
+ return rbCount;
+ }
+
+ public void recount(){
+ rbCount = RBFileUtils.countRecursiveResourceBundle(container);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java
index 3a0f77b3..52f51e51 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java
@@ -1,60 +1,67 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.model;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.core.resources.IContainer;
-
-
-public class VirtualContentManager {
- private Map<IContainer, VirtualContainer> containers = new HashMap<IContainer, VirtualContainer>();
- private Map<String, VirtualResourceBundle> vResourceBundles = new HashMap<String, VirtualResourceBundle>();
-
- static private VirtualContentManager singelton = null;
-
- private VirtualContentManager() {
- }
-
- public static VirtualContentManager getVirtualContentManager(){
- if (singelton == null){
- singelton = new VirtualContentManager();
- }
- return singelton;
- }
-
- public VirtualContainer getContainer(IContainer container) {
- return containers.get(container);
- }
-
-
- public void addVContainer(IContainer container, VirtualContainer vContainer) {
- containers.put(container, vContainer);
- }
-
- public void removeVContainer(IContainer container){
- vResourceBundles.remove(container);
- }
-
- public VirtualResourceBundle getVResourceBundles(String vRbId) {
- return vResourceBundles.get(vRbId);
- }
-
-
- public void addVResourceBundle(String vRbId, VirtualResourceBundle vResourceBundle) {
- vResourceBundles.put(vRbId, vResourceBundle);
- }
-
- public void removeVResourceBundle(String vRbId){
- vResourceBundles.remove(vRbId);
- }
-
-
- public boolean containsVResourceBundles(String vRbId) {
- return vResourceBundles.containsKey(vRbId);
- }
-
- public void reset() {
- vResourceBundles.clear();
- containers.clear();
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.model;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.resources.IContainer;
+
+
+public class VirtualContentManager {
+ private Map<IContainer, VirtualContainer> containers = new HashMap<IContainer, VirtualContainer>();
+ private Map<String, VirtualResourceBundle> vResourceBundles = new HashMap<String, VirtualResourceBundle>();
+
+ static private VirtualContentManager singelton = null;
+
+ private VirtualContentManager() {
+ }
+
+ public static VirtualContentManager getVirtualContentManager(){
+ if (singelton == null){
+ singelton = new VirtualContentManager();
+ }
+ return singelton;
+ }
+
+ public VirtualContainer getContainer(IContainer container) {
+ return containers.get(container);
+ }
+
+
+ public void addVContainer(IContainer container, VirtualContainer vContainer) {
+ containers.put(container, vContainer);
+ }
+
+ public void removeVContainer(IContainer container){
+ vResourceBundles.remove(container);
+ }
+
+ public VirtualResourceBundle getVResourceBundles(String vRbId) {
+ return vResourceBundles.get(vRbId);
+ }
+
+
+ public void addVResourceBundle(String vRbId, VirtualResourceBundle vResourceBundle) {
+ vResourceBundles.put(vRbId, vResourceBundle);
+ }
+
+ public void removeVResourceBundle(String vRbId){
+ vResourceBundles.remove(vRbId);
+ }
+
+
+ public boolean containsVResourceBundles(String vRbId) {
+ return vResourceBundles.containsKey(vRbId);
+ }
+
+ public void reset() {
+ vResourceBundles.clear();
+ containers.clear();
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java
index 972b1445..c04a2e3c 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java
@@ -1,63 +1,70 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.model;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipse.core.resources.IProject;
-
-/**
- * Representation of a project
- *
- */
-public class VirtualProject extends VirtualContainer{
- private boolean isFragment;
- private IProject hostProject;
- private List<IProject> fragmentProjects = new LinkedList<IProject>();
-
- //Slow
- public VirtualProject(IProject project, boolean countResourceBundles) {
- super(project, countResourceBundles);
- isFragment = FragmentProjectUtils.isFragment(project);
- if (isFragment) {
- hostProject = FragmentProjectUtils.getFragmentHost(project);
- } else
- fragmentProjects = FragmentProjectUtils.getFragments(project);
- }
-
- /*
- * No fragment search
- */
- public VirtualProject(final IProject project, boolean isFragment, boolean countResourceBundles){
- super(project, countResourceBundles);
- this.isFragment = isFragment;
-// Display.getDefault().asyncExec(new Runnable() {
-// @Override
-// public void run() {
-// hostProject = FragmentProjectUtils.getFragmentHost(project);
-// }
-// });
- }
-
- public Set<Locale> getProvidedLocales(){
- return rbmanager.getProjectProvidedLocales();
- }
-
- public boolean isFragment(){
- return isFragment;
- }
-
- public IProject getHostProject(){
- return hostProject;
- }
-
- public boolean hasFragments() {
- return !fragmentProjects.isEmpty();
- }
-
- public List<IProject> getFragmets(){
- return fragmentProjects;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.model;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.core.resources.IProject;
+
+/**
+ * Representation of a project
+ *
+ */
+public class VirtualProject extends VirtualContainer{
+ private boolean isFragment;
+ private IProject hostProject;
+ private List<IProject> fragmentProjects = new LinkedList<IProject>();
+
+ //Slow
+ public VirtualProject(IProject project, boolean countResourceBundles) {
+ super(project, countResourceBundles);
+ isFragment = FragmentProjectUtils.isFragment(project);
+ if (isFragment) {
+ hostProject = FragmentProjectUtils.getFragmentHost(project);
+ } else
+ fragmentProjects = FragmentProjectUtils.getFragments(project);
+ }
+
+ /*
+ * No fragment search
+ */
+ public VirtualProject(final IProject project, boolean isFragment, boolean countResourceBundles){
+ super(project, countResourceBundles);
+ this.isFragment = isFragment;
+// Display.getDefault().asyncExec(new Runnable() {
+// @Override
+// public void run() {
+// hostProject = FragmentProjectUtils.getFragmentHost(project);
+// }
+// });
+ }
+
+ public Set<Locale> getProvidedLocales(){
+ return rbmanager.getProjectProvidedLocales();
+ }
+
+ public boolean isFragment(){
+ return isFragment;
+ }
+
+ public IProject getHostProject(){
+ return hostProject;
+ }
+
+ public boolean hasFragments() {
+ return !fragmentProjects.isEmpty();
+ }
+
+ public List<IProject> getFragmets(){
+ return fragmentProjects;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
index cf435d7e..76c1a389 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java
@@ -1,52 +1,59 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.model;
-
-import java.util.Collection;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-
-public class VirtualResourceBundle{
- private String resourcebundlename;
- private String resourcebundleId;
- private ResourceBundleManager rbmanager;
-
-
- public VirtualResourceBundle(String rbname, String rbId, ResourceBundleManager rbmanager) {
- this.rbmanager=rbmanager;
- resourcebundlename=rbname;
- resourcebundleId=rbId;
- }
-
- public ResourceBundleManager getResourceBundleManager() {
- return rbmanager;
- }
-
- public String getResourceBundleId(){
- return resourcebundleId;
- }
-
-
- @Override
- public String toString(){
- return resourcebundleId;
- }
-
- public IPath getFullPath() {
- return rbmanager.getRandomFile(resourcebundleId).getFullPath();
- }
-
-
- public String getName() {
- return resourcebundlename;
- }
-
- public Collection<IResource> getFiles() {
- return rbmanager.getResourceBundles(resourcebundleId);
- }
-
- public IFile getRandomFile(){
- return rbmanager.getRandomFile(resourcebundleId);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.model;
+
+import java.util.Collection;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IPath;
+
+public class VirtualResourceBundle{
+ private String resourcebundlename;
+ private String resourcebundleId;
+ private ResourceBundleManager rbmanager;
+
+
+ public VirtualResourceBundle(String rbname, String rbId, ResourceBundleManager rbmanager) {
+ this.rbmanager=rbmanager;
+ resourcebundlename=rbname;
+ resourcebundleId=rbId;
+ }
+
+ public ResourceBundleManager getResourceBundleManager() {
+ return rbmanager;
+ }
+
+ public String getResourceBundleId(){
+ return resourcebundleId;
+ }
+
+
+ @Override
+ public String toString(){
+ return resourcebundleId;
+ }
+
+ public IPath getFullPath() {
+ return rbmanager.getRandomFile(resourcebundleId).getFullPath();
+ }
+
+
+ public String getName() {
+ return resourcebundlename;
+ }
+
+ public Collection<IResource> getFiles() {
+ return rbmanager.getResourceBundles(resourcebundleId);
+ }
+
+ public IFile getRandomFile(){
+ return rbmanager.getRandomFile(resourcebundleId);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java
index 468c9fb7..1ed2e792 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java
@@ -1,107 +1,114 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.ui.hover;
-
-import java.util.List;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseTrackAdapter;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.Widget;
-
-
-public class Hover {
- private Shell hoverShell;
- private Point hoverPosition;
- private List<HoverInformant> informant;
-
- public Hover(Shell parent, List<HoverInformant> informant){
- this.informant = informant;
- hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
- Display display = hoverShell.getDisplay();
-
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.verticalSpacing = 2;
- hoverShell.setLayout(gridLayout);
-
- hoverShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- hoverShell.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- }
-
-
- private void setHoverLocation(Shell shell, Point position) {
- Rectangle displayBounds = shell.getDisplay().getBounds();
- Rectangle shellBounds = shell.getBounds();
- shellBounds.x = Math.max(
- Math.min(position.x+1, displayBounds.width - shellBounds.width), 0);
- shellBounds.y = Math.max(
- Math.min(position.y + 16, displayBounds.height - (shellBounds.height+1)), 0);
- shell.setBounds(shellBounds);
- }
-
-
- public void activateHoverHelp(final Control control) {
-
- control.addMouseListener(new MouseAdapter() {
- public void mouseDown(MouseEvent e) {
- if (hoverShell != null && hoverShell.isVisible()){
- hoverShell.setVisible(false);
- }
- }
- });
-
- control.addMouseTrackListener(new MouseTrackAdapter() {
- public void mouseExit(MouseEvent e) {
- if (hoverShell != null && hoverShell.isVisible())
- hoverShell.setVisible(false);
- }
-
- public void mouseHover(MouseEvent event) {
- Point pt = new Point(event.x, event.y);
- Widget widget = event.widget;
- if (widget instanceof ToolBar) {
- ToolBar w = (ToolBar) widget;
- widget = w.getItem(pt);
- }
- if (widget instanceof Table) {
- Table w = (Table) widget;
- widget = w.getItem(pt);
- }
- if (widget instanceof Tree) {
- Tree w = (Tree) widget;
- widget = w.getItem(pt);
- }
- if (widget == null) {
- hoverShell.setVisible(false);
- return;
- }
- hoverPosition = control.toDisplay(pt);
-
- boolean show = false;
- Object data = widget.getData();
-
- for (HoverInformant hi :informant){
- hi.getInfoComposite(data, hoverShell);
- if (hi.show()) show= true;
- }
-
- if (show){
- hoverShell.pack();
- hoverShell.layout();
- setHoverLocation(hoverShell, hoverPosition);
- hoverShell.setVisible(true);
- }
- else hoverShell.setVisible(false);
-
- }
- });
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.ui.hover;
+
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MouseAdapter;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseTrackAdapter;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.Widget;
+
+
+public class Hover {
+ private Shell hoverShell;
+ private Point hoverPosition;
+ private List<HoverInformant> informant;
+
+ public Hover(Shell parent, List<HoverInformant> informant){
+ this.informant = informant;
+ hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL);
+ Display display = hoverShell.getDisplay();
+
+ GridLayout gridLayout = new GridLayout(1, false);
+ gridLayout.verticalSpacing = 2;
+ hoverShell.setLayout(gridLayout);
+
+ hoverShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ hoverShell.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ }
+
+
+ private void setHoverLocation(Shell shell, Point position) {
+ Rectangle displayBounds = shell.getDisplay().getBounds();
+ Rectangle shellBounds = shell.getBounds();
+ shellBounds.x = Math.max(
+ Math.min(position.x+1, displayBounds.width - shellBounds.width), 0);
+ shellBounds.y = Math.max(
+ Math.min(position.y + 16, displayBounds.height - (shellBounds.height+1)), 0);
+ shell.setBounds(shellBounds);
+ }
+
+
+ public void activateHoverHelp(final Control control) {
+
+ control.addMouseListener(new MouseAdapter() {
+ public void mouseDown(MouseEvent e) {
+ if (hoverShell != null && hoverShell.isVisible()){
+ hoverShell.setVisible(false);
+ }
+ }
+ });
+
+ control.addMouseTrackListener(new MouseTrackAdapter() {
+ public void mouseExit(MouseEvent e) {
+ if (hoverShell != null && hoverShell.isVisible())
+ hoverShell.setVisible(false);
+ }
+
+ public void mouseHover(MouseEvent event) {
+ Point pt = new Point(event.x, event.y);
+ Widget widget = event.widget;
+ if (widget instanceof ToolBar) {
+ ToolBar w = (ToolBar) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget instanceof Table) {
+ Table w = (Table) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget instanceof Tree) {
+ Tree w = (Tree) widget;
+ widget = w.getItem(pt);
+ }
+ if (widget == null) {
+ hoverShell.setVisible(false);
+ return;
+ }
+ hoverPosition = control.toDisplay(pt);
+
+ boolean show = false;
+ Object data = widget.getData();
+
+ for (HoverInformant hi :informant){
+ hi.getInfoComposite(data, hoverShell);
+ if (hi.show()) show= true;
+ }
+
+ if (show){
+ hoverShell.pack();
+ hoverShell.layout();
+ setHoverLocation(hoverShell, hoverPosition);
+ hoverShell.setVisible(true);
+ }
+ else hoverShell.setVisible(false);
+
+ }
+ });
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java
index c6030732..eed0abf7 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java
@@ -1,10 +1,17 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.ui.hover;
-
-import org.eclipse.swt.widgets.Composite;
-
-public interface HoverInformant {
-
- public Composite getInfoComposite(Object data, Composite parent);
-
- public boolean show();
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.ui.hover;
+
+import org.eclipse.swt.widgets.Composite;
+
+public interface HoverInformant {
+
+ public Composite getInfoComposite(Object data, Composite parent);
+
+ public boolean show();
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
index 496627c2..17c0eba3 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java
@@ -1,47 +1,54 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.ui.view.toolbarItems;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IViewActionDelegate;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.navigator.CommonNavigator;
-import org.eclipse.ui.navigator.CommonViewer;
-import org.eclipse.ui.progress.UIJob;
-
-public class ExpandAllActionDelegate implements IViewActionDelegate {
- private CommonViewer viewer;
-
- @Override
- public void run(IAction action) {
- Object data = viewer.getControl().getData();
-
- for(final IProject p : ((IWorkspaceRoot)data).getProjects()){
- UIJob job = new UIJob("expand Projects") {
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- viewer.expandToLevel(p, AbstractTreeViewer.ALL_LEVELS);
- return Status.OK_STATUS;
- }
- };
-
- job.schedule();
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // TODO Auto-generated method stub
- }
-
- @Override
- public void init(IViewPart view) {
- viewer = ((CommonNavigator) view).getCommonViewer();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.ui.view.toolbarItems;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.AbstractTreeViewer;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.navigator.CommonNavigator;
+import org.eclipse.ui.navigator.CommonViewer;
+import org.eclipse.ui.progress.UIJob;
+
+public class ExpandAllActionDelegate implements IViewActionDelegate {
+ private CommonViewer viewer;
+
+ @Override
+ public void run(IAction action) {
+ Object data = viewer.getControl().getData();
+
+ for(final IProject p : ((IWorkspaceRoot)data).getProjects()){
+ UIJob job = new UIJob("expand Projects") {
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ viewer.expandToLevel(p, AbstractTreeViewer.ALL_LEVELS);
+ return Status.OK_STATUS;
+ }
+ };
+
+ job.schedule();
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public void init(IViewPart view) {
+ viewer = ((CommonNavigator) view).getCommonViewer();
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
index 661013e2..53352c24 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java
@@ -1,58 +1,65 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.ui.view.toolbarItems;
-
-import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IViewActionDelegate;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.navigator.CommonNavigator;
-import org.eclipse.ui.navigator.ICommonFilterDescriptor;
-import org.eclipse.ui.navigator.INavigatorContentService;
-import org.eclipse.ui.navigator.INavigatorFilterService;
-
-
-
-public class ToggleFilterActionDelegate implements IViewActionDelegate{
- private INavigatorFilterService filterService;
- private boolean active;
- private static final String[] FILTER = {RBManagerActivator.PLUGIN_ID+".filter.ProblematicResourceBundleFiles"};
-
- @Override
- public void run(IAction action) {
- if (active==true){
- filterService.activateFilterIdsAndUpdateViewer(new String[0]);
- active = false;
- }
- else {
- filterService.activateFilterIdsAndUpdateViewer(FILTER);
- active = true;
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // Active when content change
- }
-
- @Override
- public void init(IViewPart view) {
- INavigatorContentService contentService = ((CommonNavigator) view).getCommonViewer().getNavigatorContentService();
-
- filterService = contentService.getFilterService();
- filterService.activateFilterIdsAndUpdateViewer(new String[0]);
- active=false;
- }
-
-
- @SuppressWarnings("unused")
- private String[] getActiveFilterIds() {
- ICommonFilterDescriptor[] fds = filterService.getVisibleFilterDescriptors();
- String activeFilterIds[]=new String[fds.length];
-
- for(int i=0;i<fds.length;i++)
- activeFilterIds[i]=fds[i].getId();
-
- return activeFilterIds;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.ui.view.toolbarItems;
+
+import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IViewActionDelegate;
+import org.eclipse.ui.IViewPart;
+import org.eclipse.ui.navigator.CommonNavigator;
+import org.eclipse.ui.navigator.ICommonFilterDescriptor;
+import org.eclipse.ui.navigator.INavigatorContentService;
+import org.eclipse.ui.navigator.INavigatorFilterService;
+
+
+
+public class ToggleFilterActionDelegate implements IViewActionDelegate{
+ private INavigatorFilterService filterService;
+ private boolean active;
+ private static final String[] FILTER = {RBManagerActivator.PLUGIN_ID+".filter.ProblematicResourceBundleFiles"};
+
+ @Override
+ public void run(IAction action) {
+ if (active==true){
+ filterService.activateFilterIdsAndUpdateViewer(new String[0]);
+ active = false;
+ }
+ else {
+ filterService.activateFilterIdsAndUpdateViewer(FILTER);
+ active = true;
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+ // Active when content change
+ }
+
+ @Override
+ public void init(IViewPart view) {
+ INavigatorContentService contentService = ((CommonNavigator) view).getCommonViewer().getNavigatorContentService();
+
+ filterService = contentService.getFilterService();
+ filterService.activateFilterIdsAndUpdateViewer(new String[0]);
+ active=false;
+ }
+
+
+ @SuppressWarnings("unused")
+ private String[] getActiveFilterIds() {
+ ICommonFilterDescriptor[] fds = filterService.getVisibleFilterDescriptors();
+ String activeFilterIds[]=new String[fds.length];
+
+ for(int i=0;i<fds.length;i++)
+ activeFilterIds[i]=fds[i].getId();
+
+ return activeFilterIds;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
index 7b1cce23..a88d6f64 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java
@@ -1,37 +1,44 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.ide.ResourceUtil;
-import org.eclipse.ui.navigator.ILinkHelper;
-
-/*
- * Allows 'link with editor'
- */
-public class LinkHelper implements ILinkHelper {
-
- public static IStructuredSelection viewer;
-
- @Override
- public IStructuredSelection findSelection(IEditorInput anInput) {
- IFile file = ResourceUtil.getFile(anInput);
- if (file != null) {
- return new StructuredSelection(file);
- }
- return StructuredSelection.EMPTY;
- }
-
- @Override
- public void activateEditor(IWorkbenchPage aPage,IStructuredSelection aSelection) {
- if (aSelection.getFirstElement() instanceof IFile)
- try {
- IDE.openEditor(aPage, (IFile) aSelection.getFirstElement());
- } catch (PartInitException e) {/**/}
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.ide.IDE;
+import org.eclipse.ui.ide.ResourceUtil;
+import org.eclipse.ui.navigator.ILinkHelper;
+
+/*
+ * Allows 'link with editor'
+ */
+public class LinkHelper implements ILinkHelper {
+
+ public static IStructuredSelection viewer;
+
+ @Override
+ public IStructuredSelection findSelection(IEditorInput anInput) {
+ IFile file = ResourceUtil.getFile(anInput);
+ if (file != null) {
+ return new StructuredSelection(file);
+ }
+ return StructuredSelection.EMPTY;
+ }
+
+ @Override
+ public void activateEditor(IWorkbenchPage aPage,IStructuredSelection aSelection) {
+ if (aSelection.getFirstElement() instanceof IFile)
+ try {
+ IDE.openEditor(aPage, (IFile) aSelection.getFirstElement());
+ } catch (PartInitException e) {/**/}
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
index 8a675944..21b7641c 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java
@@ -1,386 +1,393 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
-import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContainer;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContentManager;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualProject;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.ui.progress.UIJob;
-
-
-
-/**
- *
- *
- */
-public class ResourceBundleContentProvider implements ITreeContentProvider, IResourceChangeListener, IPropertyChangeListener, IResourceBundleChangedListener{
- private static final boolean FRAGMENT_PROJECTS_IN_CONTENT = false;
- private static final boolean SHOW_ONLY_PROJECTS_WITH_RBS = true;
- private StructuredViewer viewer;
- private VirtualContentManager vcManager;
- private UIJob refresh;
- private IWorkspaceRoot root;
-
- private List<IProject> listenedProjects;
- /**
- *
- */
- public ResourceBundleContentProvider() {
- ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
- TapiJIPreferences.addPropertyChangeListener(this);
- vcManager = VirtualContentManager.getVirtualContentManager();
- listenedProjects = new LinkedList<IProject>();
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- @Override
- public Object[] getChildren(final Object parentElement) {
- Object[] children = null;
-
- if (parentElement instanceof IWorkspaceRoot) {
- root = (IWorkspaceRoot) parentElement;
- try {
- IResource[] members = ((IWorkspaceRoot)parentElement).members();
-
- List<Object> displayedProjects = new ArrayList<Object>();
- for (IResource r : members)
- if (r instanceof IProject){
- IProject p = (IProject) r;
- if (FragmentProjectUtils.isFragment(r.getProject())) {
- if (vcManager.getContainer(p)==null)
- vcManager.addVContainer(p, new VirtualProject(p, true,false));
- if (FRAGMENT_PROJECTS_IN_CONTENT) displayedProjects.add(r);
- } else {
- if (SHOW_ONLY_PROJECTS_WITH_RBS){
- VirtualProject vP;
- if ((vP=(VirtualProject) vcManager.getContainer(p))==null){
- vP = new VirtualProject(p, false, true);
- vcManager.addVContainer(p, vP);
- registerResourceBundleListner(p);
- }
-
- if (vP.getRbCount()>0) displayedProjects.add(p);
- }else {
- displayedProjects.add(p);
- }
- }
- }
-
- children = displayedProjects.toArray();
- return children;
- } catch (CoreException e) { }
- }
-
-// if (parentElement instanceof IProject) {
-// final IProject iproject = (IProject) parentElement;
-// VirtualContainer vproject = vcManager.getContainer(iproject);
-// if (vproject == null){
-// vproject = new VirtualProject(iproject, true);
-// vcManager.addVContainer(iproject, vproject);
-// }
-// }
-
- if (parentElement instanceof IContainer) {
- IContainer container = (IContainer) parentElement;
- if (!((VirtualProject) vcManager.getContainer(((IResource) parentElement).getProject()))
- .isFragment())
- try {
- children = addChildren(container);
- } catch (CoreException e) {/**/}
- }
-
- if (parentElement instanceof VirtualResourceBundle) {
- VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement;
- ResourceBundleManager rbmanager = virtualrb.getResourceBundleManager();
- children = rbmanager.getResourceBundles(virtualrb.getResourceBundleId()).toArray();
- }
-
- return children != null ? children : new Object[0];
- }
-
- /*
- * Returns all ResourceBundles and sub-containers (with ResourceBundles in their subtree) of a Container
- */
- private Object[] addChildren(IContainer container) throws CoreException{
- Map<String, Object> children = new HashMap<String,Object>();
-
- VirtualProject p = (VirtualProject) vcManager.getContainer(container.getProject());
- List<IResource> members = new ArrayList<IResource>(Arrays.asList(container.members()));
-
- //finds files in the corresponding fragment-projects folder
- if (p.hasFragments()){
- List<IContainer> folders = ResourceUtils.getCorrespondingFolders(container, p.getFragmets());
- for (IContainer f : folders)
- for (IResource r : f.members())
- if (r instanceof IFile)
- members.add(r);
- }
-
- for(IResource r : members){
-
- if (r instanceof IFile) {
- String resourcebundleId = RBFileUtils.getCorrespondingResourceBundleId((IFile)r);
- if( resourcebundleId != null && (!children.containsKey(resourcebundleId))) {
- VirtualResourceBundle vrb;
-
- String vRBId;
-
- if (!p.isFragment()) vRBId = r.getProject()+"."+resourcebundleId;
- else vRBId = p.getHostProject() + "." + resourcebundleId;
-
- VirtualResourceBundle vResourceBundle = vcManager.getVResourceBundles(vRBId);
- if (vResourceBundle == null){
- String resourcebundleName = ResourceBundleManager.getResourceBundleName(r);
- vrb = new VirtualResourceBundle(resourcebundleName, resourcebundleId, ResourceBundleManager.getManager(r.getProject()));
- vcManager.addVResourceBundle(vRBId, vrb);
-
- } else vrb = vcManager.getVResourceBundles(vRBId);
-
- children.put(resourcebundleId, vrb);
- }
- }
- if (r instanceof IContainer)
- if (!r.isDerived()){ //Don't show the 'bin' folder
- VirtualContainer vContainer = vcManager.getContainer((IContainer) r);
-
- if (vContainer == null){
- int count = RBFileUtils.countRecursiveResourceBundle((IContainer)r);
- vContainer = new VirtualContainer(container, count);
- vcManager.addVContainer((IContainer) r, vContainer);
- }
-
- if (vContainer.getRbCount() != 0) //Don't show folder without resourcebundles
- children.put(""+children.size(), r);
- }
- }
- return children.values().toArray();
- }
-
- @Override
- public Object getParent(Object element) {
- if (element instanceof IContainer) {
- return ((IContainer) element).getParent();
- }
- if (element instanceof IFile) {
- String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile) element);
- return vcManager.getVResourceBundles(rbId);
- }
- if (element instanceof VirtualResourceBundle) {
- Iterator<IResource> i = new HashSet<IResource>(((VirtualResourceBundle) element).getFiles()).iterator();
- if (i.hasNext()) return i.next().getParent();
- }
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof IWorkspaceRoot) {
- try {
- if (((IWorkspaceRoot) element).members().length > 0) return true;
- } catch (CoreException e) {}
- }
- if (element instanceof IProject){
- VirtualProject vProject = (VirtualProject) vcManager.getContainer((IProject) element);
- if (vProject!= null && vProject.isFragment()) return false;
- }
- if (element instanceof IContainer) {
- try {
- VirtualContainer vContainer = vcManager.getContainer((IContainer) element);
- if (vContainer != null)
- return vContainer.getRbCount() > 0 ? true : false;
- else if (((IContainer) element).members().length > 0) return true;
- } catch (CoreException e) {}
- }
- if (element instanceof VirtualResourceBundle){
- return true;
- }
- return false;
- }
-
- @Override
- public void dispose() {
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- TapiJIPreferences.removePropertyChangeListener(this);
- vcManager.reset();
- unregisterAllResourceBundleListner();
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- this.viewer = (StructuredViewer) viewer;
- }
-
- @Override
- //TODO remove ResourceChangelistner and add ResourceBundleChangelistner
- public void resourceChanged(final IResourceChangeEvent event) {
-
- final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- final IResource res = delta.getResource();
-
- if (!RBFileUtils.isResourceBundleFile(res))
- return true;
-
- switch (delta.getKind()) {
- case IResourceDelta.REMOVED:
- recountParenthierarchy(res.getParent());
- break;
- //TODO remove unused VirtualResourceBundles and VirtualContainer from vcManager
- case IResourceDelta.ADDED:
- checkListner(res);
- break;
- case IResourceDelta.CHANGED:
- if (delta.getFlags() != IResourceDelta.MARKERS)
- return true;
- break;
- }
-
- refresh(res);
-
- return true;
- }
- };
-
- try {
- event.getDelta().accept(visitor);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void resourceBundleChanged(ResourceBundleChangedEvent event) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(event.getProject());
-
- switch (event.getType()){
- case ResourceBundleChangedEvent.ADDED:
- case ResourceBundleChangedEvent.DELETED:
- IResource res = rbmanager.getRandomFile(event.getBundle());
- IContainer hostContainer;
-
- if (res == null)
- try{
- hostContainer = event.getProject().getFile(event.getBundle()).getParent();
- }catch (Exception e) {
- refresh(null);
- return;
- }
- else {
- VirtualProject vProject = (VirtualProject) vcManager.getContainer((IContainer) res.getProject());
- if (vProject != null && vProject.isFragment()){
- IProject hostProject = vProject.getHostProject();
- hostContainer = ResourceUtils.getCorrespondingFolders(res.getParent(), hostProject);
- } else
- hostContainer = res.getParent();
- }
-
- recountParenthierarchy(hostContainer);
- refresh(null);
- break;
- }
-
- }
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if(event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)){
- vcManager.reset();
-
- refresh(root);
- }
- }
-
- //TODO problems with remove a hole ResourceBundle
- private void recountParenthierarchy(IContainer parent) {
- if (parent.isDerived())
- return; //Don't recount the 'bin' folder
-
- VirtualContainer vContainer = vcManager.getContainer((IContainer) parent);
- if (vContainer != null){
- vContainer.recount();
- }
-
- if ((parent instanceof IFolder))
- recountParenthierarchy(parent.getParent());
- }
-
- private void refresh(final IResource res) {
- if (refresh == null || refresh.getResult() != null)
- refresh = new UIJob("refresh viewer") {
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (viewer != null
- && !viewer.getControl().isDisposed())
- if (res != null)
- viewer.refresh(res.getProject(),true); // refresh(res);
- else viewer.refresh();
- return Status.OK_STATUS;
- }
- };
- refresh.schedule();
- }
-
- private void registerResourceBundleListner(IProject p) {
- listenedProjects.add(p);
-
- ResourceBundleManager rbmanager =ResourceBundleManager.getManager(p);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()){
- rbmanager.registerResourceBundleChangeListener(rbId, this);
- }
- }
-
- private void unregisterAllResourceBundleListner() {
- for( IProject p : listenedProjects){
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
- for (String rbId : rbmanager.getResourceBundleIdentifiers()){
- rbmanager.unregisterResourceBundleChangeListener(rbId, this);
- }
- }
- }
-
- private void checkListner(IResource res) {
- ResourceBundleManager rbmanager = ResourceBundleManager.getManager(res.getProject());
- String rbId = ResourceBundleManager.getResourceBundleId(res);
- rbmanager.registerResourceBundleChangeListener(rbId, this);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.babel.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.model.preferences.TapiJIPreferences;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContainer;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContentManager;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualProject;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IResourceDeltaVisitor;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.ui.progress.UIJob;
+
+
+
+/**
+ *
+ *
+ */
+public class ResourceBundleContentProvider implements ITreeContentProvider, IResourceChangeListener, IPropertyChangeListener, IResourceBundleChangedListener{
+ private static final boolean FRAGMENT_PROJECTS_IN_CONTENT = false;
+ private static final boolean SHOW_ONLY_PROJECTS_WITH_RBS = true;
+ private StructuredViewer viewer;
+ private VirtualContentManager vcManager;
+ private UIJob refresh;
+ private IWorkspaceRoot root;
+
+ private List<IProject> listenedProjects;
+ /**
+ *
+ */
+ public ResourceBundleContentProvider() {
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
+ TapiJIPreferences.addPropertyChangeListener(this);
+ vcManager = VirtualContentManager.getVirtualContentManager();
+ listenedProjects = new LinkedList<IProject>();
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ return getChildren(inputElement);
+ }
+
+ @Override
+ public Object[] getChildren(final Object parentElement) {
+ Object[] children = null;
+
+ if (parentElement instanceof IWorkspaceRoot) {
+ root = (IWorkspaceRoot) parentElement;
+ try {
+ IResource[] members = ((IWorkspaceRoot)parentElement).members();
+
+ List<Object> displayedProjects = new ArrayList<Object>();
+ for (IResource r : members)
+ if (r instanceof IProject){
+ IProject p = (IProject) r;
+ if (FragmentProjectUtils.isFragment(r.getProject())) {
+ if (vcManager.getContainer(p)==null)
+ vcManager.addVContainer(p, new VirtualProject(p, true,false));
+ if (FRAGMENT_PROJECTS_IN_CONTENT) displayedProjects.add(r);
+ } else {
+ if (SHOW_ONLY_PROJECTS_WITH_RBS){
+ VirtualProject vP;
+ if ((vP=(VirtualProject) vcManager.getContainer(p))==null){
+ vP = new VirtualProject(p, false, true);
+ vcManager.addVContainer(p, vP);
+ registerResourceBundleListner(p);
+ }
+
+ if (vP.getRbCount()>0) displayedProjects.add(p);
+ }else {
+ displayedProjects.add(p);
+ }
+ }
+ }
+
+ children = displayedProjects.toArray();
+ return children;
+ } catch (CoreException e) { }
+ }
+
+// if (parentElement instanceof IProject) {
+// final IProject iproject = (IProject) parentElement;
+// VirtualContainer vproject = vcManager.getContainer(iproject);
+// if (vproject == null){
+// vproject = new VirtualProject(iproject, true);
+// vcManager.addVContainer(iproject, vproject);
+// }
+// }
+
+ if (parentElement instanceof IContainer) {
+ IContainer container = (IContainer) parentElement;
+ if (!((VirtualProject) vcManager.getContainer(((IResource) parentElement).getProject()))
+ .isFragment())
+ try {
+ children = addChildren(container);
+ } catch (CoreException e) {/**/}
+ }
+
+ if (parentElement instanceof VirtualResourceBundle) {
+ VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement;
+ ResourceBundleManager rbmanager = virtualrb.getResourceBundleManager();
+ children = rbmanager.getResourceBundles(virtualrb.getResourceBundleId()).toArray();
+ }
+
+ return children != null ? children : new Object[0];
+ }
+
+ /*
+ * Returns all ResourceBundles and sub-containers (with ResourceBundles in their subtree) of a Container
+ */
+ private Object[] addChildren(IContainer container) throws CoreException{
+ Map<String, Object> children = new HashMap<String,Object>();
+
+ VirtualProject p = (VirtualProject) vcManager.getContainer(container.getProject());
+ List<IResource> members = new ArrayList<IResource>(Arrays.asList(container.members()));
+
+ //finds files in the corresponding fragment-projects folder
+ if (p.hasFragments()){
+ List<IContainer> folders = ResourceUtils.getCorrespondingFolders(container, p.getFragmets());
+ for (IContainer f : folders)
+ for (IResource r : f.members())
+ if (r instanceof IFile)
+ members.add(r);
+ }
+
+ for(IResource r : members){
+
+ if (r instanceof IFile) {
+ String resourcebundleId = RBFileUtils.getCorrespondingResourceBundleId((IFile)r);
+ if( resourcebundleId != null && (!children.containsKey(resourcebundleId))) {
+ VirtualResourceBundle vrb;
+
+ String vRBId;
+
+ if (!p.isFragment()) vRBId = r.getProject()+"."+resourcebundleId;
+ else vRBId = p.getHostProject() + "." + resourcebundleId;
+
+ VirtualResourceBundle vResourceBundle = vcManager.getVResourceBundles(vRBId);
+ if (vResourceBundle == null){
+ String resourcebundleName = ResourceBundleManager.getResourceBundleName(r);
+ vrb = new VirtualResourceBundle(resourcebundleName, resourcebundleId, ResourceBundleManager.getManager(r.getProject()));
+ vcManager.addVResourceBundle(vRBId, vrb);
+
+ } else vrb = vcManager.getVResourceBundles(vRBId);
+
+ children.put(resourcebundleId, vrb);
+ }
+ }
+ if (r instanceof IContainer)
+ if (!r.isDerived()){ //Don't show the 'bin' folder
+ VirtualContainer vContainer = vcManager.getContainer((IContainer) r);
+
+ if (vContainer == null){
+ int count = RBFileUtils.countRecursiveResourceBundle((IContainer)r);
+ vContainer = new VirtualContainer(container, count);
+ vcManager.addVContainer((IContainer) r, vContainer);
+ }
+
+ if (vContainer.getRbCount() != 0) //Don't show folder without resourcebundles
+ children.put(""+children.size(), r);
+ }
+ }
+ return children.values().toArray();
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ if (element instanceof IContainer) {
+ return ((IContainer) element).getParent();
+ }
+ if (element instanceof IFile) {
+ String rbId = RBFileUtils.getCorrespondingResourceBundleId((IFile) element);
+ return vcManager.getVResourceBundles(rbId);
+ }
+ if (element instanceof VirtualResourceBundle) {
+ Iterator<IResource> i = new HashSet<IResource>(((VirtualResourceBundle) element).getFiles()).iterator();
+ if (i.hasNext()) return i.next().getParent();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ if (element instanceof IWorkspaceRoot) {
+ try {
+ if (((IWorkspaceRoot) element).members().length > 0) return true;
+ } catch (CoreException e) {}
+ }
+ if (element instanceof IProject){
+ VirtualProject vProject = (VirtualProject) vcManager.getContainer((IProject) element);
+ if (vProject!= null && vProject.isFragment()) return false;
+ }
+ if (element instanceof IContainer) {
+ try {
+ VirtualContainer vContainer = vcManager.getContainer((IContainer) element);
+ if (vContainer != null)
+ return vContainer.getRbCount() > 0 ? true : false;
+ else if (((IContainer) element).members().length > 0) return true;
+ } catch (CoreException e) {}
+ }
+ if (element instanceof VirtualResourceBundle){
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void dispose() {
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
+ TapiJIPreferences.removePropertyChangeListener(this);
+ vcManager.reset();
+ unregisterAllResourceBundleListner();
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ this.viewer = (StructuredViewer) viewer;
+ }
+
+ @Override
+ //TODO remove ResourceChangelistner and add ResourceBundleChangelistner
+ public void resourceChanged(final IResourceChangeEvent event) {
+
+ final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
+ @Override
+ public boolean visit(IResourceDelta delta) throws CoreException {
+ final IResource res = delta.getResource();
+
+ if (!RBFileUtils.isResourceBundleFile(res))
+ return true;
+
+ switch (delta.getKind()) {
+ case IResourceDelta.REMOVED:
+ recountParenthierarchy(res.getParent());
+ break;
+ //TODO remove unused VirtualResourceBundles and VirtualContainer from vcManager
+ case IResourceDelta.ADDED:
+ checkListner(res);
+ break;
+ case IResourceDelta.CHANGED:
+ if (delta.getFlags() != IResourceDelta.MARKERS)
+ return true;
+ break;
+ }
+
+ refresh(res);
+
+ return true;
+ }
+ };
+
+ try {
+ event.getDelta().accept(visitor);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void resourceBundleChanged(ResourceBundleChangedEvent event) {
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(event.getProject());
+
+ switch (event.getType()){
+ case ResourceBundleChangedEvent.ADDED:
+ case ResourceBundleChangedEvent.DELETED:
+ IResource res = rbmanager.getRandomFile(event.getBundle());
+ IContainer hostContainer;
+
+ if (res == null)
+ try{
+ hostContainer = event.getProject().getFile(event.getBundle()).getParent();
+ }catch (Exception e) {
+ refresh(null);
+ return;
+ }
+ else {
+ VirtualProject vProject = (VirtualProject) vcManager.getContainer((IContainer) res.getProject());
+ if (vProject != null && vProject.isFragment()){
+ IProject hostProject = vProject.getHostProject();
+ hostContainer = ResourceUtils.getCorrespondingFolders(res.getParent(), hostProject);
+ } else
+ hostContainer = res.getParent();
+ }
+
+ recountParenthierarchy(hostContainer);
+ refresh(null);
+ break;
+ }
+
+ }
+
+ @Override
+ public void propertyChange(PropertyChangeEvent event) {
+ if(event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)){
+ vcManager.reset();
+
+ refresh(root);
+ }
+ }
+
+ //TODO problems with remove a hole ResourceBundle
+ private void recountParenthierarchy(IContainer parent) {
+ if (parent.isDerived())
+ return; //Don't recount the 'bin' folder
+
+ VirtualContainer vContainer = vcManager.getContainer((IContainer) parent);
+ if (vContainer != null){
+ vContainer.recount();
+ }
+
+ if ((parent instanceof IFolder))
+ recountParenthierarchy(parent.getParent());
+ }
+
+ private void refresh(final IResource res) {
+ if (refresh == null || refresh.getResult() != null)
+ refresh = new UIJob("refresh viewer") {
+ @Override
+ public IStatus runInUIThread(IProgressMonitor monitor) {
+ if (viewer != null
+ && !viewer.getControl().isDisposed())
+ if (res != null)
+ viewer.refresh(res.getProject(),true); // refresh(res);
+ else viewer.refresh();
+ return Status.OK_STATUS;
+ }
+ };
+ refresh.schedule();
+ }
+
+ private void registerResourceBundleListner(IProject p) {
+ listenedProjects.add(p);
+
+ ResourceBundleManager rbmanager =ResourceBundleManager.getManager(p);
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()){
+ rbmanager.registerResourceBundleChangeListener(rbId, this);
+ }
+ }
+
+ private void unregisterAllResourceBundleListner() {
+ for( IProject p : listenedProjects){
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p);
+ for (String rbId : rbmanager.getResourceBundleIdentifiers()){
+ rbmanager.unregisterResourceBundleChangeListener(rbId, this);
+ }
+ }
+ }
+
+ private void checkListner(IResource res) {
+ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(res.getProject());
+ String rbId = ResourceBundleManager.getResourceBundleId(res);
+ rbmanager.registerResourceBundleChangeListener(rbId, this);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
index 470f50ac..b1c1fe32 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java
@@ -1,166 +1,173 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContainer;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContentManager;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualProject;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.navigator.IDescriptionProvider;
-
-
-
-public class ResourceBundleLabelProvider extends LabelProvider implements ILabelProvider, IDescriptionProvider{
- VirtualContentManager vcManager;
-
- public ResourceBundleLabelProvider(){
- super();
- vcManager = VirtualContentManager.getVirtualContentManager();
- }
-
- @Override
- public Image getImage(Object element) {
- Image returnImage = null;
- if (element instanceof IProject){
- VirtualProject p = (VirtualProject) vcManager.getContainer((IProject) element);
- if (p!=null && p.isFragment())
- return returnImage = ImageUtils.getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE);
- else
- returnImage = PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_OBJ_PROJECT);
- }
- if ((element instanceof IContainer)&&(returnImage == null)){
- returnImage = PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_OBJ_FOLDER);
- }
- if (element instanceof VirtualResourceBundle)
- returnImage = ImageUtils.getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE);
- if (element instanceof IFile){
- if (RBFileUtils.isResourceBundleFile((IFile)element)){
- Locale l = RBFileUtils.getLocale((IFile)element);
- returnImage = ImageUtils.getLocalIcon(l);
-
- VirtualProject p = ((VirtualProject)vcManager.getContainer(((IFile) element).getProject()));
- if (p!=null && p.isFragment())
- returnImage = ImageUtils.getImageWithFragment(returnImage);
- }
- }
-
- if (returnImage != null) {
- if (checkMarkers(element))
- //Add a Warning Image
- returnImage = ImageUtils.getImageWithWarning(returnImage);
- }
- return returnImage;
- }
-
- @Override
- public String getText(Object element) {
-
- StringBuilder text = new StringBuilder();
- if (element instanceof IContainer) {
- IContainer container = (IContainer) element;
- text.append(container.getName());
-
- if (element instanceof IProject){
- VirtualContainer vproject = vcManager.getContainer((IProject) element);
-// if (vproject != null && vproject instanceof VirtualFragment) text.append("°");
- }
-
- VirtualContainer vContainer = vcManager.getContainer(container);
- if (vContainer != null && vContainer.getRbCount() != 0)
- text.append(" ["+vContainer.getRbCount()+"]");
-
- }
- if (element instanceof VirtualResourceBundle){
- text.append(((VirtualResourceBundle)element).getName());
- }
- if (element instanceof IFile){
- if (RBFileUtils.isResourceBundleFile((IFile)element)){
- Locale locale = RBFileUtils.getLocale((IFile)element);
- text.append(" ");
- if (locale != null) {
- text.append(locale);
- }
- else {
- text.append("default");
- }
-
- VirtualProject vproject = (VirtualProject) vcManager.getContainer(((IFile) element).getProject());
- if (vproject!= null && vproject.isFragment()) text.append("°");
- }
- }
- if(element instanceof String){
- text.append(element);
- }
- return text.toString();
- }
-
- @Override
- public String getDescription(Object anElement) {
- if (anElement instanceof IResource)
- return ((IResource)anElement).getName();
- if (anElement instanceof VirtualResourceBundle)
- return ((VirtualResourceBundle)anElement).getName();
- return null;
- }
-
- private boolean checkMarkers(Object element){
- if (element instanceof IResource){
- IMarker[] ms = null;
- try {
- if ((ms=((IResource) element).findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE)).length > 0)
- return true;
-
- if (element instanceof IContainer){
- List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) element,
- FragmentProjectUtils.getFragments(((IContainer) element).getProject()));
-
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer){
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- if (ms.length>0)
- return true;
- }
- } catch (CoreException e) {
- }
- }
- if (element instanceof VirtualResourceBundle){
- ResourceBundleManager rbmanager = ((VirtualResourceBundle)element).getResourceBundleManager();
- String id = ((VirtualResourceBundle)element).getResourceBundleId();
- for (IResource r : rbmanager.getResourceBundles(id)){
- if (RBFileUtils.hasResourceBundleMarker(r)) return true;
- }
- }
-
- return false;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContainer;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualContentManager;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualProject;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.navigator.IDescriptionProvider;
+
+
+
+public class ResourceBundleLabelProvider extends LabelProvider implements ILabelProvider, IDescriptionProvider{
+ VirtualContentManager vcManager;
+
+ public ResourceBundleLabelProvider(){
+ super();
+ vcManager = VirtualContentManager.getVirtualContentManager();
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ Image returnImage = null;
+ if (element instanceof IProject){
+ VirtualProject p = (VirtualProject) vcManager.getContainer((IProject) element);
+ if (p!=null && p.isFragment())
+ return returnImage = ImageUtils.getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE);
+ else
+ returnImage = PlatformUI.getWorkbench().getSharedImages().getImage(
+ ISharedImages.IMG_OBJ_PROJECT);
+ }
+ if ((element instanceof IContainer)&&(returnImage == null)){
+ returnImage = PlatformUI.getWorkbench().getSharedImages().getImage(
+ ISharedImages.IMG_OBJ_FOLDER);
+ }
+ if (element instanceof VirtualResourceBundle)
+ returnImage = ImageUtils.getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE);
+ if (element instanceof IFile){
+ if (RBFileUtils.isResourceBundleFile((IFile)element)){
+ Locale l = RBFileUtils.getLocale((IFile)element);
+ returnImage = ImageUtils.getLocalIcon(l);
+
+ VirtualProject p = ((VirtualProject)vcManager.getContainer(((IFile) element).getProject()));
+ if (p!=null && p.isFragment())
+ returnImage = ImageUtils.getImageWithFragment(returnImage);
+ }
+ }
+
+ if (returnImage != null) {
+ if (checkMarkers(element))
+ //Add a Warning Image
+ returnImage = ImageUtils.getImageWithWarning(returnImage);
+ }
+ return returnImage;
+ }
+
+ @Override
+ public String getText(Object element) {
+
+ StringBuilder text = new StringBuilder();
+ if (element instanceof IContainer) {
+ IContainer container = (IContainer) element;
+ text.append(container.getName());
+
+ if (element instanceof IProject){
+ VirtualContainer vproject = vcManager.getContainer((IProject) element);
+// if (vproject != null && vproject instanceof VirtualFragment) text.append("�");
+ }
+
+ VirtualContainer vContainer = vcManager.getContainer(container);
+ if (vContainer != null && vContainer.getRbCount() != 0)
+ text.append(" ["+vContainer.getRbCount()+"]");
+
+ }
+ if (element instanceof VirtualResourceBundle){
+ text.append(((VirtualResourceBundle)element).getName());
+ }
+ if (element instanceof IFile){
+ if (RBFileUtils.isResourceBundleFile((IFile)element)){
+ Locale locale = RBFileUtils.getLocale((IFile)element);
+ text.append(" ");
+ if (locale != null) {
+ text.append(locale);
+ }
+ else {
+ text.append("default");
+ }
+
+ VirtualProject vproject = (VirtualProject) vcManager.getContainer(((IFile) element).getProject());
+ if (vproject!= null && vproject.isFragment()) text.append("�");
+ }
+ }
+ if(element instanceof String){
+ text.append(element);
+ }
+ return text.toString();
+ }
+
+ @Override
+ public String getDescription(Object anElement) {
+ if (anElement instanceof IResource)
+ return ((IResource)anElement).getName();
+ if (anElement instanceof VirtualResourceBundle)
+ return ((VirtualResourceBundle)anElement).getName();
+ return null;
+ }
+
+ private boolean checkMarkers(Object element){
+ if (element instanceof IResource){
+ IMarker[] ms = null;
+ try {
+ if ((ms=((IResource) element).findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE)).length > 0)
+ return true;
+
+ if (element instanceof IContainer){
+ List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) element,
+ FragmentProjectUtils.getFragments(((IContainer) element).getProject()));
+
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer){
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ if (ms.length>0)
+ return true;
+ }
+ } catch (CoreException e) {
+ }
+ }
+ if (element instanceof VirtualResourceBundle){
+ ResourceBundleManager rbmanager = ((VirtualResourceBundle)element).getResourceBundleManager();
+ String id = ((VirtualResourceBundle)element).getResourceBundleId();
+ for (IResource r : rbmanager.getResourceBundles(id)){
+ if (RBFileUtils.hasResourceBundleMarker(r)) return true;
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
index 7201dd01..4e939200 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java
@@ -1,40 +1,47 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
-
-import java.util.Iterator;
-
-import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.AbstractTreeViewer;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.navigator.CommonViewer;
-
-
-public class ExpandAction extends Action implements IAction{
- private CommonViewer viewer;
-
- public ExpandAction(CommonViewer viewer) {
- this.viewer= viewer;
- setText("Expand Node");
- setToolTipText("expand node");
- setImageDescriptor(RBManagerActivator.getImageDescriptor(ImageUtils.EXPAND));
- }
-
- @Override
- public boolean isEnabled(){
- IStructuredSelection sSelection = (IStructuredSelection) viewer.getSelection();
- if (sSelection.size()>=1) return true;
- else return false;
- }
-
- @Override
- public void run(){
- IStructuredSelection sSelection = (IStructuredSelection) viewer.getSelection();
- Iterator<?> it = sSelection.iterator();
- while (it.hasNext()){
- viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS);
- }
-
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
+
+import java.util.Iterator;
+
+import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.AbstractTreeViewer;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.navigator.CommonViewer;
+
+
+public class ExpandAction extends Action implements IAction{
+ private CommonViewer viewer;
+
+ public ExpandAction(CommonViewer viewer) {
+ this.viewer= viewer;
+ setText("Expand Node");
+ setToolTipText("expand node");
+ setImageDescriptor(RBManagerActivator.getImageDescriptor(ImageUtils.EXPAND));
+ }
+
+ @Override
+ public boolean isEnabled(){
+ IStructuredSelection sSelection = (IStructuredSelection) viewer.getSelection();
+ if (sSelection.size()>=1) return true;
+ else return false;
+ }
+
+ @Override
+ public void run(){
+ IStructuredSelection sSelection = (IStructuredSelection) viewer.getSelection();
+ Iterator<?> it = sSelection.iterator();
+ while (it.hasNext()){
+ viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS);
+ }
+
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
index cd7924b7..1fb7a65f 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java
@@ -1,44 +1,51 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.Hover;
-import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
-import org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants.I18NProjectInformant;
-import org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants.RBMarkerInformant;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.navigator.CommonActionProvider;
-import org.eclipse.ui.navigator.CommonViewer;
-import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-
-
-public class GeneralActionProvider extends CommonActionProvider {
- private IAction expandAction;
-
- public GeneralActionProvider() {
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public void init(ICommonActionExtensionSite aSite){
- super.init(aSite);
- //init Expand-Action
- expandAction = new ExpandAction((CommonViewer) aSite.getStructuredViewer());
-
- //activate View-Hover
- List<HoverInformant> informants = new ArrayList<HoverInformant>();
- informants.add(new I18NProjectInformant());
- informants.add(new RBMarkerInformant());
-
- Hover hover = new Hover(Display.getCurrent().getActiveShell(), informants);
- hover.activateHoverHelp(((CommonViewer)aSite.getStructuredViewer()).getTree());
- }
-
- @Override
- public void fillContextMenu(IMenuManager menu) {
- menu.appendToGroup("expand",expandAction);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.Hover;
+import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
+import org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants.I18NProjectInformant;
+import org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants.RBMarkerInformant;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.navigator.CommonActionProvider;
+import org.eclipse.ui.navigator.CommonViewer;
+import org.eclipse.ui.navigator.ICommonActionExtensionSite;
+
+
+public class GeneralActionProvider extends CommonActionProvider {
+ private IAction expandAction;
+
+ public GeneralActionProvider() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public void init(ICommonActionExtensionSite aSite){
+ super.init(aSite);
+ //init Expand-Action
+ expandAction = new ExpandAction((CommonViewer) aSite.getStructuredViewer());
+
+ //activate View-Hover
+ List<HoverInformant> informants = new ArrayList<HoverInformant>();
+ informants.add(new I18NProjectInformant());
+ informants.add(new RBMarkerInformant());
+
+ Hover hover = new Hover(Display.getCurrent().getActiveShell(), informants);
+ hover.activateHoverHelp(((CommonViewer)aSite.getStructuredViewer()).getTree());
+ }
+
+ @Override
+ public void fillContextMenu(IMenuManager menu) {
+ menu.appendToGroup("expand",expandAction);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
index f158e1ab..6fbe5dc8 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java
@@ -1,37 +1,44 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
-
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IWorkbenchPage;
-
-
-
-public class OpenVRBAction extends Action {
- private ISelectionProvider selectionProvider;
-
- public OpenVRBAction(ISelectionProvider selectionProvider) {
- this.selectionProvider = selectionProvider;
- }
-
- @Override
- public boolean isEnabled(){
- IStructuredSelection sSelection = (IStructuredSelection) selectionProvider.getSelection();
- if (sSelection.size()==1) return true;
- else return false;
- }
-
- @Override
- public void run(){
- IStructuredSelection sSelection = (IStructuredSelection) selectionProvider.getSelection();
- if (sSelection.size()==1 && sSelection.getFirstElement() instanceof VirtualResourceBundle){
- VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection.getFirstElement();
- IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
-
- EditorUtils.openEditor(wp, vRB.getRandomFile(), EditorUtils.RESOURCE_BUNDLE_EDITOR);
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
+
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.RBManagerActivator;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IWorkbenchPage;
+
+
+
+public class OpenVRBAction extends Action {
+ private ISelectionProvider selectionProvider;
+
+ public OpenVRBAction(ISelectionProvider selectionProvider) {
+ this.selectionProvider = selectionProvider;
+ }
+
+ @Override
+ public boolean isEnabled(){
+ IStructuredSelection sSelection = (IStructuredSelection) selectionProvider.getSelection();
+ if (sSelection.size()==1) return true;
+ else return false;
+ }
+
+ @Override
+ public void run(){
+ IStructuredSelection sSelection = (IStructuredSelection) selectionProvider.getSelection();
+ if (sSelection.size()==1 && sSelection.getFirstElement() instanceof VirtualResourceBundle){
+ VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection.getFirstElement();
+ IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
+
+ EditorUtils.openEditor(wp, vRB.getRandomFile(), EditorUtils.RESOURCE_BUNDLE_EDITOR);
+ }
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
index 7811f930..71c22668 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java
@@ -1,29 +1,36 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.navigator.CommonActionProvider;
-import org.eclipse.ui.navigator.ICommonActionConstants;
-import org.eclipse.ui.navigator.ICommonActionExtensionSite;
-
-/*
- * Will be only active for VirtualResourceBundeles
- */
-public class VirtualRBActionProvider extends CommonActionProvider {
- private IAction openAction;
-
- public VirtualRBActionProvider() {
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public void init(ICommonActionExtensionSite aSite){
- super.init(aSite);
- openAction = new OpenVRBAction(aSite.getViewSite().getSelectionProvider());
- }
-
- @Override
- public void fillActionBars(IActionBars actionBars){
- actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, openAction);
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.navigator.CommonActionProvider;
+import org.eclipse.ui.navigator.ICommonActionConstants;
+import org.eclipse.ui.navigator.ICommonActionExtensionSite;
+
+/*
+ * Will be only active for VirtualResourceBundeles
+ */
+public class VirtualRBActionProvider extends CommonActionProvider {
+ private IAction openAction;
+
+ public VirtualRBActionProvider() {
+ // TODO Auto-generated constructor stub
+ }
+
+ @Override
+ public void init(ICommonActionExtensionSite aSite){
+ super.init(aSite);
+ openAction = new OpenVRBAction(aSite.getViewSite().getSelectionProvider());
+ }
+
+ @Override
+ public void fillActionBars(IActionBars actionBars){
+ actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, openAction);
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
index 52bed0b0..086dd235 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java
@@ -1,217 +1,224 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants;
-
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-
-public class I18NProjectInformant implements HoverInformant {
- private String locales;
- private String fragments;
- private boolean show = false;
-
- private Composite infoComposite;
- private Label localeLabel;
- private Composite localeGroup;
- private Label fragmentsLabel;
- private Composite fragmentsGroup;
-
- private GridData infoData;
- private GridData showLocalesData;
- private GridData showFragmentsData;
-
- @Override
- public Composite getInfoComposite(Object data, Composite parent) {
- show = false;
-
- if (infoComposite == null){
- infoComposite = new Composite(parent, SWT.NONE);
- GridLayout layout =new GridLayout(1,false);
- layout.verticalSpacing = 1;
- layout.horizontalSpacing = 0;
- infoComposite.setLayout(layout);
-
- infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- infoComposite.setLayoutData(infoData);
- }
-
- if (data instanceof IProject) {
- addLocale(infoComposite, data);
- addFragments(infoComposite, data);
- }
-
- if (show) {
- infoData.heightHint = -1;
- infoData.widthHint = -1;
- } else {
- infoData.heightHint = 0;
- infoData.widthHint = 0;
- }
-
- infoComposite.layout();
- infoComposite.pack();
- sinkColor(infoComposite);
-
- return infoComposite;
- }
-
- @Override
- public boolean show() {
- return show;
- }
-
- private void setColor(Control control){
- Display display = control.getParent().getDisplay();
-
- control.setForeground(display
- .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- control.setBackground(display
- .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- }
-
- private void sinkColor(Composite composite){
- setColor(composite);
-
- for(Control c : composite.getChildren()){
- setColor(c);
- if (c instanceof Composite) sinkColor((Composite) c);
- }
- }
-
- private void addLocale(Composite parent, Object data){
- if (localeGroup == null) {
- localeGroup = new Composite(parent, SWT.NONE);
- localeLabel = new Label(localeGroup, SWT.SINGLE);
-
- showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- localeGroup.setLayoutData(showLocalesData);
- }
-
- locales = getProvidedLocales(data);
-
- if (locales.length() != 0) {
- localeLabel.setText(locales);
- localeLabel.pack();
- show = true;
-// showLocalesData.heightHint = -1;
-// showLocalesData.widthHint=-1;
- } else {
- localeLabel.setText("No Language Provided");
- localeLabel.pack();
- show = true;
-// showLocalesData.heightHint = 0;
-// showLocalesData.widthHint = 0;
- }
-
-// localeGroup.layout();
- localeGroup.pack();
- }
-
- private void addFragments(Composite parent, Object data){
- if (fragmentsGroup == null) {
- fragmentsGroup = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(1, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- fragmentsGroup.setLayout(layout);
-
- showFragmentsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- fragmentsGroup.setLayoutData(showFragmentsData);
-
- Composite fragmentTitleGroup = new Composite(fragmentsGroup,
- SWT.NONE);
- layout = new GridLayout(2, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- fragmentTitleGroup.setLayout(layout);
-
- Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE);
- fragmentImageLabel.setImage(ImageUtils
- .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE));
- fragmentImageLabel.pack();
-
- Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE);
- fragementTitleLabel.setText("Project Fragments:");
- fragementTitleLabel.pack();
- fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE);
- }
-
- fragments = getFragmentProjects(data);
-
- if (fragments.length() != 0) {
- fragmentsLabel.setText(fragments);
- show = true;
- showFragmentsData.heightHint = -1;
- showFragmentsData.widthHint= -1;
- fragmentsLabel.pack();
- } else {
- showFragmentsData.heightHint = 0;
- showFragmentsData.widthHint = 0;
- }
-
- fragmentsGroup.layout();
- fragmentsGroup.pack();
- }
-
- private String getProvidedLocales(Object data) {
- if (data instanceof IProject) {
- ResourceBundleManager rbmanger = ResourceBundleManager.getManager((IProject) data);
- Set<Locale> ls = rbmanger.getProjectProvidedLocales();
-
- if (ls.size() > 0) {
- StringBuilder sb = new StringBuilder();
- sb.append("Provided Languages:\n");
-
- int i = 0;
- for (Locale l : ls) {
- if (!l.toString().equals(""))
- sb.append(l.getDisplayName());
- else
- sb.append("[Default]");
-
- if (++i != ls.size()) {
- sb.append(",");
- if (i % 5 == 0)
- sb.append("\n");
- else
- sb.append(" ");
- }
-
- }
- return sb.toString();
- }
- }
-
-
- return "";
- }
-
- private String getFragmentProjects(Object data) {
- if (data instanceof IProject){
- List<IProject> fragments = FragmentProjectUtils.getFragments((IProject) data);
- if (fragments.size() > 0) {
- StringBuilder sb = new StringBuilder();
-
- int i = 0;
- for (IProject f : fragments){
- sb.append(f.getName());
- if (++i != fragments.size()) sb.append("\n");
- }
- return sb.toString();
- }
- }
- return "";
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants;
+
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+
+public class I18NProjectInformant implements HoverInformant {
+ private String locales;
+ private String fragments;
+ private boolean show = false;
+
+ private Composite infoComposite;
+ private Label localeLabel;
+ private Composite localeGroup;
+ private Label fragmentsLabel;
+ private Composite fragmentsGroup;
+
+ private GridData infoData;
+ private GridData showLocalesData;
+ private GridData showFragmentsData;
+
+ @Override
+ public Composite getInfoComposite(Object data, Composite parent) {
+ show = false;
+
+ if (infoComposite == null){
+ infoComposite = new Composite(parent, SWT.NONE);
+ GridLayout layout =new GridLayout(1,false);
+ layout.verticalSpacing = 1;
+ layout.horizontalSpacing = 0;
+ infoComposite.setLayout(layout);
+
+ infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ infoComposite.setLayoutData(infoData);
+ }
+
+ if (data instanceof IProject) {
+ addLocale(infoComposite, data);
+ addFragments(infoComposite, data);
+ }
+
+ if (show) {
+ infoData.heightHint = -1;
+ infoData.widthHint = -1;
+ } else {
+ infoData.heightHint = 0;
+ infoData.widthHint = 0;
+ }
+
+ infoComposite.layout();
+ infoComposite.pack();
+ sinkColor(infoComposite);
+
+ return infoComposite;
+ }
+
+ @Override
+ public boolean show() {
+ return show;
+ }
+
+ private void setColor(Control control){
+ Display display = control.getParent().getDisplay();
+
+ control.setForeground(display
+ .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ control.setBackground(display
+ .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ }
+
+ private void sinkColor(Composite composite){
+ setColor(composite);
+
+ for(Control c : composite.getChildren()){
+ setColor(c);
+ if (c instanceof Composite) sinkColor((Composite) c);
+ }
+ }
+
+ private void addLocale(Composite parent, Object data){
+ if (localeGroup == null) {
+ localeGroup = new Composite(parent, SWT.NONE);
+ localeLabel = new Label(localeGroup, SWT.SINGLE);
+
+ showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ localeGroup.setLayoutData(showLocalesData);
+ }
+
+ locales = getProvidedLocales(data);
+
+ if (locales.length() != 0) {
+ localeLabel.setText(locales);
+ localeLabel.pack();
+ show = true;
+// showLocalesData.heightHint = -1;
+// showLocalesData.widthHint=-1;
+ } else {
+ localeLabel.setText("No Language Provided");
+ localeLabel.pack();
+ show = true;
+// showLocalesData.heightHint = 0;
+// showLocalesData.widthHint = 0;
+ }
+
+// localeGroup.layout();
+ localeGroup.pack();
+ }
+
+ private void addFragments(Composite parent, Object data){
+ if (fragmentsGroup == null) {
+ fragmentsGroup = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ fragmentsGroup.setLayout(layout);
+
+ showFragmentsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ fragmentsGroup.setLayoutData(showFragmentsData);
+
+ Composite fragmentTitleGroup = new Composite(fragmentsGroup,
+ SWT.NONE);
+ layout = new GridLayout(2, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 5;
+ fragmentTitleGroup.setLayout(layout);
+
+ Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE);
+ fragmentImageLabel.setImage(ImageUtils
+ .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE));
+ fragmentImageLabel.pack();
+
+ Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE);
+ fragementTitleLabel.setText("Project Fragments:");
+ fragementTitleLabel.pack();
+ fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE);
+ }
+
+ fragments = getFragmentProjects(data);
+
+ if (fragments.length() != 0) {
+ fragmentsLabel.setText(fragments);
+ show = true;
+ showFragmentsData.heightHint = -1;
+ showFragmentsData.widthHint= -1;
+ fragmentsLabel.pack();
+ } else {
+ showFragmentsData.heightHint = 0;
+ showFragmentsData.widthHint = 0;
+ }
+
+ fragmentsGroup.layout();
+ fragmentsGroup.pack();
+ }
+
+ private String getProvidedLocales(Object data) {
+ if (data instanceof IProject) {
+ ResourceBundleManager rbmanger = ResourceBundleManager.getManager((IProject) data);
+ Set<Locale> ls = rbmanger.getProjectProvidedLocales();
+
+ if (ls.size() > 0) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Provided Languages:\n");
+
+ int i = 0;
+ for (Locale l : ls) {
+ if (!l.toString().equals(""))
+ sb.append(l.getDisplayName());
+ else
+ sb.append("[Default]");
+
+ if (++i != ls.size()) {
+ sb.append(",");
+ if (i % 5 == 0)
+ sb.append("\n");
+ else
+ sb.append(" ");
+ }
+
+ }
+ return sb.toString();
+ }
+ }
+
+
+ return "";
+ }
+
+ private String getFragmentProjects(Object data) {
+ if (data instanceof IProject){
+ List<IProject> fragments = FragmentProjectUtils.getFragments((IProject) data);
+ if (fragments.size() > 0) {
+ StringBuilder sb = new StringBuilder();
+
+ int i = 0;
+ for (IProject f : fragments){
+ sb.append(f.getName());
+ if (++i != fragments.size()) sb.append("\n");
+ }
+ return sb.toString();
+ }
+ }
+ return "";
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
index 3ce44d0b..ed1164c0 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java
@@ -1,266 +1,273 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants;
-
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-
-
-public class RBMarkerInformant implements HoverInformant {
- private int MAX_PROBLEMS = 20;
- private boolean show = false;
-
- private String title;
- private String problems;
-
- private Composite infoComposite;
- private Composite titleGroup;
- private Label titleLabel;
- private Composite problemGroup;
- private Label problemLabel;
-
- private GridData infoData;
- private GridData showTitleData;
- private GridData showProblemsData;
-
-
- @Override
- public Composite getInfoComposite(Object data, Composite parent) {
- show = false;
-
- if (infoComposite == null){
- infoComposite = new Composite(parent, SWT.NONE);
- GridLayout layout =new GridLayout(1,false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- infoComposite.setLayout(layout);
-
- infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- infoComposite.setLayoutData(infoData);
- }
-
- if (data instanceof VirtualResourceBundle || data instanceof IResource) {
- addTitle(infoComposite, data);
- addProblems(infoComposite, data);
- }
-
- if (show){
- infoData.heightHint=-1;
- infoData.widthHint=-1;
- } else {
- infoData.heightHint=0;
- infoData.widthHint=0;
- }
-
- infoComposite.layout();
- sinkColor(infoComposite);
- infoComposite.pack();
-
- return infoComposite;
- }
-
- @Override
- public boolean show(){
- return show;
- }
-
- private void setColor(Control control){
- Display display = control.getParent().getDisplay();
-
- control.setForeground(display
- .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- control.setBackground(display
- .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- }
-
- private void sinkColor(Composite composite){
- setColor(composite);
-
- for(Control c : composite.getChildren()){
- setColor(c);
- if (c instanceof Composite) sinkColor((Composite) c);
- }
- }
-
- private void addTitle(Composite parent, Object data){
- if (titleGroup == null) {
- titleGroup = new Composite(parent, SWT.NONE);
- titleLabel = new Label(titleGroup, SWT.SINGLE);
-
- showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- titleGroup.setLayoutData(showTitleData);
- }
- title = getTitel(data);
-
- if (title.length() != 0) {
- titleLabel.setText(title);
- show = true;
- showTitleData.heightHint=-1;
- showTitleData.widthHint=-1;
- titleLabel.pack();
- } else {
- showTitleData.heightHint=0;
- showTitleData.widthHint=0;
- }
-
- titleGroup.layout();
- titleGroup.pack();
- }
-
-
- private void addProblems(Composite parent, Object data){
- if (problemGroup == null) {
- problemGroup = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(1, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 0;
- problemGroup.setLayout(layout);
-
- showProblemsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
- problemGroup.setLayoutData(showProblemsData);
-
- Composite problemTitleGroup = new Composite(problemGroup, SWT.NONE);
- layout = new GridLayout(2, false);
- layout.verticalSpacing = 0;
- layout.horizontalSpacing = 5;
- problemTitleGroup.setLayout(layout);
-
- Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE);
- warningImageLabel.setImage(ImageUtils
- .getBaseImage(ImageUtils.WARNING_IMAGE));
- warningImageLabel.pack();
-
- Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE);
- waringTitleLabel.setText("ResourceBundle-Problems:");
- waringTitleLabel.pack();
-
- problemLabel = new Label(problemGroup, SWT.SINGLE);
- }
-
- problems = getProblems(data);
-
- if (problems.length() != 0) {
- problemLabel.setText(problems);
- show = true;
- showProblemsData.heightHint=-1;
- showProblemsData.widthHint=-1;
- problemLabel.pack();
- } else {
- showProblemsData.heightHint=0;
- showProblemsData.widthHint=0;
- }
-
- problemGroup.layout();
- problemGroup.pack();
- }
-
-
- private String getTitel(Object data) {
- if (data instanceof IFile){
- return ((IResource)data).getFullPath().toString();
- }
- if (data instanceof VirtualResourceBundle){
- return ((VirtualResourceBundle)data).getResourceBundleId();
- }
-
- return "";
- }
-
- private String getProblems(Object data){
- IMarker[] ms = null;
-
- if (data instanceof IResource){
- IResource res = (IResource) data;
- try {
- if (res.exists())
- ms = res.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- else ms = new IMarker[0];
- } catch (CoreException e) {
- e.printStackTrace();
- }
- if (data instanceof IContainer){
- //add problem of same folder in the fragment-project
- List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) res,
- FragmentProjectUtils.getFragments(res.getProject()));
-
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer){
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
-
- ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- }
- }
- }
- }
-
- if (data instanceof VirtualResourceBundle){
- VirtualResourceBundle vRB = (VirtualResourceBundle) data;
-
- ResourceBundleManager rbmanager = vRB.getResourceBundleManager();
- IMarker[] file_ms;
-
- Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB.getResourceBundleId());
- if (!rBundles.isEmpty())
- for (IResource r : rBundles){
- try {
- file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
- if (ms != null) {
- ms = EditorUtils.concatMarkerArray(ms, file_ms);
- }else{
- ms = file_ms;
- }
- } catch (Exception e) {
- }
- }
- }
-
-
- StringBuilder sb = new StringBuilder();
- int count=0;
-
- if (ms != null && ms.length!=0){
- for (IMarker m : ms) {
- try {
- sb.append(m.getAttribute(IMarker.MESSAGE));
- sb.append("\n");
- count++;
- if (count == MAX_PROBLEMS && ms.length-count!=0){
- sb.append(" ... and ");
- sb.append(ms.length-count);
- sb.append(" other problems");
- break;
- }
- } catch (CoreException e) {
- }
- ;
- }
- return sb.toString();
- }
-
- return "";
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.actions.hoverinformants;
+
+import java.util.Collection;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.ImageUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.babel.tapiji.tools.rbmanager.ui.hover.HoverInformant;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+
+
+public class RBMarkerInformant implements HoverInformant {
+ private int MAX_PROBLEMS = 20;
+ private boolean show = false;
+
+ private String title;
+ private String problems;
+
+ private Composite infoComposite;
+ private Composite titleGroup;
+ private Label titleLabel;
+ private Composite problemGroup;
+ private Label problemLabel;
+
+ private GridData infoData;
+ private GridData showTitleData;
+ private GridData showProblemsData;
+
+
+ @Override
+ public Composite getInfoComposite(Object data, Composite parent) {
+ show = false;
+
+ if (infoComposite == null){
+ infoComposite = new Composite(parent, SWT.NONE);
+ GridLayout layout =new GridLayout(1,false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ infoComposite.setLayout(layout);
+
+ infoData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ infoComposite.setLayoutData(infoData);
+ }
+
+ if (data instanceof VirtualResourceBundle || data instanceof IResource) {
+ addTitle(infoComposite, data);
+ addProblems(infoComposite, data);
+ }
+
+ if (show){
+ infoData.heightHint=-1;
+ infoData.widthHint=-1;
+ } else {
+ infoData.heightHint=0;
+ infoData.widthHint=0;
+ }
+
+ infoComposite.layout();
+ sinkColor(infoComposite);
+ infoComposite.pack();
+
+ return infoComposite;
+ }
+
+ @Override
+ public boolean show(){
+ return show;
+ }
+
+ private void setColor(Control control){
+ Display display = control.getParent().getDisplay();
+
+ control.setForeground(display
+ .getSystemColor(SWT.COLOR_INFO_FOREGROUND));
+ control.setBackground(display
+ .getSystemColor(SWT.COLOR_INFO_BACKGROUND));
+ }
+
+ private void sinkColor(Composite composite){
+ setColor(composite);
+
+ for(Control c : composite.getChildren()){
+ setColor(c);
+ if (c instanceof Composite) sinkColor((Composite) c);
+ }
+ }
+
+ private void addTitle(Composite parent, Object data){
+ if (titleGroup == null) {
+ titleGroup = new Composite(parent, SWT.NONE);
+ titleLabel = new Label(titleGroup, SWT.SINGLE);
+
+ showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ titleGroup.setLayoutData(showTitleData);
+ }
+ title = getTitel(data);
+
+ if (title.length() != 0) {
+ titleLabel.setText(title);
+ show = true;
+ showTitleData.heightHint=-1;
+ showTitleData.widthHint=-1;
+ titleLabel.pack();
+ } else {
+ showTitleData.heightHint=0;
+ showTitleData.widthHint=0;
+ }
+
+ titleGroup.layout();
+ titleGroup.pack();
+ }
+
+
+ private void addProblems(Composite parent, Object data){
+ if (problemGroup == null) {
+ problemGroup = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout(1, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 0;
+ problemGroup.setLayout(layout);
+
+ showProblemsData = new GridData(SWT.LEFT, SWT.TOP, true, true);
+ problemGroup.setLayoutData(showProblemsData);
+
+ Composite problemTitleGroup = new Composite(problemGroup, SWT.NONE);
+ layout = new GridLayout(2, false);
+ layout.verticalSpacing = 0;
+ layout.horizontalSpacing = 5;
+ problemTitleGroup.setLayout(layout);
+
+ Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE);
+ warningImageLabel.setImage(ImageUtils
+ .getBaseImage(ImageUtils.WARNING_IMAGE));
+ warningImageLabel.pack();
+
+ Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE);
+ waringTitleLabel.setText("ResourceBundle-Problems:");
+ waringTitleLabel.pack();
+
+ problemLabel = new Label(problemGroup, SWT.SINGLE);
+ }
+
+ problems = getProblems(data);
+
+ if (problems.length() != 0) {
+ problemLabel.setText(problems);
+ show = true;
+ showProblemsData.heightHint=-1;
+ showProblemsData.widthHint=-1;
+ problemLabel.pack();
+ } else {
+ showProblemsData.heightHint=0;
+ showProblemsData.widthHint=0;
+ }
+
+ problemGroup.layout();
+ problemGroup.pack();
+ }
+
+
+ private String getTitel(Object data) {
+ if (data instanceof IFile){
+ return ((IResource)data).getFullPath().toString();
+ }
+ if (data instanceof VirtualResourceBundle){
+ return ((VirtualResourceBundle)data).getResourceBundleId();
+ }
+
+ return "";
+ }
+
+ private String getProblems(Object data){
+ IMarker[] ms = null;
+
+ if (data instanceof IResource){
+ IResource res = (IResource) data;
+ try {
+ if (res.exists())
+ ms = res.findMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ else ms = new IMarker[0];
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ if (data instanceof IContainer){
+ //add problem of same folder in the fragment-project
+ List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) res,
+ FragmentProjectUtils.getFragments(res.getProject()));
+
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer){
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+
+ ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
+ }
+ } catch (CoreException e) {
+ }
+ }
+ }
+ }
+
+ if (data instanceof VirtualResourceBundle){
+ VirtualResourceBundle vRB = (VirtualResourceBundle) data;
+
+ ResourceBundleManager rbmanager = vRB.getResourceBundleManager();
+ IMarker[] file_ms;
+
+ Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB.getResourceBundleId());
+ if (!rBundles.isEmpty())
+ for (IResource r : rBundles){
+ try {
+ file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID, false, IResource.DEPTH_INFINITE);
+ if (ms != null) {
+ ms = EditorUtils.concatMarkerArray(ms, file_ms);
+ }else{
+ ms = file_ms;
+ }
+ } catch (Exception e) {
+ }
+ }
+ }
+
+
+ StringBuilder sb = new StringBuilder();
+ int count=0;
+
+ if (ms != null && ms.length!=0){
+ for (IMarker m : ms) {
+ try {
+ sb.append(m.getAttribute(IMarker.MESSAGE));
+ sb.append("\n");
+ count++;
+ if (count == MAX_PROBLEMS && ms.length-count!=0){
+ sb.append(" ... and ");
+ sb.append(ms.length-count);
+ sb.append(" other problems");
+ break;
+ }
+ } catch (CoreException e) {
+ }
+ ;
+ }
+ return sb.toString();
+ }
+
+ return "";
+ }
+}
diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
index 989b7b73..bb0d56a8 100644
--- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
+++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java
@@ -1,65 +1,72 @@
-package org.eclipse.babel.tapiji.tools.rbmanager.viewer.filters;
-
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
-import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
-import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
-import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-
-
-
-public class ProblematicResourceBundleFilter extends ViewerFilter {
-
- /**
- * Shows only IContainer and VirtualResourcebundles with all his
- * properties-files, which have RB_Marker.
- */
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (element instanceof IFile){
- return true;
- }
- if (element instanceof VirtualResourceBundle) {
- for (IResource f : ((VirtualResourceBundle)element).getFiles() ){
- if (RBFileUtils.hasResourceBundleMarker(f))
- return true;
- }
- }
- if (element instanceof IContainer) {
- try {
- IMarker[] ms = null;
- if ((ms=((IContainer) element).findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE)).length > 0)
- return true;
-
- List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) element,
- FragmentProjectUtils.getFragments(((IContainer) element).getProject()));
-
- IMarker[] fragment_ms;
- for (IContainer c : fragmentContainer){
- try {
- if (c.exists()) {
- fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
- IResource.DEPTH_INFINITE);
- ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- if (ms.length>0)
- return true;
-
- } catch (CoreException e) { }
- }
- return false;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.tools.rbmanager.viewer.filters;
+
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.babel.tapiji.tools.core.util.FragmentProjectUtils;
+import org.eclipse.babel.tapiji.tools.core.util.RBFileUtils;
+import org.eclipse.babel.tapiji.tools.core.util.ResourceUtils;
+import org.eclipse.babel.tapiji.tools.rbmanager.model.VirtualResourceBundle;
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+
+
+
+public class ProblematicResourceBundleFilter extends ViewerFilter {
+
+ /**
+ * Shows only IContainer and VirtualResourcebundles with all his
+ * properties-files, which have RB_Marker.
+ */
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ if (element instanceof IFile){
+ return true;
+ }
+ if (element instanceof VirtualResourceBundle) {
+ for (IResource f : ((VirtualResourceBundle)element).getFiles() ){
+ if (RBFileUtils.hasResourceBundleMarker(f))
+ return true;
+ }
+ }
+ if (element instanceof IContainer) {
+ try {
+ IMarker[] ms = null;
+ if ((ms=((IContainer) element).findMarkers(EditorUtils.RB_MARKER_ID, true, IResource.DEPTH_INFINITE)).length > 0)
+ return true;
+
+ List<IContainer> fragmentContainer = ResourceUtils.getCorrespondingFolders((IContainer) element,
+ FragmentProjectUtils.getFragments(((IContainer) element).getProject()));
+
+ IMarker[] fragment_ms;
+ for (IContainer c : fragmentContainer){
+ try {
+ if (c.exists()) {
+ fragment_ms = c.findMarkers(EditorUtils.RB_MARKER_ID, false,
+ IResource.DEPTH_INFINITE);
+ ms = EditorUtils.concatMarkerArray(ms, fragment_ms);
+ }
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ if (ms.length>0)
+ return true;
+
+ } catch (CoreException e) { }
+ }
+ return false;
+ }
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java
index 99566244..0248bdd8 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IAbstractKeyTreeModel.java
@@ -1,19 +1,26 @@
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-
-
-public interface IAbstractKeyTreeModel {
-
- IKeyTreeNode[] getChildren(IKeyTreeNode node);
-
- IKeyTreeNode getChild(String key);
-
- IKeyTreeNode[] getRootNodes();
-
- IKeyTreeNode getRootNode();
-
- IKeyTreeNode getParent(IKeyTreeNode node);
-
- void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+
+
+public interface IAbstractKeyTreeModel {
+
+ IKeyTreeNode[] getChildren(IKeyTreeNode node);
+
+ IKeyTreeNode getChild(String key);
+
+ IKeyTreeNode[] getRootNodes();
+
+ IKeyTreeNode getRootNode();
+
+ IKeyTreeNode getParent(IKeyTreeNode node);
+
+ void accept(IKeyTreeVisitor visitor, IKeyTreeNode node);
+
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java
index 3651ca70..88f2d84b 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeContributor.java
@@ -1,13 +1,20 @@
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-import org.eclipse.jface.viewers.TreeViewer;
-
-
-public interface IKeyTreeContributor {
-
- void contribute(final TreeViewer treeViewer);
-
- IKeyTreeNode getKeyTreeNode(String key);
-
- IKeyTreeNode[] getRootKeyItems();
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+import org.eclipse.jface.viewers.TreeViewer;
+
+
+public interface IKeyTreeContributor {
+
+ void contribute(final TreeViewer treeViewer);
+
+ IKeyTreeNode getKeyTreeNode(String key);
+
+ IKeyTreeNode[] getRootKeyItems();
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java
index db96d445..bc1509f8 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeNode.java
@@ -1,62 +1,69 @@
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-
-
-public interface IKeyTreeNode {
-
- /**
- * Returns the key of the corresponding Resource-Bundle entry.
- * @return The key of the Resource-Bundle entry
- */
- String getMessageKey();
-
- /**
- * Returns the set of Resource-Bundle entries of the next deeper
- * hierarchy level that share the represented entry as their common
- * parent.
- * @return The direct child Resource-Bundle entries
- */
- IKeyTreeNode[] getChildren();
-
- /**
- * The represented Resource-Bundle entry's id without the prefix defined
- * by the entry's parent.
- * @return The Resource-Bundle entry's display name.
- */
- String getName();
-
- /**
- * Returns the set of Resource-Bundle entries from all deeper hierarchy
- * levels that share the represented entry as their common parent.
- * @return All child Resource-Bundle entries
- */
-// Collection<? extends IKeyTreeItem> getNestedChildren();
-
- /**
- * Returns whether this Resource-Bundle entry is visible under the
- * given filter expression.
- * @param filter The filter expression
- * @return True if the filter expression matches the represented Resource-Bundle entry
- */
-// boolean applyFilter(String filter);
-
- /**
- * The Resource-Bundle entries parent.
- * @return The parent Resource-Bundle entry
- */
- IKeyTreeNode getParent();
-
- /**
- * The Resource-Bundles key representation.
- * @return The Resource-Bundle reference, if known
- */
- IMessagesBundleGroup getMessagesBundleGroup();
-
-
- boolean isUsedAsKey();
-
- void setParent(IKeyTreeNode parentNode);
-
- void addChild(IKeyTreeNode childNode);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+
+
+public interface IKeyTreeNode {
+
+ /**
+ * Returns the key of the corresponding Resource-Bundle entry.
+ * @return The key of the Resource-Bundle entry
+ */
+ String getMessageKey();
+
+ /**
+ * Returns the set of Resource-Bundle entries of the next deeper
+ * hierarchy level that share the represented entry as their common
+ * parent.
+ * @return The direct child Resource-Bundle entries
+ */
+ IKeyTreeNode[] getChildren();
+
+ /**
+ * The represented Resource-Bundle entry's id without the prefix defined
+ * by the entry's parent.
+ * @return The Resource-Bundle entry's display name.
+ */
+ String getName();
+
+ /**
+ * Returns the set of Resource-Bundle entries from all deeper hierarchy
+ * levels that share the represented entry as their common parent.
+ * @return All child Resource-Bundle entries
+ */
+// Collection<? extends IKeyTreeItem> getNestedChildren();
+
+ /**
+ * Returns whether this Resource-Bundle entry is visible under the
+ * given filter expression.
+ * @param filter The filter expression
+ * @return True if the filter expression matches the represented Resource-Bundle entry
+ */
+// boolean applyFilter(String filter);
+
+ /**
+ * The Resource-Bundle entries parent.
+ * @return The parent Resource-Bundle entry
+ */
+ IKeyTreeNode getParent();
+
+ /**
+ * The Resource-Bundles key representation.
+ * @return The Resource-Bundle reference, if known
+ */
+ IMessagesBundleGroup getMessagesBundleGroup();
+
+
+ boolean isUsedAsKey();
+
+ void setParent(IKeyTreeNode parentNode);
+
+ void addChild(IKeyTreeNode childNode);
+
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java
index 4b24dd74..e7f294e4 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IKeyTreeVisitor.java
@@ -1,25 +1,22 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * 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:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-
-/**
- * Objects implementing this interface can act as a visitor to a
- * <code>IKeyTreeModel</code>.
- * @author Pascal Essiembre ([email protected])
- */
-public interface IKeyTreeVisitor {
- /**
- * Visits a key tree node.
- * @param item key tree node to visit
- */
- void visitKeyTreeNode(IKeyTreeNode node);
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+
+/**
+ * Objects implementing this interface can act as a visitor to a
+ * <code>IKeyTreeModel</code>.
+ * @author Pascal Essiembre ([email protected])
+ */
+public interface IKeyTreeVisitor {
+ /**
+ * Visits a key tree node.
+ * @param item key tree node to visit
+ */
+ void visitKeyTreeNode(IKeyTreeNode node);
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessage.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessage.java
index 66fff82c..54bd0359 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessage.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessage.java
@@ -1,31 +1,38 @@
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Locale;
-
-
-
-public interface IMessage {
-
- String getKey();
-
- String getValue();
-
- Locale getLocale();
-
- String getComment();
-
- boolean isActive();
-
- String toString();
-
- void setActive(boolean active);
-
- void setComment(String comment);
-
- void setComment(String comment, boolean silent);
-
- void setText(String test);
-
- void setText(String test, boolean silent);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+import java.util.Locale;
+
+
+
+public interface IMessage {
+
+ String getKey();
+
+ String getValue();
+
+ Locale getLocale();
+
+ String getComment();
+
+ boolean isActive();
+
+ String toString();
+
+ void setActive(boolean active);
+
+ void setComment(String comment);
+
+ void setComment(String comment, boolean silent);
+
+ void setText(String test);
+
+ void setText(String test, boolean silent);
+
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java
index b6ea1dfd..4fdbc9f8 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundle.java
@@ -1,40 +1,47 @@
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-
-
-
-
-public interface IMessagesBundle {
-
- void dispose();
-
- void renameMessageKey(String sourceKey, String targetKey);
-
- void removeMessage(String messageKey);
-
- void duplicateMessage(String sourceKey, String targetKey);
-
- Locale getLocale();
-
- String[] getKeys();
-
- String getValue(String key);
-
- Collection<IMessage> getMessages();
-
- IMessage getMessage(String key);
-
- void addMessage(IMessage message);
-
- void removeMessages(String[] messageKeys);
-
- void setComment(String comment);
-
- String getComment();
-
- IMessagesResource getResource();
-
- void removeMessageAddParentKey(String key);
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+import java.util.Collection;
+import java.util.Locale;
+
+
+
+
+public interface IMessagesBundle {
+
+ void dispose();
+
+ void renameMessageKey(String sourceKey, String targetKey);
+
+ void removeMessage(String messageKey);
+
+ void duplicateMessage(String sourceKey, String targetKey);
+
+ Locale getLocale();
+
+ String[] getKeys();
+
+ String getValue(String key);
+
+ Collection<IMessage> getMessages();
+
+ IMessage getMessage(String key);
+
+ void addMessage(IMessage message);
+
+ void removeMessages(String[] messageKeys);
+
+ void setComment(String comment);
+
+ String getComment();
+
+ IMessagesResource getResource();
+
+ void removeMessageAddParentKey(String key);
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java
index 99ccde09..78aefc04 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesBundleGroup.java
@@ -1,46 +1,53 @@
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-
-
-public interface IMessagesBundleGroup {
-
- Collection<IMessagesBundle> getMessagesBundles();
-
- boolean containsKey(String key);
-
- IMessage[] getMessages(String key);
-
- IMessage getMessage(String key, Locale locale);
-
- IMessagesBundle getMessagesBundle(Locale locale);
-
- void removeMessages(String messageKey);
-
- boolean isKey(String key);
-
- void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
-
- String[] getMessageKeys();
-
- void addMessages(String key);
-
- int getMessagesBundleCount();
-
- String getName();
-
- String getResourceBundleId();
-
- boolean hasPropertiesFileGroupStrategy();
-
- public boolean isMessageKey(String key);
-
- public String getProjectName();
-
- public void removeMessagesBundle(IMessagesBundle messagesBundle);
-
- public void dispose();
-
- void removeMessagesAddParentKey(String key);
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+import java.util.Collection;
+import java.util.Locale;
+
+
+public interface IMessagesBundleGroup {
+
+ Collection<IMessagesBundle> getMessagesBundles();
+
+ boolean containsKey(String key);
+
+ IMessage[] getMessages(String key);
+
+ IMessage getMessage(String key, Locale locale);
+
+ IMessagesBundle getMessagesBundle(Locale locale);
+
+ void removeMessages(String messageKey);
+
+ boolean isKey(String key);
+
+ void addMessagesBundle(Locale locale, IMessagesBundle messagesBundle);
+
+ String[] getMessageKeys();
+
+ void addMessages(String key);
+
+ int getMessagesBundleCount();
+
+ String getName();
+
+ String getResourceBundleId();
+
+ boolean hasPropertiesFileGroupStrategy();
+
+ public boolean isMessageKey(String key);
+
+ public String getProjectName();
+
+ public void removeMessagesBundle(IMessagesBundle messagesBundle);
+
+ public void dispose();
+
+ void removeMessagesAddParentKey(String key);
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java
index e62f51ea..c6133588 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
public interface IMessagesEditor {
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResource.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResource.java
index 71bd9079..b82b1214 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResource.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResource.java
@@ -1,65 +1,62 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * 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:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Locale;
-
-/**
- * Class abstracting the underlying native storage mechanism for persisting
- * internationalised text messages.
- * @author Pascal Essiembre
- */
-public interface IMessagesResource {
-
- /**
- * Gets the resource locale.
- * @return locale
- */
- Locale getLocale();
- /**
- * Gets the underlying object abstracted by this resource (e.g. a File).
- * @return source object
- */
- Object getSource();
- /**
- * Serializes a {@link MessagesBundle} instance to its native format.
- * @param messagesBundle the MessagesBundle to serialize
- */
- void serialize(IMessagesBundle messagesBundle);
- /**
- * Deserializes a {@link MessagesBundle} instance from its native format.
- * @param messagesBundle the MessagesBundle to deserialize
- */
- void deserialize(IMessagesBundle messagesBundle);
- /**
- * Adds a messages resource listener. Implementors are required to notify
- * listeners of changes within the native implementation.
- * @param listener the listener
- */
- void addMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
- /**
- * Removes a messages resource listener.
- * @param listener the listener
- */
- void removeMessagesResourceChangeListener(
- IMessagesResourceChangeListener listener);
- /**
- * @return The resource location label. or null if unknown.
- */
- String getResourceLocationLabel();
-
- /**
- * Called when the group it belongs to is disposed.
- */
- void dispose();
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+import java.util.Locale;
+
+/**
+ * Class abstracting the underlying native storage mechanism for persisting
+ * internationalised text messages.
+ * @author Pascal Essiembre
+ */
+public interface IMessagesResource {
+
+ /**
+ * Gets the resource locale.
+ * @return locale
+ */
+ Locale getLocale();
+ /**
+ * Gets the underlying object abstracted by this resource (e.g. a File).
+ * @return source object
+ */
+ Object getSource();
+ /**
+ * Serializes a {@link MessagesBundle} instance to its native format.
+ * @param messagesBundle the MessagesBundle to serialize
+ */
+ void serialize(IMessagesBundle messagesBundle);
+ /**
+ * Deserializes a {@link MessagesBundle} instance from its native format.
+ * @param messagesBundle the MessagesBundle to deserialize
+ */
+ void deserialize(IMessagesBundle messagesBundle);
+ /**
+ * Adds a messages resource listener. Implementors are required to notify
+ * listeners of changes within the native implementation.
+ * @param listener the listener
+ */
+ void addMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener);
+ /**
+ * Removes a messages resource listener.
+ * @param listener the listener
+ */
+ void removeMessagesResourceChangeListener(
+ IMessagesResourceChangeListener listener);
+ /**
+ * @return The resource location label. or null if unknown.
+ */
+ String getResourceLocationLabel();
+
+ /**
+ * Called when the group it belongs to is disposed.
+ */
+ void dispose();
+
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java
index c42bbd67..dba216bb 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesResourceChangeListener.java
@@ -1,24 +1,21 @@
-/*******************************************************************************
- * Copyright (c) 2007 Pascal Essiembre.
- * 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:
- * Pascal Essiembre - initial API and implementation
- ******************************************************************************/
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-/**
- * Listener being notified when a {@link IMessagesResource} content changes.
- * @author Pascal Essiembre
- */
-public interface IMessagesResourceChangeListener {
-
- /**
- * Method called when the messages resource has changed.
- * @param resource the resource that changed
- */
- void resourceChanged(IMessagesResource resource);
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+/**
+ * Listener being notified when a {@link IMessagesResource} content changes.
+ * @author Pascal Essiembre
+ */
+public interface IMessagesResourceChangeListener {
+
+ /**
+ * Method called when the messages resource has changed.
+ * @param resource the resource that changed
+ */
+ void resourceChanged(IMessagesResource resource);
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java
index d4e0ef52..6673e1fb 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IValuedKeyTreeNode.java
@@ -1,26 +1,33 @@
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Map;
-
-
-public interface IValuedKeyTreeNode extends IKeyTreeNode{
-
- public void initValues (Map<Locale, String> values);
-
- public void addValue (Locale locale, String value);
-
- public void setValue (Locale locale, String newValue);
-
- public String getValue (Locale locale);
-
- public Collection<String> getValues ();
-
- public void setInfo(Object info);
-
- public Object getInfo();
-
- public Collection<Locale> getLocales ();
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+import java.util.Collection;
+import java.util.Locale;
+import java.util.Map;
+
+
+public interface IValuedKeyTreeNode extends IKeyTreeNode{
+
+ public void initValues (Map<Locale, String> values);
+
+ public void addValue (Locale locale, String value);
+
+ public void setValue (Locale locale, String newValue);
+
+ public String getValue (Locale locale);
+
+ public Collection<String> getValues ();
+
+ public void setInfo(Object info);
+
+ public Object getInfo();
+
+ public Collection<Locale> getLocales ();
+
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/TreeType.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/TreeType.java
index 86fe1a93..6b383220 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/TreeType.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/TreeType.java
@@ -1,14 +1,21 @@
-/**
- *
- */
-package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
-
-
-/**
- * @author ala
- *
- */
-public enum TreeType {
- Tree,
- Flat
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+/**
+ *
+ */
+package org.eclipse.babel.tapiji.translator.rbe.babel.bundle;
+
+
+/**
+ * @author ala
+ *
+ */
+public enum TreeType {
+ Tree,
+ Flat
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java
index 139c35ec..e966386c 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/model/analyze/ILevenshteinDistanceAnalyzer.java
@@ -1,7 +1,14 @@
-package org.eclipse.babel.tapiji.translator.rbe.model.analyze;
-
-public interface ILevenshteinDistanceAnalyzer {
-
- double analyse(Object value, Object pattern);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.model.analyze;
+
+public interface ILevenshteinDistanceAnalyzer {
+
+ double analyse(Object value, Object pattern);
+
+}
diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java
index ed8f035b..8620545a 100644
--- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java
+++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/ui/wizards/IResourceBundleWizard.java
@@ -1,9 +1,16 @@
-package org.eclipse.babel.tapiji.translator.rbe.ui.wizards;
-
-public interface IResourceBundleWizard {
-
- void setBundleId(String rbName);
-
- void setDefaultPath(String pathName);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipse.babel.tapiji.translator.rbe.ui.wizards;
+
+public interface IResourceBundleWizard {
+
+ void setBundleId(String rbName);
+
+ void setDefaultPath(String pathName);
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
index 42372b72..d70a0da9 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java
@@ -1,111 +1,118 @@
-package auditor;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.babel.tapiji.tools.core.builder.quickfix.CreateResourceBundle;
-import org.eclipse.babel.tapiji.tools.core.builder.quickfix.IncludeResource;
-import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor;
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.ui.IMarkerResolution;
-
-import quickfix.ExportToResourceBundleResolution;
-import quickfix.ReplaceResourceBundleDefReference;
-import quickfix.ReplaceResourceBundleReference;
-
-public class JSFResourceAuditor extends I18nResourceAuditor {
-
- public String[] getFileEndings () {
- return new String [] {"xhtml", "jsp"};
- }
-
- public void audit(IResource resource) {
- parse (resource);
- }
-
- private void parse (IResource resource) {
-
- }
-
- @Override
- public List<ILocation> getConstantStringLiterals() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public List<ILocation> getBrokenResourceReferences() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public List<ILocation> getBrokenBundleReferences() {
- return new ArrayList<ILocation>();
- }
-
- @Override
- public String getContextId() {
- return "jsf";
- }
-
- @Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
- int cause = marker.getAttribute("cause", -1);
-
- switch (cause) {
- case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
- resolutions.add(new ExportToResourceBundleResolution());
- break;
- case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
- String dataName = marker.getAttribute("bundleName", "");
- int dataStart = marker.getAttribute("bundleStart", 0);
- int dataEnd = marker.getAttribute("bundleEnd", 0);
-
- IProject project = marker.getResource().getProject();
- ResourceBundleManager manager = ResourceBundleManager.getManager(project);
-
- if (manager.getResourceBundle(dataName) != null) {
- String key = marker.getAttribute("key", "");
-
- resolutions.add(new CreateResourceBundleEntry(key, dataName));
- resolutions.add(new ReplaceResourceBundleReference(key, dataName));
- resolutions.add(new ReplaceResourceBundleDefReference(dataName, dataStart, dataEnd));
- } else {
- String bname = dataName;
-
- Set<IResource> bundleResources =
- ResourceBundleManager.getManager(marker.getResource().getProject()).getAllResourceBundleResources(bname);
-
- if (bundleResources != null && bundleResources.size() > 0)
- resolutions.add(new IncludeResource(bname, bundleResources));
- else
- resolutions.add(new CreateResourceBundle(bname, marker.getResource(), dataStart, dataEnd));
-
- resolutions.add(new ReplaceResourceBundleDefReference(bname, dataStart, dataEnd));
- }
-
- break;
- case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
- String bname = marker.getAttribute("key", "");
-
- Set<IResource> bundleResources =
- ResourceBundleManager.getManager(marker.getResource().getProject()).getAllResourceBundleResources(bname);
-
- if (bundleResources != null && bundleResources.size() > 0)
- resolutions.add(new IncludeResource(bname, bundleResources));
- else
- resolutions.add(new CreateResourceBundle(marker.getAttribute("key", ""), marker.getResource(),marker.getAttribute(IMarker.CHAR_START, 0), marker.getAttribute(IMarker.CHAR_END, 0)));
- resolutions.add(new ReplaceResourceBundleDefReference(marker.getAttribute("key", ""), marker.getAttribute(IMarker.CHAR_START, 0), marker.getAttribute(IMarker.CHAR_END, 0)));
- }
-
- return resolutions;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package auditor;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.babel.tapiji.tools.core.builder.quickfix.CreateResourceBundle;
+import org.eclipse.babel.tapiji.tools.core.builder.quickfix.IncludeResource;
+import org.eclipse.babel.tapiji.tools.core.extensions.I18nResourceAuditor;
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundleEntry;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.ui.IMarkerResolution;
+
+import quickfix.ExportToResourceBundleResolution;
+import quickfix.ReplaceResourceBundleDefReference;
+import quickfix.ReplaceResourceBundleReference;
+
+public class JSFResourceAuditor extends I18nResourceAuditor {
+
+ public String[] getFileEndings () {
+ return new String [] {"xhtml", "jsp"};
+ }
+
+ public void audit(IResource resource) {
+ parse (resource);
+ }
+
+ private void parse (IResource resource) {
+
+ }
+
+ @Override
+ public List<ILocation> getConstantStringLiterals() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public List<ILocation> getBrokenResourceReferences() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public List<ILocation> getBrokenBundleReferences() {
+ return new ArrayList<ILocation>();
+ }
+
+ @Override
+ public String getContextId() {
+ return "jsf";
+ }
+
+ @Override
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
+ List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
+ int cause = marker.getAttribute("cause", -1);
+
+ switch (cause) {
+ case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
+ resolutions.add(new ExportToResourceBundleResolution());
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_REFERENCE:
+ String dataName = marker.getAttribute("bundleName", "");
+ int dataStart = marker.getAttribute("bundleStart", 0);
+ int dataEnd = marker.getAttribute("bundleEnd", 0);
+
+ IProject project = marker.getResource().getProject();
+ ResourceBundleManager manager = ResourceBundleManager.getManager(project);
+
+ if (manager.getResourceBundle(dataName) != null) {
+ String key = marker.getAttribute("key", "");
+
+ resolutions.add(new CreateResourceBundleEntry(key, dataName));
+ resolutions.add(new ReplaceResourceBundleReference(key, dataName));
+ resolutions.add(new ReplaceResourceBundleDefReference(dataName, dataStart, dataEnd));
+ } else {
+ String bname = dataName;
+
+ Set<IResource> bundleResources =
+ ResourceBundleManager.getManager(marker.getResource().getProject()).getAllResourceBundleResources(bname);
+
+ if (bundleResources != null && bundleResources.size() > 0)
+ resolutions.add(new IncludeResource(bname, bundleResources));
+ else
+ resolutions.add(new CreateResourceBundle(bname, marker.getResource(), dataStart, dataEnd));
+
+ resolutions.add(new ReplaceResourceBundleDefReference(bname, dataStart, dataEnd));
+ }
+
+ break;
+ case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE:
+ String bname = marker.getAttribute("key", "");
+
+ Set<IResource> bundleResources =
+ ResourceBundleManager.getManager(marker.getResource().getProject()).getAllResourceBundleResources(bname);
+
+ if (bundleResources != null && bundleResources.size() > 0)
+ resolutions.add(new IncludeResource(bname, bundleResources));
+ else
+ resolutions.add(new CreateResourceBundle(marker.getAttribute("key", ""), marker.getResource(),marker.getAttribute(IMarker.CHAR_START, 0), marker.getAttribute(IMarker.CHAR_END, 0)));
+ resolutions.add(new ReplaceResourceBundleDefReference(marker.getAttribute("key", ""), marker.getAttribute(IMarker.CHAR_START, 0), marker.getAttribute(IMarker.CHAR_END, 0)));
+ }
+
+ return resolutions;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
index 16f1eca5..89533285 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java
@@ -1,418 +1,425 @@
-package auditor;
-
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IDOMContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-public class JSFResourceBundleDetector {
-
- public static List<IRegion> getNonELValueRegions (String elExpression) {
- List<IRegion> stringRegions = new ArrayList<IRegion>();
- int pos = -1;
-
- do {
- int start = pos + 1;
- int end = elExpression.indexOf("#{", start);
- end = end >= 0 ? end : elExpression.length();
-
- if (elExpression.substring(start, end).trim().length() > 0) {
- IRegion region = new Region (start, end-start);
- stringRegions.add(region);
- }
-
- if (elExpression.substring(end).startsWith("#{"))
- pos = elExpression.indexOf("}", end);
- else
- pos = end;
- } while (pos >= 0 && pos < elExpression.length());
-
- return stringRegions;
- }
-
- public static String getBundleVariableName (String elExpression) {
- String bundleVarName = null;
- String[] delimitors = new String [] { ".", "[" };
-
- int startPos = elExpression.indexOf(delimitors[0]);
-
- for (String del : delimitors) {
- if ((startPos > elExpression.indexOf(del) && elExpression.indexOf(del) >= 0) ||
- (startPos == -1 && elExpression.indexOf(del) >= 0))
- startPos = elExpression.indexOf(del);
- }
-
- if (startPos >= 0)
- bundleVarName = elExpression.substring(0, startPos);
-
- return bundleVarName;
- }
-
- public static String getResourceKey (String elExpression) {
- String key = null;
-
- if (elExpression.indexOf("[") == -1 || (elExpression.indexOf(".") < elExpression.indexOf("[") && elExpression.indexOf(".") >= 0)) {
- // Separation by dot
- key = elExpression.substring(elExpression.indexOf(".") + 1);
- } else {
- // Separation by '[' and ']'
- if (elExpression.indexOf("\"") >= 0 || elExpression.indexOf("'") >= 0) {
- int startPos = elExpression.indexOf("\"") >= 0 ? elExpression.indexOf("\"") : elExpression.indexOf("'");
- int endPos = elExpression.indexOf("\"", startPos + 1) >= 0 ? elExpression.indexOf("\"", startPos + 1) : elExpression.indexOf("'", startPos + 1);
- if (startPos < endPos) {
- key = elExpression.substring(startPos+1, endPos);
- }
- }
- }
-
- return key;
- }
-
- public static String resolveResourceBundleRefIdentifier (IDocument document, int startPos) {
- String result = null;
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- if (curNode instanceof Attr) {
- final Attr attr = (Attr) curNode;
- if (attr.getNodeName().toLowerCase().equals("basename")) {
- final Element owner = attr.getOwnerElement();
- if (isBundleElement (owner, context))
- result = attr.getValue();
- }
- } else if (curNode instanceof Element) {
- final Element elem = (Element) curNode;
- if (isBundleElement (elem, context))
- result = elem.getAttribute("basename");
- }
- }
-
- return result;
- }
-
- public static String resolveResourceBundleId(IDocument document,
- String varName) {
- String content = document.get();
- String bundleId = "";
- int offset = 0;
-
- while (content.indexOf("\"" + varName + "\"", offset+1) >= 0
- || content.indexOf("'" + varName + "'", offset+1) >= 0) {
- offset = content.indexOf("\"" + varName + "\"") >= 0 ? content
- .indexOf("\"" + varName + "\"") : content.indexOf("'"
- + varName + "'");
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- Attr attr = null;
- if (curNode instanceof Attr) {
- attr = (Attr) curNode;
- if (!attr.getNodeName().toLowerCase().equals("var"))
- continue;
- }
-
- // Retrieve parent node
- Element parentElement = (Element) attr.getOwnerElement();
-
- if (!isBundleElement(parentElement, context))
- continue;
-
- bundleId = parentElement.getAttribute("basename");
- break;
- }
- }
-
- return bundleId;
- }
-
- public static boolean isBundleElement (Element element, IStructuredDocumentContext context) {
- String bName = element.getTagName().substring(element.getTagName().indexOf(":")+1);
-
- if (bName.equals("loadBundle")) {
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
- if (tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/core")) {
- return true;
- }
- }
-
- return false;
- }
-
- public static boolean isJSFElement (Element element, IStructuredDocumentContext context) {
- try {
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
- if (tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/core") ||
- tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/html")) {
- return true;
- }
- } catch (Exception e) {}
- return false;
- }
-
- public static IRegion getBasenameRegion(IDocument document, int startPos) {
- IRegion result = null;
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- if (curNode instanceof Element) {
- final Element elem = (Element) curNode;
- if (isBundleElement (elem, context)) {
- Attr na = elem.getAttributeNode("basename");
-
- if (na != null) {
- int attrStart = document.get().indexOf("basename", startPos);
- result = new Region (document.get().indexOf(na.getValue(), attrStart), na.getValue().length());
- }
- }
- }
- }
-
- return result;
- }
-
- public static IRegion getElementAttrValueRegion(IDocument document, String attribute, int startPos) {
- IRegion result = null;
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- Node curNode = domResolver.getNode();
- if (curNode instanceof Attr)
- curNode = ((Attr) curNode).getOwnerElement();
-
- // node must be an XML attribute
- if (curNode instanceof Element) {
- final Element elem = (Element) curNode;
- Attr na = elem.getAttributeNode(attribute);
-
- if (na != null && isJSFElement(elem, context)) {
- int attrStart = document.get().indexOf(attribute, startPos);
- result = new Region (document.get().indexOf(na.getValue().trim(), attrStart), na.getValue().trim().length());
- }
- }
- }
-
- return result;
- }
-
- public static IRegion resolveResourceBundleRefPos(IDocument document,
- String varName) {
- String content = document.get();
- IRegion region = null;
- int offset = 0;
-
- while (content.indexOf("\"" + varName + "\"", offset+1) >= 0
- || content.indexOf("'" + varName + "'", offset+1) >= 0) {
- offset = content.indexOf("\"" + varName + "\"") >= 0 ? content
- .indexOf("\"" + varName + "\"") : content.indexOf("'"
- + varName + "'");
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- Attr attr = null;
- if (curNode instanceof Attr) {
- attr = (Attr) curNode;
- if (!attr.getNodeName().toLowerCase().equals("var"))
- continue;
- }
-
- // Retrieve parent node
- Element parentElement = (Element) attr.getOwnerElement();
-
- if (!isBundleElement(parentElement, context))
- continue;
-
- String bundleId = parentElement.getAttribute("basename");
-
- if (bundleId != null && bundleId.trim().length() > 0) {
-
- while (region == null) {
- int basename = content.indexOf("basename", offset);
- int value = content.indexOf(bundleId, content.indexOf("=", basename));
- if (value > basename) {
- region = new Region (value, bundleId.length());
- }
- }
-
- }
- break;
- }
- }
-
- return region;
- }
-
- public static String resolveResourceBundleVariable(IDocument document,
- String selectedResourceBundle) {
- String content = document.get();
- String variableName = null;
- int offset = 0;
-
- while (content.indexOf("\"" + selectedResourceBundle + "\"", offset+1) >= 0
- || content.indexOf("'" + selectedResourceBundle + "'", offset+1) >= 0) {
- offset = content.indexOf("\"" + selectedResourceBundle + "\"") >= 0 ? content
- .indexOf("\"" + selectedResourceBundle + "\"") : content.indexOf("'"
- + selectedResourceBundle + "'");
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- // node must be an XML attribute
- Attr attr = null;
- if (curNode instanceof Attr) {
- attr = (Attr) curNode;
- if (!attr.getNodeName().toLowerCase().equals("basename"))
- continue;
- }
-
- // Retrieve parent node
- Element parentElement = (Element) attr.getOwnerElement();
-
- if (!isBundleElement(parentElement, context))
- continue;
-
- variableName = parentElement.getAttribute("var");
- break;
- }
- }
-
- return variableName;
- }
-
- public static String resolveNewVariableName (IDocument document, String selectedResourceBundle) {
- String variableName = "";
- int i = 0;
- variableName = selectedResourceBundle.replace(".", "");
- while (resolveResourceBundleId(document, variableName).trim().length() > 0 ) {
- variableName = selectedResourceBundle + (i++);
- }
- return variableName;
- }
-
- public static void createResourceBundleRef(IDocument document,
- String selectedResourceBundle,
- String variableName) {
- String content = document.get();
- int headInsertPos = -1;
- int offset = 0;
-
- while (content.indexOf("head", offset+1) >= 0) {
- offset = content.indexOf("head", offset+1);
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- if (!(curNode instanceof Element)) {
- continue;
- }
-
- // Retrieve parent node
- Element parentElement = (Element) curNode;
-
- if (parentElement.getNodeName().equalsIgnoreCase("head")) {
- do {
- headInsertPos = content.indexOf("head", offset+5);
-
- final IStructuredDocumentContext contextHeadClose = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, offset);
- final IDOMContextResolver domResolverHeadClose = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(contextHeadClose);
- if (domResolverHeadClose.getNode() instanceof Element && domResolverHeadClose.getNode().getNodeName().equalsIgnoreCase("head")) {
- headInsertPos = content.substring(0, headInsertPos).lastIndexOf("<");
- break;
- }
- } while (headInsertPos >= 0);
-
- if (headInsertPos < 0) {
- headInsertPos = content.indexOf(">", offset) + 1;
- }
-
- break;
- }
- }
- }
-
- // resolve the taglib
- try {
- int taglibPos = content.lastIndexOf("taglib");
- if (taglibPos > 0) {
- final IStructuredDocumentContext taglibContext = IStructuredDocumentContextFactory.INSTANCE
- .getContext(document, taglibPos);
- taglibPos = content.indexOf("%>", taglibPos);
- if (taglibPos > 0) {
- String decl = createLoadBundleDeclaration (document, taglibContext, variableName, selectedResourceBundle);
- if (headInsertPos > taglibPos)
- document.replace(headInsertPos, 0, decl);
- else
- document.replace(taglibPos, 0, decl);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- private static String createLoadBundleDeclaration(IDocument document,
- IStructuredDocumentContext context, String variableName, String selectedResourceBundle) {
- String bundleDecl = "";
-
- // Retrieve jsf core namespace prefix
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
- String bundlePrefix = tlResolver.getTagPrefixForURI("http://java.sun.com/jsf/core");
-
- MessageFormat tlFormatter = new MessageFormat ("<{0}:loadBundle var=\"{1}\" basename=\"{2}\" />\r\n");
- bundleDecl = tlFormatter.format(new String[] {bundlePrefix, variableName, selectedResourceBundle});
-
- return bundleDecl;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package auditor;
+
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IDOMContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+public class JSFResourceBundleDetector {
+
+ public static List<IRegion> getNonELValueRegions (String elExpression) {
+ List<IRegion> stringRegions = new ArrayList<IRegion>();
+ int pos = -1;
+
+ do {
+ int start = pos + 1;
+ int end = elExpression.indexOf("#{", start);
+ end = end >= 0 ? end : elExpression.length();
+
+ if (elExpression.substring(start, end).trim().length() > 0) {
+ IRegion region = new Region (start, end-start);
+ stringRegions.add(region);
+ }
+
+ if (elExpression.substring(end).startsWith("#{"))
+ pos = elExpression.indexOf("}", end);
+ else
+ pos = end;
+ } while (pos >= 0 && pos < elExpression.length());
+
+ return stringRegions;
+ }
+
+ public static String getBundleVariableName (String elExpression) {
+ String bundleVarName = null;
+ String[] delimitors = new String [] { ".", "[" };
+
+ int startPos = elExpression.indexOf(delimitors[0]);
+
+ for (String del : delimitors) {
+ if ((startPos > elExpression.indexOf(del) && elExpression.indexOf(del) >= 0) ||
+ (startPos == -1 && elExpression.indexOf(del) >= 0))
+ startPos = elExpression.indexOf(del);
+ }
+
+ if (startPos >= 0)
+ bundleVarName = elExpression.substring(0, startPos);
+
+ return bundleVarName;
+ }
+
+ public static String getResourceKey (String elExpression) {
+ String key = null;
+
+ if (elExpression.indexOf("[") == -1 || (elExpression.indexOf(".") < elExpression.indexOf("[") && elExpression.indexOf(".") >= 0)) {
+ // Separation by dot
+ key = elExpression.substring(elExpression.indexOf(".") + 1);
+ } else {
+ // Separation by '[' and ']'
+ if (elExpression.indexOf("\"") >= 0 || elExpression.indexOf("'") >= 0) {
+ int startPos = elExpression.indexOf("\"") >= 0 ? elExpression.indexOf("\"") : elExpression.indexOf("'");
+ int endPos = elExpression.indexOf("\"", startPos + 1) >= 0 ? elExpression.indexOf("\"", startPos + 1) : elExpression.indexOf("'", startPos + 1);
+ if (startPos < endPos) {
+ key = elExpression.substring(startPos+1, endPos);
+ }
+ }
+ }
+
+ return key;
+ }
+
+ public static String resolveResourceBundleRefIdentifier (IDocument document, int startPos) {
+ String result = null;
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ if (curNode instanceof Attr) {
+ final Attr attr = (Attr) curNode;
+ if (attr.getNodeName().toLowerCase().equals("basename")) {
+ final Element owner = attr.getOwnerElement();
+ if (isBundleElement (owner, context))
+ result = attr.getValue();
+ }
+ } else if (curNode instanceof Element) {
+ final Element elem = (Element) curNode;
+ if (isBundleElement (elem, context))
+ result = elem.getAttribute("basename");
+ }
+ }
+
+ return result;
+ }
+
+ public static String resolveResourceBundleId(IDocument document,
+ String varName) {
+ String content = document.get();
+ String bundleId = "";
+ int offset = 0;
+
+ while (content.indexOf("\"" + varName + "\"", offset+1) >= 0
+ || content.indexOf("'" + varName + "'", offset+1) >= 0) {
+ offset = content.indexOf("\"" + varName + "\"") >= 0 ? content
+ .indexOf("\"" + varName + "\"") : content.indexOf("'"
+ + varName + "'");
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ Attr attr = null;
+ if (curNode instanceof Attr) {
+ attr = (Attr) curNode;
+ if (!attr.getNodeName().toLowerCase().equals("var"))
+ continue;
+ }
+
+ // Retrieve parent node
+ Element parentElement = (Element) attr.getOwnerElement();
+
+ if (!isBundleElement(parentElement, context))
+ continue;
+
+ bundleId = parentElement.getAttribute("basename");
+ break;
+ }
+ }
+
+ return bundleId;
+ }
+
+ public static boolean isBundleElement (Element element, IStructuredDocumentContext context) {
+ String bName = element.getTagName().substring(element.getTagName().indexOf(":")+1);
+
+ if (bName.equals("loadBundle")) {
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
+ if (tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/core")) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public static boolean isJSFElement (Element element, IStructuredDocumentContext context) {
+ try {
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
+ if (tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/core") ||
+ tlResolver.getTagURIForNodeName(element).trim().equalsIgnoreCase("http://java.sun.com/jsf/html")) {
+ return true;
+ }
+ } catch (Exception e) {}
+ return false;
+ }
+
+ public static IRegion getBasenameRegion(IDocument document, int startPos) {
+ IRegion result = null;
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ if (curNode instanceof Element) {
+ final Element elem = (Element) curNode;
+ if (isBundleElement (elem, context)) {
+ Attr na = elem.getAttributeNode("basename");
+
+ if (na != null) {
+ int attrStart = document.get().indexOf("basename", startPos);
+ result = new Region (document.get().indexOf(na.getValue(), attrStart), na.getValue().length());
+ }
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static IRegion getElementAttrValueRegion(IDocument document, String attribute, int startPos) {
+ IRegion result = null;
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE.getContext(document, startPos);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ Node curNode = domResolver.getNode();
+ if (curNode instanceof Attr)
+ curNode = ((Attr) curNode).getOwnerElement();
+
+ // node must be an XML attribute
+ if (curNode instanceof Element) {
+ final Element elem = (Element) curNode;
+ Attr na = elem.getAttributeNode(attribute);
+
+ if (na != null && isJSFElement(elem, context)) {
+ int attrStart = document.get().indexOf(attribute, startPos);
+ result = new Region (document.get().indexOf(na.getValue().trim(), attrStart), na.getValue().trim().length());
+ }
+ }
+ }
+
+ return result;
+ }
+
+ public static IRegion resolveResourceBundleRefPos(IDocument document,
+ String varName) {
+ String content = document.get();
+ IRegion region = null;
+ int offset = 0;
+
+ while (content.indexOf("\"" + varName + "\"", offset+1) >= 0
+ || content.indexOf("'" + varName + "'", offset+1) >= 0) {
+ offset = content.indexOf("\"" + varName + "\"") >= 0 ? content
+ .indexOf("\"" + varName + "\"") : content.indexOf("'"
+ + varName + "'");
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ Attr attr = null;
+ if (curNode instanceof Attr) {
+ attr = (Attr) curNode;
+ if (!attr.getNodeName().toLowerCase().equals("var"))
+ continue;
+ }
+
+ // Retrieve parent node
+ Element parentElement = (Element) attr.getOwnerElement();
+
+ if (!isBundleElement(parentElement, context))
+ continue;
+
+ String bundleId = parentElement.getAttribute("basename");
+
+ if (bundleId != null && bundleId.trim().length() > 0) {
+
+ while (region == null) {
+ int basename = content.indexOf("basename", offset);
+ int value = content.indexOf(bundleId, content.indexOf("=", basename));
+ if (value > basename) {
+ region = new Region (value, bundleId.length());
+ }
+ }
+
+ }
+ break;
+ }
+ }
+
+ return region;
+ }
+
+ public static String resolveResourceBundleVariable(IDocument document,
+ String selectedResourceBundle) {
+ String content = document.get();
+ String variableName = null;
+ int offset = 0;
+
+ while (content.indexOf("\"" + selectedResourceBundle + "\"", offset+1) >= 0
+ || content.indexOf("'" + selectedResourceBundle + "'", offset+1) >= 0) {
+ offset = content.indexOf("\"" + selectedResourceBundle + "\"") >= 0 ? content
+ .indexOf("\"" + selectedResourceBundle + "\"") : content.indexOf("'"
+ + selectedResourceBundle + "'");
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ // node must be an XML attribute
+ Attr attr = null;
+ if (curNode instanceof Attr) {
+ attr = (Attr) curNode;
+ if (!attr.getNodeName().toLowerCase().equals("basename"))
+ continue;
+ }
+
+ // Retrieve parent node
+ Element parentElement = (Element) attr.getOwnerElement();
+
+ if (!isBundleElement(parentElement, context))
+ continue;
+
+ variableName = parentElement.getAttribute("var");
+ break;
+ }
+ }
+
+ return variableName;
+ }
+
+ public static String resolveNewVariableName (IDocument document, String selectedResourceBundle) {
+ String variableName = "";
+ int i = 0;
+ variableName = selectedResourceBundle.replace(".", "");
+ while (resolveResourceBundleId(document, variableName).trim().length() > 0 ) {
+ variableName = selectedResourceBundle + (i++);
+ }
+ return variableName;
+ }
+
+ public static void createResourceBundleRef(IDocument document,
+ String selectedResourceBundle,
+ String variableName) {
+ String content = document.get();
+ int headInsertPos = -1;
+ int offset = 0;
+
+ while (content.indexOf("head", offset+1) >= 0) {
+ offset = content.indexOf("head", offset+1);
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ if (!(curNode instanceof Element)) {
+ continue;
+ }
+
+ // Retrieve parent node
+ Element parentElement = (Element) curNode;
+
+ if (parentElement.getNodeName().equalsIgnoreCase("head")) {
+ do {
+ headInsertPos = content.indexOf("head", offset+5);
+
+ final IStructuredDocumentContext contextHeadClose = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, offset);
+ final IDOMContextResolver domResolverHeadClose = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(contextHeadClose);
+ if (domResolverHeadClose.getNode() instanceof Element && domResolverHeadClose.getNode().getNodeName().equalsIgnoreCase("head")) {
+ headInsertPos = content.substring(0, headInsertPos).lastIndexOf("<");
+ break;
+ }
+ } while (headInsertPos >= 0);
+
+ if (headInsertPos < 0) {
+ headInsertPos = content.indexOf(">", offset) + 1;
+ }
+
+ break;
+ }
+ }
+ }
+
+ // resolve the taglib
+ try {
+ int taglibPos = content.lastIndexOf("taglib");
+ if (taglibPos > 0) {
+ final IStructuredDocumentContext taglibContext = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(document, taglibPos);
+ taglibPos = content.indexOf("%>", taglibPos);
+ if (taglibPos > 0) {
+ String decl = createLoadBundleDeclaration (document, taglibContext, variableName, selectedResourceBundle);
+ if (headInsertPos > taglibPos)
+ document.replace(headInsertPos, 0, decl);
+ else
+ document.replace(taglibPos, 0, decl);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ private static String createLoadBundleDeclaration(IDocument document,
+ IStructuredDocumentContext context, String variableName, String selectedResourceBundle) {
+ String bundleDecl = "";
+
+ // Retrieve jsf core namespace prefix
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTaglibContextResolver(context);
+ String bundlePrefix = tlResolver.getTagPrefixForURI("http://java.sun.com/jsf/core");
+
+ MessageFormat tlFormatter = new MessageFormat ("<{0}:loadBundle var=\"{1}\" basename=\"{2}\" />\r\n");
+ bundleDecl = tlFormatter.format(new String[] {bundlePrefix, variableName, selectedResourceBundle});
+
+ return bundleDecl;
+ }
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
index ed99c0f7..63918ce1 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java
@@ -1,53 +1,60 @@
-package auditor.model;
-
-import java.io.Serializable;
-
-import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
-import org.eclipse.core.resources.IFile;
-
-
-public class SLLocation implements Serializable, ILocation {
-
- private static final long serialVersionUID = 1L;
- private IFile file = null;
- private int startPos = -1;
- private int endPos = -1;
- private String literal;
- private Serializable data;
-
- public SLLocation(IFile file, int startPos, int endPos, String literal) {
- super();
- this.file = file;
- this.startPos = startPos;
- this.endPos = endPos;
- this.literal = literal;
- }
- public IFile getFile() {
- return file;
- }
- public void setFile(IFile file) {
- this.file = file;
- }
- public int getStartPos() {
- return startPos;
- }
- public void setStartPos(int startPos) {
- this.startPos = startPos;
- }
- public int getEndPos() {
- return endPos;
- }
- public void setEndPos(int endPos) {
- this.endPos = endPos;
- }
- public String getLiteral() {
- return literal;
- }
- public Serializable getData () {
- return data;
- }
- public void setData (Serializable data) {
- this.data = data;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package auditor.model;
+
+import java.io.Serializable;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.ILocation;
+import org.eclipse.core.resources.IFile;
+
+
+public class SLLocation implements Serializable, ILocation {
+
+ private static final long serialVersionUID = 1L;
+ private IFile file = null;
+ private int startPos = -1;
+ private int endPos = -1;
+ private String literal;
+ private Serializable data;
+
+ public SLLocation(IFile file, int startPos, int endPos, String literal) {
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.literal = literal;
+ }
+ public IFile getFile() {
+ return file;
+ }
+ public void setFile(IFile file) {
+ this.file = file;
+ }
+ public int getStartPos() {
+ return startPos;
+ }
+ public void setStartPos(int startPos) {
+ this.startPos = startPos;
+ }
+ public int getEndPos() {
+ return endPos;
+ }
+ public void setEndPos(int endPos) {
+ this.endPos = endPos;
+ }
+ public String getLiteral() {
+ return literal;
+ }
+ public Serializable getData () {
+ return data;
+ }
+ public void setData (Serializable data) {
+ this.data = data;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
index 7aeed754..58f869d6 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
@@ -1,119 +1,126 @@
-package quickfix;
-
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-
-import auditor.JSFResourceBundleDetector;
-
-public class ExportToResourceBundleResolution implements IMarkerResolution2 {
-
- public ExportToResourceBundleResolution() {
- }
-
- @Override
- public String getDescription() {
- return "Export constant string literal to a resource bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Export to Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey("");
- config.setPreselectedMessage("");
- config.setPreselectedBundle((startPos < document.getLength() && endPos > 1) ? document
- .get(startPos, endPos) : "");
- config.setPreselectedLocale("");
- config.setProjectName(resource.getProject().getName());
-
- dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- /** Check for an existing resource bundle reference **/
- String bundleVar = JSFResourceBundleDetector
- .resolveResourceBundleVariable(document,
- dialog.getSelectedResourceBundle());
-
- boolean requiresNewReference = false;
- if (bundleVar == null) {
- requiresNewReference = true;
- bundleVar = JSFResourceBundleDetector.resolveNewVariableName(
- document, dialog.getSelectedResourceBundle());
- }
-
- // insert resource reference
- String key = dialog.getSelectedKey();
-
- if (key.indexOf(".") >= 0) {
- int quoteDblIdx = document.get().substring(0, startPos)
- .lastIndexOf("\"");
- int quoteSingleIdx = document.get().substring(0, startPos)
- .lastIndexOf("'");
- String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
-
- document.replace(startPos, endPos, "#{" + bundleVar + "["
- + quoteSign + key + quoteSign + "]}");
- } else {
- document.replace(startPos, endPos, "#{" + bundleVar + "." + key
- + "}");
- }
-
- if (requiresNewReference) {
- JSFResourceBundleDetector.createResourceBundleRef(document,
- dialog.getSelectedResourceBundle(), bundleVar);
- }
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+import auditor.JSFResourceBundleDetector;
+
+public class ExportToResourceBundleResolution implements IMarkerResolution2 {
+
+ public ExportToResourceBundleResolution() {
+ }
+
+ @Override
+ public String getDescription() {
+ return "Export constant string literal to a resource bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Export to Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey("");
+ config.setPreselectedMessage("");
+ config.setPreselectedBundle((startPos < document.getLength() && endPos > 1) ? document
+ .get(startPos, endPos) : "");
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ /** Check for an existing resource bundle reference **/
+ String bundleVar = JSFResourceBundleDetector
+ .resolveResourceBundleVariable(document,
+ dialog.getSelectedResourceBundle());
+
+ boolean requiresNewReference = false;
+ if (bundleVar == null) {
+ requiresNewReference = true;
+ bundleVar = JSFResourceBundleDetector.resolveNewVariableName(
+ document, dialog.getSelectedResourceBundle());
+ }
+
+ // insert resource reference
+ String key = dialog.getSelectedKey();
+
+ if (key.indexOf(".") >= 0) {
+ int quoteDblIdx = document.get().substring(0, startPos)
+ .lastIndexOf("\"");
+ int quoteSingleIdx = document.get().substring(0, startPos)
+ .lastIndexOf("'");
+ String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
+
+ document.replace(startPos, endPos, "#{" + bundleVar + "["
+ + quoteSign + key + quoteSign + "]}");
+ } else {
+ document.replace(startPos, endPos, "#{" + bundleVar + "." + key
+ + "}");
+ }
+
+ if (requiresNewReference) {
+ JSFResourceBundleDetector.createResourceBundleRef(document,
+ dialog.getSelectedResourceBundle(), bundleVar);
+ }
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
index 7618d69d..95b21cfa 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java
@@ -1,16 +1,23 @@
-package quickfix;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolutionGenerator;
-
-public class JSFViolationResolutionGenerator implements
- IMarkerResolutionGenerator {
-
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package quickfix;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.ui.IMarkerResolution;
+import org.eclipse.ui.IMarkerResolutionGenerator;
+
+public class JSFViolationResolutionGenerator implements
+ IMarkerResolutionGenerator {
+
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
index 3383e5c7..8d34a36c 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java
@@ -1,83 +1,90 @@
-package quickfix;
-
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-
-
-public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
-
- private String key;
- private int start;
- private int end;
-
- public ReplaceResourceBundleDefReference(String key, int start, int end) {
- this.key = key;
- this.start = start;
- this.end = end;
- }
-
- @Override
- public String getDescription() {
- return "Replaces the non-existing Resource-Bundle reference '"
- + key
- + "' with a reference to an already existing Resource-Bundle.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Select an alternative Resource-Bundle";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = start;
- int endPos = end-start;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(Display.getDefault().getActiveShell(),
- resource.getProject());
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- key = dialog.getSelectedBundleId();
-
- document.replace(startPos, endPos, key);
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+
+public class ReplaceResourceBundleDefReference implements IMarkerResolution2 {
+
+ private String key;
+ private int start;
+ private int end;
+
+ public ReplaceResourceBundleDefReference(String key, int start, int end) {
+ this.key = key;
+ this.start = start;
+ this.end = end;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Replaces the non-existing Resource-Bundle reference '"
+ + key
+ + "' with a reference to an already existing Resource-Bundle.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Select an alternative Resource-Bundle";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = start;
+ int endPos = end-start;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog(Display.getDefault().getActiveShell(),
+ resource.getProject());
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ key = dialog.getSelectedBundleId();
+
+ document.replace(startPos, endPos, key);
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
index 6ab75f0b..cb15b9f9 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java
@@ -1,105 +1,112 @@
-package quickfix;
-
-import java.util.Locale;
-
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IMarkerResolution2;
-
-import auditor.JSFResourceBundleDetector;
-
-public class ReplaceResourceBundleReference implements IMarkerResolution2 {
-
- private String key;
- private String bundleId;
-
- public ReplaceResourceBundleReference(String key, String bundleId) {
- this.key = key;
- this.bundleId = bundleId;
- }
-
- @Override
- public String getDescription() {
- return "Replaces the non-existing Resource-Bundle key '"
- + key
- + "' with a reference to an already existing localized string literal.";
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Select alternative Resource-Bundle entry";
- }
-
- @Override
- public void run(IMarker marker) {
- int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
- int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
- IResource resource = marker.getResource();
-
- ITextFileBufferManager bufferManager = FileBuffers
- .getTextFileBufferManager();
- IPath path = resource.getRawLocation();
- try {
- bufferManager.connect(path, null);
- ITextFileBuffer textFileBuffer = bufferManager
- .getTextFileBuffer(path);
- IDocument document = textFileBuffer.getDocument();
-
- ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
- Display.getDefault().getActiveShell());
-
- dialog.setProjectName(resource.getProject().getName());
- dialog.setBundleName(bundleId);
-
- if (dialog.open() != InputDialog.OK)
- return;
-
- String key = dialog.getSelectedResource();
- Locale locale = dialog.getSelectedLocale();
-
- String jsfBundleVar = JSFResourceBundleDetector
- .getBundleVariableName(document.get().substring(startPos,
- startPos + endPos));
-
- if (key.indexOf(".") >= 0) {
- int quoteDblIdx = document.get().substring(0, startPos)
- .lastIndexOf("\"");
- int quoteSingleIdx = document.get().substring(0, startPos)
- .lastIndexOf("'");
- String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
-
- document.replace(startPos, endPos, jsfBundleVar + "["
- + quoteSign + key + quoteSign + "]");
- } else {
- document.replace(startPos, endPos, jsfBundleVar + "." + key);
- }
-
- textFileBuffer.commit(null, false);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bufferManager.disconnect(path, null);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package quickfix;
+
+import java.util.Locale;
+
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IMarkerResolution2;
+
+import auditor.JSFResourceBundleDetector;
+
+public class ReplaceResourceBundleReference implements IMarkerResolution2 {
+
+ private String key;
+ private String bundleId;
+
+ public ReplaceResourceBundleReference(String key, String bundleId) {
+ this.key = key;
+ this.bundleId = bundleId;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Replaces the non-existing Resource-Bundle key '"
+ + key
+ + "' with a reference to an already existing localized string literal.";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Select alternative Resource-Bundle entry";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ int startPos = marker.getAttribute(IMarker.CHAR_START, 0);
+ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos;
+ IResource resource = marker.getResource();
+
+ ITextFileBufferManager bufferManager = FileBuffers
+ .getTextFileBufferManager();
+ IPath path = resource.getRawLocation();
+ try {
+ bufferManager.connect(path, null);
+ ITextFileBuffer textFileBuffer = bufferManager
+ .getTextFileBuffer(path);
+ IDocument document = textFileBuffer.getDocument();
+
+ ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog(
+ Display.getDefault().getActiveShell());
+
+ dialog.setProjectName(resource.getProject().getName());
+ dialog.setBundleName(bundleId);
+
+ if (dialog.open() != InputDialog.OK)
+ return;
+
+ String key = dialog.getSelectedResource();
+ Locale locale = dialog.getSelectedLocale();
+
+ String jsfBundleVar = JSFResourceBundleDetector
+ .getBundleVariableName(document.get().substring(startPos,
+ startPos + endPos));
+
+ if (key.indexOf(".") >= 0) {
+ int quoteDblIdx = document.get().substring(0, startPos)
+ .lastIndexOf("\"");
+ int quoteSingleIdx = document.get().substring(0, startPos)
+ .lastIndexOf("'");
+ String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'";
+
+ document.replace(startPos, endPos, jsfBundleVar + "["
+ + quoteSign + key + quoteSign + "]");
+ } else {
+ document.replace(startPos, endPos, jsfBundleVar + "." + key);
+ }
+
+ textFileBuffer.commit(null, false);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ bufferManager.disconnect(path, null);
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
index abce30a4..9da1e63b 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java
@@ -1,63 +1,70 @@
-package ui;
-
-import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.internal.ITextRegionContextResolver;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
-import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts;
-
-import util.ELUtils;
-import auditor.JSFResourceBundleDetector;
-
-/**
- * This class creates hovers for ISymbols in an el expression that have a
- * detailedDescription.
- */
-public class JSFELMessageHover implements ITextHover {
-
- private String expressionValue = "";
- private IProject project = null;
-
- public final String getHoverInfo(final ITextViewer textViewer,
- final IRegion hoverRegion) {
- String bundleName = JSFResourceBundleDetector.resolveResourceBundleId(textViewer.getDocument(),
- JSFResourceBundleDetector.getBundleVariableName(expressionValue));
- String resourceKey = JSFResourceBundleDetector.getResourceKey(expressionValue);
-
- return ELUtils.getResource (project, bundleName, resourceKey);
- }
-
- public final IRegion getHoverRegion(final ITextViewer textViewer,
- final int documentPosition) {
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(textViewer, documentPosition);
-
- IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
-
- project = workspaceResolver.getProject();
-
- if (project != null) {
- if (!InternationalizationNature.hasNature(project))
- return null;
- } else
- return null;
-
- final ITextRegionContextResolver symbolResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTextRegionResolver(context);
-
- if (!symbolResolver.getRegionType().equals(DOMJSPRegionContexts.JSP_VBL_CONTENT))
- return null;
- expressionValue = symbolResolver.getRegionText();
-
- return new Region (symbolResolver.getStartOffset(), symbolResolver.getLength());
-
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package ui;
+
+import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextHover;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.internal.ITextRegionContextResolver;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
+import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts;
+
+import util.ELUtils;
+import auditor.JSFResourceBundleDetector;
+
+/**
+ * This class creates hovers for ISymbols in an el expression that have a
+ * detailedDescription.
+ */
+public class JSFELMessageHover implements ITextHover {
+
+ private String expressionValue = "";
+ private IProject project = null;
+
+ public final String getHoverInfo(final ITextViewer textViewer,
+ final IRegion hoverRegion) {
+ String bundleName = JSFResourceBundleDetector.resolveResourceBundleId(textViewer.getDocument(),
+ JSFResourceBundleDetector.getBundleVariableName(expressionValue));
+ String resourceKey = JSFResourceBundleDetector.getResourceKey(expressionValue);
+
+ return ELUtils.getResource (project, bundleName, resourceKey);
+ }
+
+ public final IRegion getHoverRegion(final ITextViewer textViewer,
+ final int documentPosition) {
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(textViewer, documentPosition);
+
+ IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getWorkspaceContextResolver(context);
+
+ project = workspaceResolver.getProject();
+
+ if (project != null) {
+ if (!InternationalizationNature.hasNature(project))
+ return null;
+ } else
+ return null;
+
+ final ITextRegionContextResolver symbolResolver = IStructuredDocumentContextResolverFactory.INSTANCE.getTextRegionResolver(context);
+
+ if (!symbolResolver.getRegionType().equals(DOMJSPRegionContexts.JSP_VBL_CONTENT))
+ return null;
+ expressionValue = symbolResolver.getRegionText();
+
+ return new Region (symbolResolver.getStartOffset(), symbolResolver.getLength());
+
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java
index def18aa3..6406701d 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java
@@ -1,149 +1,156 @@
-package ui.autocompletion;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IDOMContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.internal.ITextRegionContextResolver;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Node;
-
-
-public class BundleNameProposal implements IContentAssistProcessor {
-
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
- List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(viewer, offset);
-
- IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
-
- IProject project = workspaceResolver.getProject();
- IResource resource = workspaceResolver.getResource();
-
- if (project != null) {
- if (!InternationalizationNature.hasNature(project))
- return proposals.toArray(new ICompletionProposal[proposals
- .size()]);
- } else
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
-
- addBundleProposals(proposals, context, offset, viewer.getDocument(),
- resource);
-
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
- private void addBundleProposals(List<ICompletionProposal> proposals,
- final IStructuredDocumentContext context,
- int startPos,
- IDocument document,
- IResource resource) {
- final ITextRegionContextResolver resolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getTextRegionResolver(context);
-
- if (resolver != null) {
- final String regionType = resolver.getRegionType();
- startPos = resolver.getStartOffset()+1;
-
- if (regionType != null
- && regionType
- .equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) {
-
- final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getTaglibContextResolver(context);
-
- if (tlResolver != null) {
- Attr attr = getAttribute(context);
- String startString = attr.getValue();
-
- int length = startString.length();
-
- if (attr != null) {
- Node tagElement = attr.getOwnerElement();
- if (tagElement == null)
- return;
-
- String nodeName = tagElement.getNodeName();
- if (nodeName.substring(nodeName.indexOf(":")+1).toLowerCase().equals("loadbundle")) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject());
- for (String id : manager.getResourceBundleIdentifiers()) {
- if (id.startsWith(startString) && id.length() != startString.length()) {
- proposals.add(new ui.autocompletion.MessageCompletionProposal(
- startPos, length, id, true));
- }
- }
- }
- }
- }
- }
- }
- }
-
- private Attr getAttribute(IStructuredDocumentContext context) {
- final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getDOMContextResolver(context);
-
- if (domResolver != null) {
- final Node curNode = domResolver.getNode();
-
- if (curNode instanceof Attr) {
- return (Attr) curNode;
- }
- }
- return null;
-
- }
-
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer,
- int offset) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package ui.autocompletion;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.jface.text.contentassist.IContextInformationValidator;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IDOMContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.ITaglibContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.internal.ITextRegionContextResolver;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
+import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Node;
+
+
+public class BundleNameProposal implements IContentAssistProcessor {
+
+ @Override
+ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
+ int offset) {
+ List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(viewer, offset);
+
+ IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getWorkspaceContextResolver(context);
+
+ IProject project = workspaceResolver.getProject();
+ IResource resource = workspaceResolver.getResource();
+
+ if (project != null) {
+ if (!InternationalizationNature.hasNature(project))
+ return proposals.toArray(new ICompletionProposal[proposals
+ .size()]);
+ } else
+ return proposals.toArray(new ICompletionProposal[proposals.size()]);
+
+ addBundleProposals(proposals, context, offset, viewer.getDocument(),
+ resource);
+
+ return proposals.toArray(new ICompletionProposal[proposals.size()]);
+ }
+
+ private void addBundleProposals(List<ICompletionProposal> proposals,
+ final IStructuredDocumentContext context,
+ int startPos,
+ IDocument document,
+ IResource resource) {
+ final ITextRegionContextResolver resolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTextRegionResolver(context);
+
+ if (resolver != null) {
+ final String regionType = resolver.getRegionType();
+ startPos = resolver.getStartOffset()+1;
+
+ if (regionType != null
+ && regionType
+ .equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) {
+
+ final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getTaglibContextResolver(context);
+
+ if (tlResolver != null) {
+ Attr attr = getAttribute(context);
+ String startString = attr.getValue();
+
+ int length = startString.length();
+
+ if (attr != null) {
+ Node tagElement = attr.getOwnerElement();
+ if (tagElement == null)
+ return;
+
+ String nodeName = tagElement.getNodeName();
+ if (nodeName.substring(nodeName.indexOf(":")+1).toLowerCase().equals("loadbundle")) {
+ ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject());
+ for (String id : manager.getResourceBundleIdentifiers()) {
+ if (id.startsWith(startString) && id.length() != startString.length()) {
+ proposals.add(new ui.autocompletion.MessageCompletionProposal(
+ startPos, length, id, true));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private Attr getAttribute(IStructuredDocumentContext context) {
+ final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getDOMContextResolver(context);
+
+ if (domResolver != null) {
+ final Node curNode = domResolver.getNode();
+
+ if (curNode instanceof Attr) {
+ return (Attr) curNode;
+ }
+ }
+ return null;
+
+ }
+
+ @Override
+ public IContextInformation[] computeContextInformation(ITextViewer viewer,
+ int offset) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public char[] getCompletionProposalAutoActivationCharacters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public char[] getContextInformationAutoActivationCharacters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IContextInformationValidator getContextInformationValidator() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java
index 1536e504..2ed64653 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java
@@ -1,71 +1,78 @@
-package ui.autocompletion;
-
-import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-
-
-public class MessageCompletionProposal implements IJavaCompletionProposal {
-
- private int offset = 0;
- private int length = 0;
- private String content = "";
- private boolean messageAccessor = false;
-
- public MessageCompletionProposal (int offset, int length, String content, boolean messageAccessor) {
- this.offset = offset;
- this.length = length;
- this.content = content;
- this.messageAccessor = messageAccessor;
- }
-
- @Override
- public void apply(IDocument document) {
- try {
- document.replace(offset, length, content);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return "Inserts the property key '" + content + "' of the resource-bundle 'at.test.messages'";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return content;
- }
-
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- if (messageAccessor)
- return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
- return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return new Point (offset+content.length()+1, 0);
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- return 99;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.util.ImageUtils;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+
+
+public class MessageCompletionProposal implements IJavaCompletionProposal {
+
+ private int offset = 0;
+ private int length = 0;
+ private String content = "";
+ private boolean messageAccessor = false;
+
+ public MessageCompletionProposal (int offset, int length, String content, boolean messageAccessor) {
+ this.offset = offset;
+ this.length = length;
+ this.content = content;
+ this.messageAccessor = messageAccessor;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+ try {
+ document.replace(offset, length, content);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ // TODO Auto-generated method stub
+ return "Inserts the property key '" + content + "' of the resource-bundle 'at.test.messages'";
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ return content;
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ if (messageAccessor)
+ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE);
+ return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE);
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ // TODO Auto-generated method stub
+ return new Point (offset+content.length()+1, 0);
+ }
+
+ @Override
+ public int getRelevance() {
+ // TODO Auto-generated method stub
+ return 99;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
index 138d80e1..f2a76cd8 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java
@@ -1,122 +1,129 @@
-package ui.autocompletion;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-
-public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
-
- private int startPos;
- private int endPos;
- private String value;
- private ResourceBundleManager manager;
- private IResource resource;
- private String bundleName;
- private String reference;
- private boolean isKey;
-
- public NewResourceBundleEntryProposal(IResource resource, String str, int startPos, int endPos,
- ResourceBundleManager manager, String bundleName, boolean isKey) {
- this.startPos = startPos;
- this.endPos = endPos;
- this.manager = manager;
- this.value = str;
- this.resource = resource;
- this.bundleName = bundleName;
- this.isKey = isKey;
- }
-
- @Override
- public void apply(IDocument document) {
-
- CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
- Display.getDefault().getActiveShell());
-
- DialogConfiguration config = dialog.new DialogConfiguration();
- config.setPreselectedKey(isKey ? value : "");
- config.setPreselectedMessage(!isKey ? value : "");
- config.setPreselectedBundle(bundleName == null ? "" : bundleName);
- config.setPreselectedLocale("");
- config.setProjectName(resource.getProject().getName());
-
- dialog.setDialogConfiguration(config);
-
- if (dialog.open() != InputDialog.OK) {
- return;
- }
-
- String resourceBundleId = dialog.getSelectedResourceBundle();
- String key = dialog.getSelectedKey();
-
- try {
- document.replace(startPos, endPos, key);
- reference = key + "\"";
- ResourceBundleManager.refreshResource(resource);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- // TODO Auto-generated method stub
- return "Creates a new string literal within one of the" +
- " project's resource bundles. This action results " +
- "in a reference to the localized string literal!";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getDisplayString() {
- String displayStr = "";
-
- displayStr = "Create a new localized string literal";
-
- if (this.isKey) {
- if (value != null && value.length() > 0)
- displayStr += " with the key '" + value + "'";
- } else {
- if (value != null && value.length() > 0)
- displayStr += " for '" + value + "'";
- }
- return displayStr;
- }
-
- @Override
- public Image getImage() {
- return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_OBJ_ADD).createImage();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- // TODO Auto-generated method stub
- return new Point (startPos + reference.length()-1, 0);
- }
-
- @Override
- public int getRelevance() {
- // TODO Auto-generated method stub
- if (this.value.trim().length() == 0)
- return 1096;
- else
- return 1096;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package ui.autocompletion;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipse.babel.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog.DialogConfiguration;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+
+public class NewResourceBundleEntryProposal implements IJavaCompletionProposal {
+
+ private int startPos;
+ private int endPos;
+ private String value;
+ private ResourceBundleManager manager;
+ private IResource resource;
+ private String bundleName;
+ private String reference;
+ private boolean isKey;
+
+ public NewResourceBundleEntryProposal(IResource resource, String str, int startPos, int endPos,
+ ResourceBundleManager manager, String bundleName, boolean isKey) {
+ this.startPos = startPos;
+ this.endPos = endPos;
+ this.manager = manager;
+ this.value = str;
+ this.resource = resource;
+ this.bundleName = bundleName;
+ this.isKey = isKey;
+ }
+
+ @Override
+ public void apply(IDocument document) {
+
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell());
+
+ DialogConfiguration config = dialog.new DialogConfiguration();
+ config.setPreselectedKey(isKey ? value : "");
+ config.setPreselectedMessage(!isKey ? value : "");
+ config.setPreselectedBundle(bundleName == null ? "" : bundleName);
+ config.setPreselectedLocale("");
+ config.setProjectName(resource.getProject().getName());
+
+ dialog.setDialogConfiguration(config);
+
+ if (dialog.open() != InputDialog.OK) {
+ return;
+ }
+
+ String resourceBundleId = dialog.getSelectedResourceBundle();
+ String key = dialog.getSelectedKey();
+
+ try {
+ document.replace(startPos, endPos, key);
+ reference = key + "\"";
+ ResourceBundleManager.refreshResource(resource);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public String getAdditionalProposalInfo() {
+ // TODO Auto-generated method stub
+ return "Creates a new string literal within one of the" +
+ " project's resource bundles. This action results " +
+ "in a reference to the localized string literal!";
+ }
+
+ @Override
+ public IContextInformation getContextInformation() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getDisplayString() {
+ String displayStr = "";
+
+ displayStr = "Create a new localized string literal";
+
+ if (this.isKey) {
+ if (value != null && value.length() > 0)
+ displayStr += " with the key '" + value + "'";
+ } else {
+ if (value != null && value.length() > 0)
+ displayStr += " for '" + value + "'";
+ }
+ return displayStr;
+ }
+
+ @Override
+ public Image getImage() {
+ return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
+ ISharedImages.IMG_OBJ_ADD).createImage();
+ }
+
+ @Override
+ public Point getSelection(IDocument document) {
+ // TODO Auto-generated method stub
+ return new Point (startPos + reference.length()-1, 0);
+ }
+
+ @Override
+ public int getRelevance() {
+ // TODO Auto-generated method stub
+ if (this.value.trim().length() == 0)
+ return 1096;
+ else
+ return 1096;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java
index ca06d56c..815f6c86 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java
@@ -1,111 +1,118 @@
-package ui.autocompletion.jsf;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.CompletionProposal;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
-import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
-import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
-
-import ui.autocompletion.NewResourceBundleEntryProposal;
-import auditor.JSFResourceBundleDetector;
-
-public class MessageCompletionProposal implements IContentAssistProcessor {
-
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
- int offset) {
- List <ICompletionProposal> proposals = new ArrayList<ICompletionProposal> ();
-
- final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
- .getContext(viewer, offset);
-
- IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
- .getWorkspaceContextResolver(context);
-
- IProject project = workspaceResolver.getProject();
- IResource resource = workspaceResolver.getResource();
-
- if (project != null) {
- if (!InternationalizationNature.hasNature(project))
- return proposals.toArray(new CompletionProposal[proposals.size()]);
- } else
- return proposals.toArray(new CompletionProposal[proposals.size()]);
-
- // Compute proposals
- String expression = getProposalPrefix (viewer.getDocument(), offset);
- String bundleId = JSFResourceBundleDetector.resolveResourceBundleId(viewer.getDocument(),
- JSFResourceBundleDetector.getBundleVariableName(expression));
- String key = JSFResourceBundleDetector.getResourceKey(expression);
-
- if (expression.trim().length() > 0 &&
- bundleId.trim().length() > 0 &&
- isNonExistingKey (project, bundleId, key)) {
- // Add 'New Resource' proposal
- int startpos = offset - key.length();
- int length = key.length();
-
- proposals.add(new NewResourceBundleEntryProposal(resource, key, startpos, length, ResourceBundleManager.getManager(project)
- , bundleId, true));
- }
-
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
- private String getProposalPrefix(IDocument document, int offset) {
- String content = document.get().substring(0, offset);
- int expIntro = content.lastIndexOf("#{");
-
- return content.substring(expIntro+2, offset);
- }
-
- protected boolean isNonExistingKey (IProject project, String bundleId, String key) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(project);
-
- return !manager.isResourceExisting(bundleId, key);
- }
-
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer,
- int offset) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package ui.autocompletion.jsf;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.contentassist.CompletionProposal;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.jface.text.contentassist.IContextInformationValidator;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IStructuredDocumentContextResolverFactory;
+import org.eclipse.jst.jsf.context.resolver.structureddocument.IWorkspaceContextResolver;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContext;
+import org.eclipse.jst.jsf.context.structureddocument.IStructuredDocumentContextFactory;
+
+import ui.autocompletion.NewResourceBundleEntryProposal;
+import auditor.JSFResourceBundleDetector;
+
+public class MessageCompletionProposal implements IContentAssistProcessor {
+
+ @Override
+ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
+ int offset) {
+ List <ICompletionProposal> proposals = new ArrayList<ICompletionProposal> ();
+
+ final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE
+ .getContext(viewer, offset);
+
+ IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE
+ .getWorkspaceContextResolver(context);
+
+ IProject project = workspaceResolver.getProject();
+ IResource resource = workspaceResolver.getResource();
+
+ if (project != null) {
+ if (!InternationalizationNature.hasNature(project))
+ return proposals.toArray(new CompletionProposal[proposals.size()]);
+ } else
+ return proposals.toArray(new CompletionProposal[proposals.size()]);
+
+ // Compute proposals
+ String expression = getProposalPrefix (viewer.getDocument(), offset);
+ String bundleId = JSFResourceBundleDetector.resolveResourceBundleId(viewer.getDocument(),
+ JSFResourceBundleDetector.getBundleVariableName(expression));
+ String key = JSFResourceBundleDetector.getResourceKey(expression);
+
+ if (expression.trim().length() > 0 &&
+ bundleId.trim().length() > 0 &&
+ isNonExistingKey (project, bundleId, key)) {
+ // Add 'New Resource' proposal
+ int startpos = offset - key.length();
+ int length = key.length();
+
+ proposals.add(new NewResourceBundleEntryProposal(resource, key, startpos, length, ResourceBundleManager.getManager(project)
+ , bundleId, true));
+ }
+
+ return proposals.toArray(new ICompletionProposal[proposals.size()]);
+ }
+
+ private String getProposalPrefix(IDocument document, int offset) {
+ String content = document.get().substring(0, offset);
+ int expIntro = content.lastIndexOf("#{");
+
+ return content.substring(expIntro+2, offset);
+ }
+
+ protected boolean isNonExistingKey (IProject project, String bundleId, String key) {
+ ResourceBundleManager manager = ResourceBundleManager.getManager(project);
+
+ return !manager.isResourceExisting(bundleId, key);
+ }
+
+ @Override
+ public IContextInformation[] computeContextInformation(ITextViewer viewer,
+ int offset) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public char[] getCompletionProposalAutoActivationCharacters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public char[] getContextInformationAutoActivationCharacters() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public IContextInformationValidator getContextInformationValidator() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java b/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java
index afbc548e..4e518a6f 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java
@@ -1,16 +1,23 @@
-package util;
-
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.core.resources.IProject;
-
-
-public class ELUtils {
-
- public static String getResource (IProject project, String bundleName, String key) {
- ResourceBundleManager manager = ResourceBundleManager.getManager(project);
- if (manager.isResourceExisting(bundleName, key))
- return manager.getKeyHoverString(bundleName, key);
- else
- return null;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package util;
+
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.core.resources.IProject;
+
+
+public class ELUtils {
+
+ public static String getResource (IProject project, String bundleName, String key) {
+ ResourceBundleManager manager = ResourceBundleManager.getManager(project);
+ if (manager.isResourceExisting(bundleName, key))
+ return manager.getKeyHoverString(bundleName, key);
+ else
+ return null;
+ }
+}
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java b/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
index 98bd5b7f..afd6f9dd 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java
@@ -1,199 +1,206 @@
-package validator;
-
-import java.util.List;
-
-import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
-import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
-import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator;
-import org.eclipse.wst.validation.internal.core.ValidationException;
-import org.eclipse.wst.validation.internal.provisional.core.IReporter;
-import org.eclipse.wst.validation.internal.provisional.core.IValidationContext;
-import org.eclipse.wst.validation.internal.provisional.core.IValidator;
-
-import auditor.JSFResourceBundleDetector;
-import auditor.model.SLLocation;
-
-public class JSFInternationalizationValidator implements IValidator, ISourceValidator {
-
- private IDocument document;
-
- @Override
- public void cleanup(IReporter reporter) {
- }
-
- @Override
- public void validate(IValidationContext context, IReporter reporter)
- throws ValidationException {
- if (context.getURIs().length > 0) {
- IFile file = ResourcesPlugin.getWorkspace().getRoot()
- .getFile(new Path(context.getURIs()[0]));
-
- // full document validation
- EditorUtils.deleteAuditMarkersForResource(file.getProject()
- .findMember(file.getProjectRelativePath()));
-
- // validate all bundle definitions
- int pos = document.get().indexOf("loadBundle", 0);
- while (pos >= 0) {
- validateRegion(new Region(pos, 1), context, reporter);
- pos = document.get().indexOf("loadBundle", pos + 1);
- }
-
- // iterate all value definitions
- pos = document.get().indexOf(" value", 0);
- while (pos >= 0) {
- validateRegion(new Region(pos, 1), context, reporter);
- pos = document.get().indexOf(" value", pos + 1);
- }
- }
- }
-
- @Override
- public void connect(IDocument doc) {
- document = doc;
- }
-
- @Override
- public void disconnect(IDocument arg0) {
- document = null;
- }
-
- public void validateRegion(IRegion dirtyRegion, IValidationContext context,
- IReporter reporter) {
- int startPos = dirtyRegion.getOffset();
- int endPos = dirtyRegion.getOffset() + dirtyRegion.getLength();
-
- if (context.getURIs().length > 0) {
- IFile file = ResourcesPlugin.getWorkspace().getRoot()
- .getFile(new Path(context.getURIs()[0]));
- ResourceBundleManager manager = ResourceBundleManager
- .getManager(file.getProject());
-
- String bundleName = JSFResourceBundleDetector
- .resolveResourceBundleRefIdentifier(document, startPos);
- if (bundleName != null
- && !manager.getResourceBundleIdentifiers().contains(
- bundleName)) {
- IRegion reg = JSFResourceBundleDetector.getBasenameRegion(
- document, startPos);
- String ref = document.get().substring(reg.getOffset(),
- reg.getOffset() + reg.getLength());
-
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
- new String[] { ref }),
- new SLLocation(file, reg.getOffset(), reg
- .getOffset() + reg.getLength(), ref),
- IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
- ref, null, "jsf");
- return;
- }
-
- IRegion evr = JSFResourceBundleDetector.getElementAttrValueRegion(
- document, "value", startPos);
- if (evr != null) {
- String elementValue = document.get().substring(evr.getOffset(),
- evr.getOffset() + evr.getLength());
-
- // check all constant string expressions
- List<IRegion> regions = JSFResourceBundleDetector
- .getNonELValueRegions(elementValue);
-
- for (IRegion region : regions) {
- // report constant string literals
- String constantLiteral = elementValue.substring(
- region.getOffset(),
- region.getOffset() + region.getLength());
-
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
- new String[] { constantLiteral }),
- new SLLocation(file, region.getOffset()
- + evr.getOffset(), evr.getOffset()
- + region.getOffset()
- + region.getLength(),
- constantLiteral),
- IMarkerConstants.CAUSE_CONSTANT_LITERAL,
- constantLiteral, null,
- "jsf");
- }
-
- // check el expressions
- int start = document.get().indexOf("#{", evr.getOffset());
-
- while (start >= 0 && start < evr.getOffset() + evr.getLength()) {
- int end = document.get().indexOf("}", start);
- end = Math.min(end, evr.getOffset() + evr.getLength());
-
- if ((end - start) > 6) {
- String def = document.get().substring(start + 2, end);
- String varName = JSFResourceBundleDetector
- .getBundleVariableName(def);
- String key = JSFResourceBundleDetector
- .getResourceKey(def);
- if (varName != null && key != null) {
- if (varName.length() > 0) {
- IRegion refReg = JSFResourceBundleDetector
- .resolveResourceBundleRefPos(document,
- varName);
-
- if (refReg == null) {
- start = document.get().indexOf("#{", end);
- continue;
- }
-
- int bundleStart = refReg.getOffset();
- int bundleEnd = refReg.getOffset()
- + refReg.getLength();
-
- if (manager.isKeyBroken(
- document.get().substring(
- refReg.getOffset(),
- refReg.getOffset()
- + refReg.getLength()),
- key)) {
- SLLocation subMarker = new SLLocation(file,
- bundleStart, bundleEnd, document
- .get().substring(
- bundleStart,
- bundleEnd));
- EditorUtils
- .reportToMarker(
- EditorUtils
- .getFormattedMessage(
- EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
- new String[] { key, subMarker.getLiteral() }),
- new SLLocation(file,
- start+2, end, key),
- IMarkerConstants.CAUSE_BROKEN_REFERENCE,
- key,
- subMarker,
- "jsf");
- }
- }
- }
- }
-
- start = document.get().indexOf("#{", end);
- }
- }
- }
- }
-
- @Override
- public void validate(IRegion arg0, IValidationContext arg1, IReporter arg2) {}
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package validator;
+
+import java.util.List;
+
+import org.eclipse.babel.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipse.babel.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipse.babel.tapiji.tools.core.util.EditorUtils;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.Region;
+import org.eclipse.wst.sse.ui.internal.reconcile.validator.ISourceValidator;
+import org.eclipse.wst.validation.internal.core.ValidationException;
+import org.eclipse.wst.validation.internal.provisional.core.IReporter;
+import org.eclipse.wst.validation.internal.provisional.core.IValidationContext;
+import org.eclipse.wst.validation.internal.provisional.core.IValidator;
+
+import auditor.JSFResourceBundleDetector;
+import auditor.model.SLLocation;
+
+public class JSFInternationalizationValidator implements IValidator, ISourceValidator {
+
+ private IDocument document;
+
+ @Override
+ public void cleanup(IReporter reporter) {
+ }
+
+ @Override
+ public void validate(IValidationContext context, IReporter reporter)
+ throws ValidationException {
+ if (context.getURIs().length > 0) {
+ IFile file = ResourcesPlugin.getWorkspace().getRoot()
+ .getFile(new Path(context.getURIs()[0]));
+
+ // full document validation
+ EditorUtils.deleteAuditMarkersForResource(file.getProject()
+ .findMember(file.getProjectRelativePath()));
+
+ // validate all bundle definitions
+ int pos = document.get().indexOf("loadBundle", 0);
+ while (pos >= 0) {
+ validateRegion(new Region(pos, 1), context, reporter);
+ pos = document.get().indexOf("loadBundle", pos + 1);
+ }
+
+ // iterate all value definitions
+ pos = document.get().indexOf(" value", 0);
+ while (pos >= 0) {
+ validateRegion(new Region(pos, 1), context, reporter);
+ pos = document.get().indexOf(" value", pos + 1);
+ }
+ }
+ }
+
+ @Override
+ public void connect(IDocument doc) {
+ document = doc;
+ }
+
+ @Override
+ public void disconnect(IDocument arg0) {
+ document = null;
+ }
+
+ public void validateRegion(IRegion dirtyRegion, IValidationContext context,
+ IReporter reporter) {
+ int startPos = dirtyRegion.getOffset();
+ int endPos = dirtyRegion.getOffset() + dirtyRegion.getLength();
+
+ if (context.getURIs().length > 0) {
+ IFile file = ResourcesPlugin.getWorkspace().getRoot()
+ .getFile(new Path(context.getURIs()[0]));
+ ResourceBundleManager manager = ResourceBundleManager
+ .getManager(file.getProject());
+
+ String bundleName = JSFResourceBundleDetector
+ .resolveResourceBundleRefIdentifier(document, startPos);
+ if (bundleName != null
+ && !manager.getResourceBundleIdentifiers().contains(
+ bundleName)) {
+ IRegion reg = JSFResourceBundleDetector.getBasenameRegion(
+ document, startPos);
+ String ref = document.get().substring(reg.getOffset(),
+ reg.getOffset() + reg.getLength());
+
+ EditorUtils
+ .reportToMarker(
+ EditorUtils
+ .getFormattedMessage(
+ EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE,
+ new String[] { ref }),
+ new SLLocation(file, reg.getOffset(), reg
+ .getOffset() + reg.getLength(), ref),
+ IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE,
+ ref, null, "jsf");
+ return;
+ }
+
+ IRegion evr = JSFResourceBundleDetector.getElementAttrValueRegion(
+ document, "value", startPos);
+ if (evr != null) {
+ String elementValue = document.get().substring(evr.getOffset(),
+ evr.getOffset() + evr.getLength());
+
+ // check all constant string expressions
+ List<IRegion> regions = JSFResourceBundleDetector
+ .getNonELValueRegions(elementValue);
+
+ for (IRegion region : regions) {
+ // report constant string literals
+ String constantLiteral = elementValue.substring(
+ region.getOffset(),
+ region.getOffset() + region.getLength());
+
+ EditorUtils
+ .reportToMarker(
+ EditorUtils
+ .getFormattedMessage(
+ EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL,
+ new String[] { constantLiteral }),
+ new SLLocation(file, region.getOffset()
+ + evr.getOffset(), evr.getOffset()
+ + region.getOffset()
+ + region.getLength(),
+ constantLiteral),
+ IMarkerConstants.CAUSE_CONSTANT_LITERAL,
+ constantLiteral, null,
+ "jsf");
+ }
+
+ // check el expressions
+ int start = document.get().indexOf("#{", evr.getOffset());
+
+ while (start >= 0 && start < evr.getOffset() + evr.getLength()) {
+ int end = document.get().indexOf("}", start);
+ end = Math.min(end, evr.getOffset() + evr.getLength());
+
+ if ((end - start) > 6) {
+ String def = document.get().substring(start + 2, end);
+ String varName = JSFResourceBundleDetector
+ .getBundleVariableName(def);
+ String key = JSFResourceBundleDetector
+ .getResourceKey(def);
+ if (varName != null && key != null) {
+ if (varName.length() > 0) {
+ IRegion refReg = JSFResourceBundleDetector
+ .resolveResourceBundleRefPos(document,
+ varName);
+
+ if (refReg == null) {
+ start = document.get().indexOf("#{", end);
+ continue;
+ }
+
+ int bundleStart = refReg.getOffset();
+ int bundleEnd = refReg.getOffset()
+ + refReg.getLength();
+
+ if (manager.isKeyBroken(
+ document.get().substring(
+ refReg.getOffset(),
+ refReg.getOffset()
+ + refReg.getLength()),
+ key)) {
+ SLLocation subMarker = new SLLocation(file,
+ bundleStart, bundleEnd, document
+ .get().substring(
+ bundleStart,
+ bundleEnd));
+ EditorUtils
+ .reportToMarker(
+ EditorUtils
+ .getFormattedMessage(
+ EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE,
+ new String[] { key, subMarker.getLiteral() }),
+ new SLLocation(file,
+ start+2, end, key),
+ IMarkerConstants.CAUSE_BROKEN_REFERENCE,
+ key,
+ subMarker,
+ "jsf");
+ }
+ }
+ }
+ }
+
+ start = document.get().indexOf("#{", end);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void validate(IRegion arg0, IValidationContext arg1, IReporter arg2) {}
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java
index 6689bdfe..5b5f1bff 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java
@@ -1,61 +1,68 @@
-package org.eclipselabs.tapiji.translator;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class Activator extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipselabs.tapiji.translator"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static Activator getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipselabs.tapiji.translator"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java
index bd06d884..e641189c 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.equinox.app.IApplication;
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
index bd96f8c5..27ebb38c 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.jface.action.GroupMarker;
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
index 666e751b..655f465b 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.ui.application.IWorkbenchConfigurer;
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
index 40b88788..c06b2f52 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.core.runtime.CoreException;
@@ -100,7 +107,7 @@ public void handleEvent(Event event) {
Menu menu = new Menu (window.getShell(), SWT.POP_UP);
MenuItem about = new MenuItem (menu, SWT.None);
- about.setText("&Über");
+ about.setText("&�ber");
about.addListener(SWT.Selection, new Listener () {
@Override
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java
index d1fcd27a..986a37ce 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator;
import org.eclipse.ui.IPageLayout;
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java
index c2378edf..c661bf42 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java
@@ -1,65 +1,72 @@
-package org.eclipselabs.tapiji.translator.actions;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
-public class FileOpenAction extends Action implements
- IWorkbenchWindowActionDelegate {
-
- /** Editor ids **/
- public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
-
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName = FileUtils.queryFileName(window.getShell(),
- "Open Resource-Bundle", SWT.OPEN,
- new String[] { "*.properties" });
- if (!FileUtils.isResourceBundle(fileName)) {
- MessageDialog.openError(window.getShell(),
- "Cannot open Resource-Bundle",
- "The choosen file does not represent a Resource-Bundle!");
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page = window.getActivePage();
- try {
- page.openEditor(
- new FileEditorInput(FileUtils
- .getResourceBundleRef(fileName)),
- RESOURCE_BUNDLE_EDITOR);
-
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.actions;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.IWorkbenchWindowActionDelegate;
+import org.eclipse.ui.part.FileEditorInput;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
+
+public class FileOpenAction extends Action implements
+ IWorkbenchWindowActionDelegate {
+
+ /** Editor ids **/
+ public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor";
+
+ private IWorkbenchWindow window;
+
+ @Override
+ public void run(IAction action) {
+ String fileName = FileUtils.queryFileName(window.getShell(),
+ "Open Resource-Bundle", SWT.OPEN,
+ new String[] { "*.properties" });
+ if (!FileUtils.isResourceBundle(fileName)) {
+ MessageDialog.openError(window.getShell(),
+ "Cannot open Resource-Bundle",
+ "The choosen file does not represent a Resource-Bundle!");
+ return;
+ }
+
+ if (fileName != null) {
+ IWorkbenchPage page = window.getActivePage();
+ try {
+ page.openEditor(
+ new FileEditorInput(FileUtils
+ .getResourceBundleRef(fileName)),
+ RESOURCE_BUNDLE_EDITOR);
+
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void dispose() {
+ window = null;
+ }
+
+ @Override
+ public void init(IWorkbenchWindow window) {
+ this.window = window;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
index 967c0814..66b123d8 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java
@@ -1,63 +1,70 @@
-package org.eclipselabs.tapiji.translator.actions;
-
-import java.io.File;
-import java.text.MessageFormat;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
-
-public class NewGlossaryAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window */
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "New Glossary", SWT.SAVE, new String[] {"*.xml"} );
-
- if (!fileName.endsWith(".xml")) {
- if (fileName.endsWith("."))
- fileName += "xml";
- else
- fileName += ".xml";
- }
-
- if (new File (fileName).exists()) {
- String recallPattern = "The file \"{0}\" already exists. Do you want to replace this file with an empty translation glossary?";
- MessageFormat mf = new MessageFormat(recallPattern);
-
- if (!MessageDialog.openQuestion(window.getShell(),
- "File already exists!", mf.format(new String[] {fileName})))
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
- GlossaryManager.newGlossary (new File (fileName));
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
-
- }
-
- @Override
- public void dispose() {
- this.window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.actions;
+
+import java.io.File;
+import java.text.MessageFormat;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.IWorkbenchWindowActionDelegate;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
+
+
+public class NewGlossaryAction implements IWorkbenchWindowActionDelegate {
+
+ /** The workbench window */
+ private IWorkbenchWindow window;
+
+ @Override
+ public void run(IAction action) {
+ String fileName= FileUtils.queryFileName(window.getShell(), "New Glossary", SWT.SAVE, new String[] {"*.xml"} );
+
+ if (!fileName.endsWith(".xml")) {
+ if (fileName.endsWith("."))
+ fileName += "xml";
+ else
+ fileName += ".xml";
+ }
+
+ if (new File (fileName).exists()) {
+ String recallPattern = "The file \"{0}\" already exists. Do you want to replace this file with an empty translation glossary?";
+ MessageFormat mf = new MessageFormat(recallPattern);
+
+ if (!MessageDialog.openQuestion(window.getShell(),
+ "File already exists!", mf.format(new String[] {fileName})))
+ return;
+ }
+
+ if (fileName != null) {
+ IWorkbenchPage page= window.getActivePage();
+ GlossaryManager.newGlossary (new File (fileName));
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+
+ }
+
+ @Override
+ public void dispose() {
+ this.window = null;
+ }
+
+ @Override
+ public void init(IWorkbenchWindow window) {
+ this.window = window;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
index b2556c2c..40a8c894 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java
@@ -1,53 +1,60 @@
-package org.eclipselabs.tapiji.translator.actions;
-
-import java.io.File;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.utils.FileUtils;
-
-
-public class OpenGlossaryAction implements IWorkbenchWindowActionDelegate {
-
- /** The workbench window */
- private IWorkbenchWindow window;
-
- @Override
- public void run(IAction action) {
- String fileName= FileUtils.queryFileName(window.getShell(), "Open Glossary", SWT.OPEN, new String[] {"*.xml"} );
- if (!FileUtils.isGlossary(fileName)) {
- MessageDialog.openError(window.getShell(),
- "Cannot open Glossary", "The choosen file does not represent a Glossary!");
- return;
- }
-
- if (fileName != null) {
- IWorkbenchPage page= window.getActivePage();
- if (fileName != null) {
- GlossaryManager.loadGlossary(new File (fileName));
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
-
- }
-
- @Override
- public void dispose() {
- this.window = null;
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- this.window = window;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.actions;
+
+import java.io.File;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.IWorkbenchWindowActionDelegate;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
+
+
+public class OpenGlossaryAction implements IWorkbenchWindowActionDelegate {
+
+ /** The workbench window */
+ private IWorkbenchWindow window;
+
+ @Override
+ public void run(IAction action) {
+ String fileName= FileUtils.queryFileName(window.getShell(), "Open Glossary", SWT.OPEN, new String[] {"*.xml"} );
+ if (!FileUtils.isGlossary(fileName)) {
+ MessageDialog.openError(window.getShell(),
+ "Cannot open Glossary", "The choosen file does not represent a Glossary!");
+ return;
+ }
+
+ if (fileName != null) {
+ IWorkbenchPage page= window.getActivePage();
+ if (fileName != null) {
+ GlossaryManager.loadGlossary(new File (fileName));
+ }
+ }
+ }
+
+ @Override
+ public void selectionChanged(IAction action, ISelection selection) {
+
+ }
+
+ @Override
+ public void dispose() {
+ this.window = null;
+ }
+
+ @Override
+ public void init(IWorkbenchWindow window) {
+ this.window = window;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
index 5ce5a885..4e687773 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java
@@ -1,82 +1,89 @@
-package org.eclipselabs.tapiji.translator.core;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-
-import org.eclipselabs.tapiji.translator.model.Glossary;
-
-
-public class GlossaryManager {
-
- private Glossary glossary;
- private File file;
- private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener> ();
-
- public GlossaryManager (File file, boolean overwrite) throws Exception {
- this.file = file;
-
- if (file.exists() && !overwrite) {
- // load the existing glossary
- glossary = new Glossary();
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Unmarshaller unmarshaller = context.createUnmarshaller();
- glossary = (Glossary) unmarshaller.unmarshal(file);
- } else {
- // Create a new glossary
- glossary = new Glossary ();
- saveGlossary();
- }
- }
-
- public void saveGlossary () throws Exception {
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-16");
-
- OutputStream fout = new FileOutputStream (file.getAbsolutePath());
- OutputStream bout = new BufferedOutputStream (fout);
- marshaller.marshal(glossary, new OutputStreamWriter (bout, "UTF-16"));
- }
-
- public void setGlossary (Glossary glossary) {
- this.glossary = glossary;
- }
-
- public Glossary getGlossary () {
- return glossary;
- }
-
- public static void loadGlossary (File file) {
- /* Inform the listeners */
- LoadGlossaryEvent event = new LoadGlossaryEvent (file);
- for (ILoadGlossaryListener listener : loadGlossaryListeners) {
- listener.glossaryLoaded(event);
- }
- }
-
- public static void registerLoadGlossaryListener (ILoadGlossaryListener listener) {
- loadGlossaryListeners.add(listener);
- }
-
- public static void unregisterLoadGlossaryListener (ILoadGlossaryListener listener) {
- loadGlossaryListeners.remove(listener);
- }
-
- public static void newGlossary(File file) {
- /* Inform the listeners */
- LoadGlossaryEvent event = new LoadGlossaryEvent (file);
- event.setNewGlossary(true);
- for (ILoadGlossaryListener listener : loadGlossaryListeners) {
- listener.glossaryLoaded(event);
- }
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.core;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+
+import org.eclipselabs.tapiji.translator.model.Glossary;
+
+
+public class GlossaryManager {
+
+ private Glossary glossary;
+ private File file;
+ private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener> ();
+
+ public GlossaryManager (File file, boolean overwrite) throws Exception {
+ this.file = file;
+
+ if (file.exists() && !overwrite) {
+ // load the existing glossary
+ glossary = new Glossary();
+ JAXBContext context = JAXBContext.newInstance(glossary.getClass());
+ Unmarshaller unmarshaller = context.createUnmarshaller();
+ glossary = (Glossary) unmarshaller.unmarshal(file);
+ } else {
+ // Create a new glossary
+ glossary = new Glossary ();
+ saveGlossary();
+ }
+ }
+
+ public void saveGlossary () throws Exception {
+ JAXBContext context = JAXBContext.newInstance(glossary.getClass());
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-16");
+
+ OutputStream fout = new FileOutputStream (file.getAbsolutePath());
+ OutputStream bout = new BufferedOutputStream (fout);
+ marshaller.marshal(glossary, new OutputStreamWriter (bout, "UTF-16"));
+ }
+
+ public void setGlossary (Glossary glossary) {
+ this.glossary = glossary;
+ }
+
+ public Glossary getGlossary () {
+ return glossary;
+ }
+
+ public static void loadGlossary (File file) {
+ /* Inform the listeners */
+ LoadGlossaryEvent event = new LoadGlossaryEvent (file);
+ for (ILoadGlossaryListener listener : loadGlossaryListeners) {
+ listener.glossaryLoaded(event);
+ }
+ }
+
+ public static void registerLoadGlossaryListener (ILoadGlossaryListener listener) {
+ loadGlossaryListeners.add(listener);
+ }
+
+ public static void unregisterLoadGlossaryListener (ILoadGlossaryListener listener) {
+ loadGlossaryListeners.remove(listener);
+ }
+
+ public static void newGlossary(File file) {
+ /* Inform the listeners */
+ LoadGlossaryEvent event = new LoadGlossaryEvent (file);
+ event.setNewGlossary(true);
+ for (ILoadGlossaryListener listener : loadGlossaryListeners) {
+ listener.glossaryLoaded(event);
+ }
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
index 3d3a263f..69095e11 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java
@@ -1,7 +1,14 @@
-package org.eclipselabs.tapiji.translator.core;
-
-public interface ILoadGlossaryListener {
-
- void glossaryLoaded (LoadGlossaryEvent event);
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.core;
+
+public interface ILoadGlossaryListener {
+
+ void glossaryLoaded (LoadGlossaryEvent event);
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
index 54bc3891..6b344ae0 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java
@@ -1,30 +1,37 @@
-package org.eclipselabs.tapiji.translator.core;
-
-import java.io.File;
-
-public class LoadGlossaryEvent {
-
- private boolean newGlossary = false;
- private File glossaryFile;
-
- public LoadGlossaryEvent (File glossaryFile) {
- this.glossaryFile = glossaryFile;
- }
-
- public File getGlossaryFile() {
- return glossaryFile;
- }
-
- public void setNewGlossary(boolean newGlossary) {
- this.newGlossary = newGlossary;
- }
-
- public boolean isNewGlossary() {
- return newGlossary;
- }
-
- public void setGlossaryFile(File glossaryFile) {
- this.glossaryFile = glossaryFile;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.core;
+
+import java.io.File;
+
+public class LoadGlossaryEvent {
+
+ private boolean newGlossary = false;
+ private File glossaryFile;
+
+ public LoadGlossaryEvent (File glossaryFile) {
+ this.glossaryFile = glossaryFile;
+ }
+
+ public File getGlossaryFile() {
+ return glossaryFile;
+ }
+
+ public void setNewGlossary(boolean newGlossary) {
+ this.newGlossary = newGlossary;
+ }
+
+ public boolean isNewGlossary() {
+ return newGlossary;
+ }
+
+ public void setGlossaryFile(File glossaryFile) {
+ this.glossaryFile = glossaryFile;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java
index 61607d56..3aad69e2 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java
@@ -1,75 +1,82 @@
-package org.eclipselabs.tapiji.translator.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class Glossary implements Serializable {
-
- private static final long serialVersionUID = 2070750758712154134L;
-
- public Info info;
-
- @XmlElementWrapper (name="terms")
- @XmlElement (name = "term")
- public List<Term> terms;
-
- public Glossary() {
- terms = new ArrayList <Term> ();
- info = new Info();
- }
-
- public Term[] getAllTerms () {
- return terms.toArray(new Term [terms.size()]);
- }
-
- public int getIndexOfLocale(String referenceLocale) {
- int i = 0;
-
- for (String locale : info.translations) {
- if (locale.equalsIgnoreCase(referenceLocale))
- return i;
- i++;
- }
-
- return 0;
- }
-
- public void removeTerm(Term elem) {
- for (Term term : terms) {
- if (term == elem) {
- terms.remove(term);
- break;
- }
-
- if (term.removeTerm (elem))
- break;
- }
- }
-
- public void addTerm(Term parentTerm, Term newTerm) {
- if (parentTerm == null) {
- this.terms.add(newTerm);
- return;
- }
-
- for (Term term : terms) {
- if (term == parentTerm) {
- term.subTerms.add(newTerm);
- break;
- }
-
- if (term.addTerm (parentTerm, newTerm))
- break;
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.model;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.FIELD)
+public class Glossary implements Serializable {
+
+ private static final long serialVersionUID = 2070750758712154134L;
+
+ public Info info;
+
+ @XmlElementWrapper (name="terms")
+ @XmlElement (name = "term")
+ public List<Term> terms;
+
+ public Glossary() {
+ terms = new ArrayList <Term> ();
+ info = new Info();
+ }
+
+ public Term[] getAllTerms () {
+ return terms.toArray(new Term [terms.size()]);
+ }
+
+ public int getIndexOfLocale(String referenceLocale) {
+ int i = 0;
+
+ for (String locale : info.translations) {
+ if (locale.equalsIgnoreCase(referenceLocale))
+ return i;
+ i++;
+ }
+
+ return 0;
+ }
+
+ public void removeTerm(Term elem) {
+ for (Term term : terms) {
+ if (term == elem) {
+ terms.remove(term);
+ break;
+ }
+
+ if (term.removeTerm (elem))
+ break;
+ }
+ }
+
+ public void addTerm(Term parentTerm, Term newTerm) {
+ if (parentTerm == null) {
+ this.terms.add(newTerm);
+ return;
+ }
+
+ for (Term term : terms) {
+ if (term == parentTerm) {
+ term.subTerms.add(newTerm);
+ break;
+ }
+
+ if (term.addTerm (parentTerm, newTerm))
+ break;
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java
index f7abdc18..4efbdce6 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java
@@ -1,32 +1,39 @@
-package org.eclipselabs.tapiji.translator.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-public class Info implements Serializable {
-
- private static final long serialVersionUID = 8607746669906026928L;
-
- @XmlElementWrapper (name = "locales")
- @XmlElement (name = "locale")
- public List<String> translations;
-
- public Info () {
- this.translations = new ArrayList<String>();
-
- // Add the default Locale
- this.translations.add("Default");
- }
-
- public String[] getTranslations () {
- return translations.toArray(new String [translations.size()]);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.model;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+
+@XmlAccessorType (XmlAccessType.FIELD)
+public class Info implements Serializable {
+
+ private static final long serialVersionUID = 8607746669906026928L;
+
+ @XmlElementWrapper (name = "locales")
+ @XmlElement (name = "locale")
+ public List<String> translations;
+
+ public Info () {
+ this.translations = new ArrayList<String>();
+
+ // Add the default Locale
+ this.translations.add("Default");
+ }
+
+ public String[] getTranslations () {
+ return translations.toArray(new String [translations.size()]);
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java
index 26bef6e2..3cbdc581 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java
@@ -1,106 +1,113 @@
-package org.eclipselabs.tapiji.translator.model;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlTransient;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-public class Term implements Serializable {
-
- private static final long serialVersionUID = 7004998590181568026L;
-
- @XmlElementWrapper (name = "translations")
- @XmlElement (name = "translation")
- public List<Translation> translations;
-
- @XmlElementWrapper (name = "terms")
- @XmlElement (name = "term")
- public List<Term> subTerms;
-
- public Term parentTerm;
-
- @XmlTransient
- private Object info;
-
- public Term () {
- translations = new ArrayList<Translation> ();
- subTerms = new ArrayList<Term> ();
- parentTerm = null;
- info = null;
- }
-
- public void setInfo(Object info) {
- this.info = info;
- }
-
- public Object getInfo() {
- return info;
- }
-
- public Term[] getAllSubTerms () {
- return subTerms.toArray(new Term[subTerms.size()]);
- }
-
- public Term getParentTerm() {
- return parentTerm;
- }
-
- public boolean hasChildTerms () {
- return subTerms != null && subTerms.size() > 0;
- }
-
- public Translation[] getAllTranslations() {
- return translations.toArray(new Translation [translations.size()]);
- }
-
- public Translation getTranslation (String language) {
- for (Translation translation : translations) {
- if (translation.id.equalsIgnoreCase(language))
- return translation;
- }
-
- Translation newTranslation = new Translation ();
- newTranslation.id = language;
- translations.add(newTranslation);
-
- return newTranslation;
- }
-
- public boolean removeTerm(Term elem) {
- boolean hasFound = false;
- for (Term subTerm : subTerms) {
- if (subTerm == elem) {
- subTerms.remove(elem);
- hasFound = true;
- break;
- } else {
- hasFound = subTerm.removeTerm(elem);
- if (hasFound)
- break;
- }
- }
- return hasFound;
- }
-
- public boolean addTerm(Term parentTerm, Term newTerm) {
- boolean hasFound = false;
- for (Term subTerm : subTerms) {
- if (subTerm == parentTerm) {
- subTerms.add(newTerm);
- hasFound = true;
- break;
- } else {
- hasFound = subTerm.addTerm(parentTerm, newTerm);
- if (hasFound)
- break;
- }
- }
- return hasFound;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.model;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlTransient;
+
+@XmlAccessorType (XmlAccessType.FIELD)
+public class Term implements Serializable {
+
+ private static final long serialVersionUID = 7004998590181568026L;
+
+ @XmlElementWrapper (name = "translations")
+ @XmlElement (name = "translation")
+ public List<Translation> translations;
+
+ @XmlElementWrapper (name = "terms")
+ @XmlElement (name = "term")
+ public List<Term> subTerms;
+
+ public Term parentTerm;
+
+ @XmlTransient
+ private Object info;
+
+ public Term () {
+ translations = new ArrayList<Translation> ();
+ subTerms = new ArrayList<Term> ();
+ parentTerm = null;
+ info = null;
+ }
+
+ public void setInfo(Object info) {
+ this.info = info;
+ }
+
+ public Object getInfo() {
+ return info;
+ }
+
+ public Term[] getAllSubTerms () {
+ return subTerms.toArray(new Term[subTerms.size()]);
+ }
+
+ public Term getParentTerm() {
+ return parentTerm;
+ }
+
+ public boolean hasChildTerms () {
+ return subTerms != null && subTerms.size() > 0;
+ }
+
+ public Translation[] getAllTranslations() {
+ return translations.toArray(new Translation [translations.size()]);
+ }
+
+ public Translation getTranslation (String language) {
+ for (Translation translation : translations) {
+ if (translation.id.equalsIgnoreCase(language))
+ return translation;
+ }
+
+ Translation newTranslation = new Translation ();
+ newTranslation.id = language;
+ translations.add(newTranslation);
+
+ return newTranslation;
+ }
+
+ public boolean removeTerm(Term elem) {
+ boolean hasFound = false;
+ for (Term subTerm : subTerms) {
+ if (subTerm == elem) {
+ subTerms.remove(elem);
+ hasFound = true;
+ break;
+ } else {
+ hasFound = subTerm.removeTerm(elem);
+ if (hasFound)
+ break;
+ }
+ }
+ return hasFound;
+ }
+
+ public boolean addTerm(Term parentTerm, Term newTerm) {
+ boolean hasFound = false;
+ for (Term subTerm : subTerms) {
+ if (subTerm == parentTerm) {
+ subTerms.add(newTerm);
+ hasFound = true;
+ break;
+ } else {
+ hasFound = subTerm.addTerm(parentTerm, newTerm);
+ if (hasFound)
+ break;
+ }
+ }
+ return hasFound;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java
index 624b5066..493f01ab 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java
@@ -1,24 +1,31 @@
-package org.eclipselabs.tapiji.translator.model;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlType;
-
-@XmlAccessorType (XmlAccessType.FIELD)
-@XmlType (name = "Translation")
-public class Translation implements Serializable {
-
- private static final long serialVersionUID = 2033276999496196690L;
-
- public String id;
-
- public String value;
-
- public Translation () {
- id = "";
- value = "";
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.model;
+
+import java.io.Serializable;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlAccessorType (XmlAccessType.FIELD)
+@XmlType (name = "Translation")
+public class Translation implements Serializable {
+
+ private static final long serialVersionUID = 2033276999496196690L;
+
+ public String id;
+
+ public String value;
+
+ public Translation () {
+ id = "";
+ value = "";
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
index 57872066..6985a578 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java
@@ -1,127 +1,134 @@
-package org.eclipselabs.tapiji.translator.tests;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.util.ArrayList;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Info;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-import org.junit.Assert;
-import org.junit.Test;
-
-
-public class JaxBTest {
-
- @Test
- public void testModel () {
- Glossary glossary = new Glossary ();
- Info info = new Info ();
- info.translations = new ArrayList<String>();
- info.translations.add("default");
- info.translations.add("de");
- info.translations.add("en");
- glossary.info = info;
- glossary.terms = new ArrayList<Term>();
-
- // Hello World
- Term term = new Term();
-
- Translation tranl1 = new Translation ();
- tranl1.id = "default";
- tranl1.value = "Hallo Welt";
-
- Translation tranl2 = new Translation ();
- tranl2.id = "de";
- tranl2.value = "Hallo Welt";
-
- Translation tranl3 = new Translation ();
- tranl3.id = "en";
- tranl3.value = "Hello World!";
-
- term.translations = new ArrayList <Translation>();
- term.translations.add(tranl1);
- term.translations.add(tranl2);
- term.translations.add(tranl3);
- term.parentTerm = null;
-
- glossary.terms.add(term);
-
- // Hello World 2
- Term term2 = new Term();
-
- Translation tranl12 = new Translation ();
- tranl12.id = "default";
- tranl12.value = "Hallo Welt2";
-
- Translation tranl22 = new Translation ();
- tranl22.id = "de";
- tranl22.value = "Hallo Welt2";
-
- Translation tranl32 = new Translation ();
- tranl32.id = "en";
- tranl32.value = "Hello World2!";
-
- term2.translations = new ArrayList <Translation>();
- term2.translations.add(tranl12);
- term2.translations.add(tranl22);
- term2.translations.add(tranl32);
- //term2.parentTerm = term;
-
- term.subTerms = new ArrayList<Term>();
- term.subTerms.add(term2);
-
- // Hello World 3
- Term term3 = new Term();
-
- Translation tranl13 = new Translation ();
- tranl13.id = "default";
- tranl13.value = "Hallo Welt3";
-
- Translation tranl23 = new Translation ();
- tranl23.id = "de";
- tranl23.value = "Hallo Welt3";
-
- Translation tranl33 = new Translation ();
- tranl33.id = "en";
- tranl33.value = "Hello World3!";
-
- term3.translations = new ArrayList <Translation>();
- term3.translations.add(tranl13);
- term3.translations.add(tranl23);
- term3.translations.add(tranl33);
- term3.parentTerm = null;
-
- glossary.terms.add(term3);
-
- // Serialize model
- try {
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Marshaller marshaller = context.createMarshaller();
- marshaller.marshal(glossary, new FileWriter ("C:\\test.xml"));
- } catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
- }
- }
-
- @Test
- public void testReadModel () {
- Glossary glossary = new Glossary();
-
- try {
- JAXBContext context = JAXBContext.newInstance(glossary.getClass());
- Unmarshaller unmarshaller = context.createUnmarshaller();
- glossary = (Glossary) unmarshaller.unmarshal(new File ("C:\\test.xml"));
- } catch (Exception e) {
- e.printStackTrace();
- Assert.assertFalse(true);
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.tests;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.util.ArrayList;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Info;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.junit.Assert;
+import org.junit.Test;
+
+
+public class JaxBTest {
+
+ @Test
+ public void testModel () {
+ Glossary glossary = new Glossary ();
+ Info info = new Info ();
+ info.translations = new ArrayList<String>();
+ info.translations.add("default");
+ info.translations.add("de");
+ info.translations.add("en");
+ glossary.info = info;
+ glossary.terms = new ArrayList<Term>();
+
+ // Hello World
+ Term term = new Term();
+
+ Translation tranl1 = new Translation ();
+ tranl1.id = "default";
+ tranl1.value = "Hallo Welt";
+
+ Translation tranl2 = new Translation ();
+ tranl2.id = "de";
+ tranl2.value = "Hallo Welt";
+
+ Translation tranl3 = new Translation ();
+ tranl3.id = "en";
+ tranl3.value = "Hello World!";
+
+ term.translations = new ArrayList <Translation>();
+ term.translations.add(tranl1);
+ term.translations.add(tranl2);
+ term.translations.add(tranl3);
+ term.parentTerm = null;
+
+ glossary.terms.add(term);
+
+ // Hello World 2
+ Term term2 = new Term();
+
+ Translation tranl12 = new Translation ();
+ tranl12.id = "default";
+ tranl12.value = "Hallo Welt2";
+
+ Translation tranl22 = new Translation ();
+ tranl22.id = "de";
+ tranl22.value = "Hallo Welt2";
+
+ Translation tranl32 = new Translation ();
+ tranl32.id = "en";
+ tranl32.value = "Hello World2!";
+
+ term2.translations = new ArrayList <Translation>();
+ term2.translations.add(tranl12);
+ term2.translations.add(tranl22);
+ term2.translations.add(tranl32);
+ //term2.parentTerm = term;
+
+ term.subTerms = new ArrayList<Term>();
+ term.subTerms.add(term2);
+
+ // Hello World 3
+ Term term3 = new Term();
+
+ Translation tranl13 = new Translation ();
+ tranl13.id = "default";
+ tranl13.value = "Hallo Welt3";
+
+ Translation tranl23 = new Translation ();
+ tranl23.id = "de";
+ tranl23.value = "Hallo Welt3";
+
+ Translation tranl33 = new Translation ();
+ tranl33.id = "en";
+ tranl33.value = "Hello World3!";
+
+ term3.translations = new ArrayList <Translation>();
+ term3.translations.add(tranl13);
+ term3.translations.add(tranl23);
+ term3.translations.add(tranl33);
+ term3.parentTerm = null;
+
+ glossary.terms.add(term3);
+
+ // Serialize model
+ try {
+ JAXBContext context = JAXBContext.newInstance(glossary.getClass());
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.marshal(glossary, new FileWriter ("C:\\test.xml"));
+ } catch (Exception e) {
+ e.printStackTrace();
+ Assert.assertFalse(true);
+ }
+ }
+
+ @Test
+ public void testReadModel () {
+ Glossary glossary = new Glossary();
+
+ try {
+ JAXBContext context = JAXBContext.newInstance(glossary.getClass());
+ Unmarshaller unmarshaller = context.createUnmarshaller();
+ glossary = (Glossary) unmarshaller.unmarshal(new File ("C:\\test.xml"));
+ } catch (Exception e) {
+ e.printStackTrace();
+ Assert.assertFalse(true);
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
index c4dc3957..e12a577e 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java
@@ -1,133 +1,140 @@
-package org.eclipselabs.tapiji.translator.utils;
-
-import java.io.File;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-
-public class FileUtils {
-
- /** Token to replace in a regular expression with a bundle name. */
- private static final String TOKEN_BUNDLE_NAME = "BUNDLENAME";
- /** Token to replace in a regular expression with a file extension. */
- private static final String TOKEN_FILE_EXTENSION =
- "FILEEXTENSION";
- /** Regex to match a properties file. */
- private static final String PROPERTIES_FILE_REGEX =
- "^(" + TOKEN_BUNDLE_NAME + ")"
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
- + TOKEN_FILE_EXTENSION + ")$";
-
- /** The singleton instance of Workspace */
- private static IWorkspace workspace;
-
- /** Wrapper project for external file resources */
- private static IProject project;
-
- public static boolean isResourceBundle (String fileName) {
- return fileName.toLowerCase().endsWith(".properties");
- }
-
- public static boolean isGlossary (String fileName) {
- return fileName.toLowerCase().endsWith(".xml");
- }
-
- public static IWorkspace getWorkspace () {
- if (workspace == null) {
- workspace = ResourcesPlugin.getWorkspace();
- }
-
- return workspace;
- }
-
- public static IProject getProject () throws CoreException {
- if (project == null) {
- project = getWorkspace().getRoot().getProject("ExternalResourceBundles");
- }
-
- if (!project.exists())
- project.create(null);
- if (!project.isOpen())
- project.open(null);
-
- return project;
- }
-
- public static void prePareEditorInputs () {
- IWorkspace workspace = getWorkspace();
- }
-
- public static IFile getResourceBundleRef (String location) throws CoreException {
- IPath path = new Path (location);
-
- /** Create all files of the Resource-Bundle within the project space and link them to the original file */
- String regex = getPropertiesFileRegEx(path);
- String projPathName = toProjectRelativePathName(path);
- IFile file = getProject().getFile(projPathName);
- file.createLink(path, IResource.REPLACE, null);
-
- File parentDir = new File (path.toFile().getParent());
- String[] files = parentDir.list();
-
- for (String fn : files) {
- File fo = new File (parentDir, fn);
- if (!fo.isFile())
- continue;
-
- IPath newFilePath = new Path(fo.getAbsolutePath());
- if (fo.getName().matches(regex) && !path.toFile().getName().equals(newFilePath.toFile().getName())) {
- IFile newFile = project.getFile(toProjectRelativePathName(newFilePath));
- newFile.createLink(newFilePath, IResource.REPLACE, null);
- }
- }
-
- return file;
- }
-
- protected static String toProjectRelativePathName (IPath path) {
- String projectRelativeName = "";
-
- projectRelativeName = path.toString().replaceAll(":", "");
- projectRelativeName = projectRelativeName.replaceAll("/", ".");
-
- return projectRelativeName;
- }
-
- protected static String getPropertiesFileRegEx(IPath file) {
- String bundleName = getBundleName(file);
- return PROPERTIES_FILE_REGEX.replaceFirst(
- TOKEN_BUNDLE_NAME, bundleName).replaceFirst(
- TOKEN_FILE_EXTENSION, file.getFileExtension());
- }
-
- public static String getBundleName(IPath file) {
- String name = file.toFile().getName();
- String regex = "^(.*?)" //$NON-NLS-1$
- + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
- + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
- + file.getFileExtension() + ")$";
- return name.replaceFirst(regex, "$1");
- }
-
- public static String queryFileName(Shell shell, String title, int dialogOptions, String[] endings) {
- FileDialog dialog= new FileDialog(shell, dialogOptions);
- dialog.setText( title );
- dialog.setFilterExtensions(endings);
- String path= dialog.open();
-
-
- if (path != null && path.length() > 0)
- return path;
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.utils;
+
+import java.io.File;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+
+public class FileUtils {
+
+ /** Token to replace in a regular expression with a bundle name. */
+ private static final String TOKEN_BUNDLE_NAME = "BUNDLENAME";
+ /** Token to replace in a regular expression with a file extension. */
+ private static final String TOKEN_FILE_EXTENSION =
+ "FILEEXTENSION";
+ /** Regex to match a properties file. */
+ private static final String PROPERTIES_FILE_REGEX =
+ "^(" + TOKEN_BUNDLE_NAME + ")"
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
+ + TOKEN_FILE_EXTENSION + ")$";
+
+ /** The singleton instance of Workspace */
+ private static IWorkspace workspace;
+
+ /** Wrapper project for external file resources */
+ private static IProject project;
+
+ public static boolean isResourceBundle (String fileName) {
+ return fileName.toLowerCase().endsWith(".properties");
+ }
+
+ public static boolean isGlossary (String fileName) {
+ return fileName.toLowerCase().endsWith(".xml");
+ }
+
+ public static IWorkspace getWorkspace () {
+ if (workspace == null) {
+ workspace = ResourcesPlugin.getWorkspace();
+ }
+
+ return workspace;
+ }
+
+ public static IProject getProject () throws CoreException {
+ if (project == null) {
+ project = getWorkspace().getRoot().getProject("ExternalResourceBundles");
+ }
+
+ if (!project.exists())
+ project.create(null);
+ if (!project.isOpen())
+ project.open(null);
+
+ return project;
+ }
+
+ public static void prePareEditorInputs () {
+ IWorkspace workspace = getWorkspace();
+ }
+
+ public static IFile getResourceBundleRef (String location) throws CoreException {
+ IPath path = new Path (location);
+
+ /** Create all files of the Resource-Bundle within the project space and link them to the original file */
+ String regex = getPropertiesFileRegEx(path);
+ String projPathName = toProjectRelativePathName(path);
+ IFile file = getProject().getFile(projPathName);
+ file.createLink(path, IResource.REPLACE, null);
+
+ File parentDir = new File (path.toFile().getParent());
+ String[] files = parentDir.list();
+
+ for (String fn : files) {
+ File fo = new File (parentDir, fn);
+ if (!fo.isFile())
+ continue;
+
+ IPath newFilePath = new Path(fo.getAbsolutePath());
+ if (fo.getName().matches(regex) && !path.toFile().getName().equals(newFilePath.toFile().getName())) {
+ IFile newFile = project.getFile(toProjectRelativePathName(newFilePath));
+ newFile.createLink(newFilePath, IResource.REPLACE, null);
+ }
+ }
+
+ return file;
+ }
+
+ protected static String toProjectRelativePathName (IPath path) {
+ String projectRelativeName = "";
+
+ projectRelativeName = path.toString().replaceAll(":", "");
+ projectRelativeName = projectRelativeName.replaceAll("/", ".");
+
+ return projectRelativeName;
+ }
+
+ protected static String getPropertiesFileRegEx(IPath file) {
+ String bundleName = getBundleName(file);
+ return PROPERTIES_FILE_REGEX.replaceFirst(
+ TOKEN_BUNDLE_NAME, bundleName).replaceFirst(
+ TOKEN_FILE_EXTENSION, file.getFileExtension());
+ }
+
+ public static String getBundleName(IPath file) {
+ String name = file.toFile().getName();
+ String regex = "^(.*?)" //$NON-NLS-1$
+ + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})"
+ + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\."
+ + file.getFileExtension() + ")$";
+ return name.replaceFirst(regex, "$1");
+ }
+
+ public static String queryFileName(Shell shell, String title, int dialogOptions, String[] endings) {
+ FileDialog dialog= new FileDialog(shell, dialogOptions);
+ dialog.setText( title );
+ dialog.setFilterExtensions(endings);
+ String path= dialog.open();
+
+
+ if (path != null && path.length() > 0)
+ return path;
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
index 92764ce8..cfddb70c 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java
@@ -1,80 +1,87 @@
-package org.eclipselabs.tapiji.translator.utils;
-
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipselabs.tapiji.translator.Activator;
-
-
-public class FontUtils {
-
- /**
- * Gets a system color.
- * @param colorId SWT constant
- * @return system color
- */
- public static Color getSystemColor(int colorId) {
- return Activator.getDefault().getWorkbench()
- .getDisplay().getSystemColor(colorId);
- }
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style (size is unaffected).
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(Control control, int style) {
- //TODO consider dropping in favor of control-less version?
- return createFont(control, style, 0);
- }
-
-
- /**
- * Creates a font by altering the font associated with the given control
- * and applying the provided style and relative size.
- * @param control control we base our font data on
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(Control control, int style, int relSize) {
- //TODO consider dropping in favor of control-less version?
- FontData[] fontData = control.getFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(control.getDisplay(), fontData);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @return newly created font
- */
- public static Font createFont(int style) {
- return createFont(style, 0);
- }
-
- /**
- * Creates a font by altering the system font
- * and applying the provided style and relative size.
- * @param style style to apply to the new font
- * @param relSize size to add or remove from the control size
- * @return newly created font
- */
- public static Font createFont(int style, int relSize) {
- Display display = Activator.getDefault().getWorkbench().getDisplay();
- FontData[] fontData = display.getSystemFont().getFontData();
- for (int i = 0; i < fontData.length; i++) {
- fontData[i].setHeight(fontData[i].getHeight() + relSize);
- fontData[i].setStyle(style);
- }
- return new Font(display, fontData);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.utils;
+
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipselabs.tapiji.translator.Activator;
+
+
+public class FontUtils {
+
+ /**
+ * Gets a system color.
+ * @param colorId SWT constant
+ * @return system color
+ */
+ public static Color getSystemColor(int colorId) {
+ return Activator.getDefault().getWorkbench()
+ .getDisplay().getSystemColor(colorId);
+ }
+
+ /**
+ * Creates a font by altering the font associated with the given control
+ * and applying the provided style (size is unaffected).
+ * @param control control we base our font data on
+ * @param style style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style) {
+ //TODO consider dropping in favor of control-less version?
+ return createFont(control, style, 0);
+ }
+
+
+ /**
+ * Creates a font by altering the font associated with the given control
+ * and applying the provided style and relative size.
+ * @param control control we base our font data on
+ * @param style style to apply to the new font
+ * @param relSize size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(Control control, int style, int relSize) {
+ //TODO consider dropping in favor of control-less version?
+ FontData[] fontData = control.getFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(control.getDisplay(), fontData);
+ }
+
+ /**
+ * Creates a font by altering the system font
+ * and applying the provided style and relative size.
+ * @param style style to apply to the new font
+ * @return newly created font
+ */
+ public static Font createFont(int style) {
+ return createFont(style, 0);
+ }
+
+ /**
+ * Creates a font by altering the system font
+ * and applying the provided style and relative size.
+ * @param style style to apply to the new font
+ * @param relSize size to add or remove from the control size
+ * @return newly created font
+ */
+ public static Font createFont(int style, int relSize) {
+ Display display = Activator.getDefault().getWorkbench().getDisplay();
+ FontData[] fontData = display.getSystemFont().getFontData();
+ for (int i = 0; i < fontData.length; i++) {
+ fontData[i].setHeight(fontData[i].getHeight() + relSize);
+ fontData[i].setStyle(style);
+ }
+ return new Font(display, fontData);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java
index 793a9913..47549301 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java
@@ -1,3 +1,10 @@
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
package org.eclipselabs.tapiji.translator.views;
@@ -664,4 +671,4 @@ public void glossaryLoaded(LoadGlossaryEvent event) {
"Cannot open Glossary", "The choosen file does not represent a valid Glossary!");
}
}
-}
\ No newline at end of file
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
index cd0a4536..fda93b86 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
@@ -1,29 +1,36 @@
-package org.eclipselabs.tapiji.translator.views.dialog;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-public class LocaleContentProvider implements IStructuredContentProvider {
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
-
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof List) {
- List<Locale> locales = (List<Locale>) inputElement;
- return locales.toArray(new Locale[locales.size()]);
- }
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.dialog;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+public class LocaleContentProvider implements IStructuredContentProvider {
+
+ @Override
+ public void dispose() {
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof List) {
+ List<Locale> locales = (List<Locale>) inputElement;
+ return locales.toArray(new Locale[locales.size()]);
+ }
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
index 6ba650a1..60002ded 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
@@ -1,45 +1,52 @@
-package org.eclipselabs.tapiji.translator.views.dialog;
-
-import java.util.Locale;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.swt.graphics.Image;
-
-public class LocaleLabelProvider implements ILabelProvider {
-
- @Override
- public void addListener(ILabelProviderListener listener) {
-
- }
-
- @Override
- public void dispose() {
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
-
- }
-
- @Override
- public Image getImage(Object element) {
- // TODO add image output for Locale entries
- return null;
- }
-
- @Override
- public String getText(Object element) {
- if (element != null && element instanceof Locale)
- return ((Locale)element).getDisplayName();
-
- return null;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.dialog;
+
+import java.util.Locale;
+
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.swt.graphics.Image;
+
+public class LocaleLabelProvider implements ILabelProvider {
+
+ @Override
+ public void addListener(ILabelProviderListener listener) {
+
+ }
+
+ @Override
+ public void dispose() {
+
+ }
+
+ @Override
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ @Override
+ public void removeListener(ILabelProviderListener listener) {
+
+ }
+
+ @Override
+ public Image getImage(Object element) {
+ // TODO add image output for Locale entries
+ return null;
+ }
+
+ @Override
+ public String getText(Object element) {
+ if (element != null && element instanceof Locale)
+ return ((Locale)element).getDisplayName();
+
+ return null;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
index 658ce20a..9d7d2551 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java
@@ -1,92 +1,99 @@
-package org.eclipselabs.tapiji.translator.views.menus;
-
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget;
-
-
-public class GlossaryEntryMenuContribution extends ContributionItem implements
- ISelectionChangedListener {
-
- private GlossaryWidget parentView;
- private boolean legalSelection = false;
-
- // Menu-Items
- private MenuItem addItem;
- private MenuItem removeItem;
-
- public GlossaryEntryMenuContribution () {
- }
-
- public GlossaryEntryMenuContribution (GlossaryWidget view, boolean legalSelection) {
- this.legalSelection = legalSelection;
- this.parentView = view;
- parentView.addSelectionChangedListener(this);
- }
-
- @Override
- public void fill(Menu menu, int index) {
-
- // MenuItem for adding a new entry
- addItem = new MenuItem(menu, SWT.NONE, index);
- addItem.setText("Add ...");
- addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
- addItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.addNewItem();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
-
- if ((parentView == null && legalSelection) || parentView != null) {
- // MenuItem for deleting the currently selected entry
- removeItem = new MenuItem(menu, SWT.NONE, index + 1);
- removeItem.setText("Remove");
- removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
- .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
- .createImage());
- removeItem.addSelectionListener( new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- parentView.deleteSelectedItems();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
-
- }
- });
- enableMenuItems();
- }
- }
-
- protected void enableMenuItems() {
- try {
- removeItem.setEnabled(legalSelection);
- } catch (Exception e) {
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- legalSelection = !event.getSelection().isEmpty();
-// enableMenuItems ();
- }
-
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.menus;
+
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget;
+
+
+public class GlossaryEntryMenuContribution extends ContributionItem implements
+ ISelectionChangedListener {
+
+ private GlossaryWidget parentView;
+ private boolean legalSelection = false;
+
+ // Menu-Items
+ private MenuItem addItem;
+ private MenuItem removeItem;
+
+ public GlossaryEntryMenuContribution () {
+ }
+
+ public GlossaryEntryMenuContribution (GlossaryWidget view, boolean legalSelection) {
+ this.legalSelection = legalSelection;
+ this.parentView = view;
+ parentView.addSelectionChangedListener(this);
+ }
+
+ @Override
+ public void fill(Menu menu, int index) {
+
+ // MenuItem for adding a new entry
+ addItem = new MenuItem(menu, SWT.NONE, index);
+ addItem.setText("Add ...");
+ addItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage());
+ addItem.addSelectionListener( new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.addNewItem();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+
+ if ((parentView == null && legalSelection) || parentView != null) {
+ // MenuItem for deleting the currently selected entry
+ removeItem = new MenuItem(menu, SWT.NONE, index + 1);
+ removeItem.setText("Remove");
+ removeItem.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)
+ .createImage());
+ removeItem.addSelectionListener( new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ parentView.deleteSelectedItems();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+
+ }
+ });
+ enableMenuItems();
+ }
+ }
+
+ protected void enableMenuItems() {
+ try {
+ removeItem.setEnabled(legalSelection);
+ } catch (Exception e) {
+ }
+ }
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ legalSelection = !event.getSelection().isEmpty();
+// enableMenuItems ();
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
index fe5d4b84..bff167cf 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
@@ -1,630 +1,637 @@
-package org.eclipselabs.tapiji.translator.views.widgets;
-
-import java.awt.ComponentOrientation;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.layout.TreeColumnLayout;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDragSource;
-import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDropTarget;
-import org.eclipselabs.tapiji.translator.views.widgets.dnd.TermTransfer;
-import org.eclipselabs.tapiji.translator.views.widgets.filter.ExactMatcher;
-import org.eclipselabs.tapiji.translator.views.widgets.filter.FuzzyMatcher;
-import org.eclipselabs.tapiji.translator.views.widgets.filter.SelectiveMatcher;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryLabelProvider;
-import org.eclipselabs.tapiji.translator.views.widgets.sorter.GlossaryEntrySorter;
-import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
-
-
-public class GlossaryWidget extends Composite implements IResourceChangeListener {
-
- private final int TERM_COLUMN_WEIGHT = 1;
- private final int DESCRIPTION_COLUMN_WEIGHT = 1;
-
- private boolean editable;
-
- private IWorkbenchPartSite site;
- private TreeColumnLayout basicLayout;
- private TreeViewer treeViewer;
- private TreeColumn termColumn;
- private boolean grouped = true;
- private boolean fuzzyMatchingEnabled = false;
- private boolean selectiveViewEnabled = false;
- private float matchingPrecision = .75f;
- private String referenceLocale;
- private List<String> displayedTranslations;
- private String[] translationsToDisplay;
-
- private SortInfo sortInfo;
- private Glossary glossary;
- private GlossaryManager manager;
-
- private GlossaryContentProvider contentProvider;
- private GlossaryLabelProvider labelProvider;
-
- /*** MATCHER ***/
- ExactMatcher matcher;
-
- /*** SORTER ***/
- GlossaryEntrySorter sorter;
-
- /*** ACTIONS ***/
- private Action doubleClickAction;
-
- public GlossaryWidget(IWorkbenchPartSite site,
- Composite parent, int style, GlossaryManager manager, String refLang, List<String> dls) {
- super(parent, style);
- this.site = site;
-
- if (manager != null) {
- this.manager = manager;
- this.glossary = manager.getGlossary();
-
- if (refLang != null)
- this.referenceLocale = refLang;
- else
- this.referenceLocale = glossary.info.getTranslations()[0];
-
- if (dls != null)
- this.translationsToDisplay = dls.toArray(new String[dls.size()]);
- else
- this.translationsToDisplay = glossary.info.getTranslations();
- }
-
- constructWidget();
-
- if (this.glossary!= null) {
- initTreeViewer();
- initMatchers();
- initSorters();
- }
-
- hookDragAndDrop();
- registerListeners();
- }
-
- protected void registerListeners() {
- treeViewer.getControl().addKeyListener(new KeyAdapter() {
- public void keyPressed (KeyEvent event) {
- if (event.character == SWT.DEL &&
- event.stateMask == 0) {
- deleteSelectedItems();
- }
- }
- });
-
- // Listen resource changes
- ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
- }
-
- protected void initSorters() {
- sorter = new GlossaryEntrySorter(treeViewer, sortInfo, glossary.getIndexOfLocale (referenceLocale), glossary.info.translations);
- treeViewer.setSorter(sorter);
- }
-
- public void enableFuzzyMatching(boolean enable) {
- String pattern = "";
- if (matcher != null) {
- pattern = matcher.getPattern();
-
- if (!fuzzyMatchingEnabled && enable) {
- if (matcher.getPattern().trim().length() > 1
- && matcher.getPattern().startsWith("*")
- && matcher.getPattern().endsWith("*"))
- pattern = pattern.substring(1).substring(0,
- pattern.length() - 2);
- matcher.setPattern(null);
- }
- }
- fuzzyMatchingEnabled = enable;
- initMatchers();
-
- matcher.setPattern(pattern);
- treeViewer.refresh();
- }
-
- public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
- }
-
- protected void initMatchers() {
- treeViewer.resetFilters();
-
- String patternBefore = matcher != null ? matcher.getPattern() : "";
-
- if (fuzzyMatchingEnabled) {
- matcher = new FuzzyMatcher(treeViewer);
- ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
- } else
- matcher = new ExactMatcher(treeViewer);
-
- matcher.setPattern(patternBefore);
-
- if (this.selectiveViewEnabled)
- new SelectiveMatcher(treeViewer, site.getPage());
- }
-
- protected void initTreeViewer() {
- // init content provider
- contentProvider = new GlossaryContentProvider( this.glossary );
- treeViewer.setContentProvider(contentProvider);
-
- // init label provider
- labelProvider = new GlossaryLabelProvider(this.displayedTranslations.indexOf(referenceLocale), this.displayedTranslations, site.getPage());
- treeViewer.setLabelProvider(labelProvider);
-
- setTreeStructure(grouped);
- }
-
- public void setTreeStructure(boolean grouped) {
- this.grouped = grouped;
- ((GlossaryContentProvider)treeViewer.getContentProvider()).setGrouped(this.grouped);
- if (treeViewer.getInput() == null)
- treeViewer.setUseHashlookup(false);
- treeViewer.setInput(this.glossary);
- treeViewer.refresh();
- }
-
- protected void constructWidget() {
- basicLayout = new TreeColumnLayout();
- this.setLayout(basicLayout);
-
- treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE
- | SWT.BORDER);
- Tree tree = treeViewer.getTree();
-
- if (glossary != null) {
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
-
- // create tree-columns
- constructTreeColumns(tree);
- } else {
- tree.setHeaderVisible(false);
- tree.setLinesVisible(false);
- }
-
- makeActions();
- hookDoubleClickAction();
-
- // register messages table as selection provider
- site.setSelectionProvider(treeViewer);
- }
-
- /**
- * Gets the orientation suited for a given locale.
- * @param locale the locale
- * @return <code>SWT.RIGHT_TO_LEFT</code> or <code>SWT.LEFT_TO_RIGHT</code>
- */
- private int getOrientation(Locale locale){
- if(locale!=null){
- ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
- if(orientation==ComponentOrientation.RIGHT_TO_LEFT){
- return SWT.RIGHT_TO_LEFT;
- }
- }
- return SWT.LEFT_TO_RIGHT;
- }
-
- protected void constructTreeColumns(Tree tree) {
- tree.removeAll();
- if (this.displayedTranslations == null)
- this.displayedTranslations = new ArrayList <String>();
-
- this.displayedTranslations.clear();
-
- /** Reference term */
- String[] refDef = referenceLocale.split("_");
- Locale l = refDef.length < 3 ? (refDef.length < 2 ? new Locale (refDef[0]) : new Locale(refDef[0], refDef[1])) : new Locale (refDef[0], refDef[1], refDef[2]);
-
- this.displayedTranslations.add(referenceLocale);
- termColumn = new TreeColumn(tree, SWT.RIGHT_TO_LEFT/*getOrientation(l)*/);
-
- termColumn.setText(l.getDisplayName());
- TreeViewerColumn termCol = new TreeViewerColumn(treeViewer, termColumn);
- termCol.setEditingSupport(new EditingSupport(treeViewer) {
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- if (element instanceof Term) {
- Term term = (Term) element;
- Translation translation = (Translation) term.getTranslation(referenceLocale);
-
- if (translation != null) {
- translation.value = (String) value;
- Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
- manager.setGlossary(gl);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- treeViewer.refresh();
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, 0);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer
- .getControl();
- editor = new TextCellEditor(tree);
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
- termColumn.addSelectionListener(new SelectionListener() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(0);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(0);
- }
- });
- basicLayout.setColumnData(termColumn, new ColumnWeightData(
- TERM_COLUMN_WEIGHT));
-
-
- /** Translations */
- String[] allLocales = this.translationsToDisplay;
-
- int iCol = 1;
- for (String locale : allLocales) {
- final int ifCall = iCol;
- final String sfLocale = locale;
- if (locale.equalsIgnoreCase(this.referenceLocale))
- continue;
-
- // trac the rendered translation
- this.displayedTranslations.add(locale);
-
- String [] locDef = locale.split("_");
- l = locDef.length < 3 ? (locDef.length < 2 ? new Locale (locDef[0]) : new Locale(locDef[0], locDef[1])) : new Locale (locDef[0], locDef[1], locDef[2]);
-
- // Add editing support to this table column
- TreeColumn descriptionColumn = new TreeColumn(tree, SWT.NONE);
- TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, descriptionColumn);
- tCol.setEditingSupport(new EditingSupport(treeViewer) {
- TextCellEditor editor = null;
-
- @Override
- protected void setValue(Object element, Object value) {
- if (element instanceof Term) {
- Term term = (Term) element;
- Translation translation = (Translation) term.getTranslation(sfLocale);
-
- if (translation != null) {
- translation.value = (String) value;
- Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
- manager.setGlossary(gl);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- treeViewer.refresh();
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- return labelProvider.getColumnText(element, ifCall);
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- if (editor == null) {
- Composite tree = (Composite) treeViewer
- .getControl();
- editor = new TextCellEditor(tree);
- }
- return editor;
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return editable;
- }
- });
-
- descriptionColumn.setText(l.getDisplayName());
- descriptionColumn.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateSorter(ifCall);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- updateSorter(ifCall);
- }
- });
- basicLayout.setColumnData(descriptionColumn, new ColumnWeightData(
- DESCRIPTION_COLUMN_WEIGHT));
- iCol ++;
- }
-
- }
-
- protected void updateSorter(int idx) {
- SortInfo sortInfo = sorter.getSortInfo();
- if (idx == sortInfo.getColIdx())
- sortInfo.setDESC(!sortInfo.isDESC());
- else {
- sortInfo.setColIdx(idx);
- sortInfo.setDESC(false);
- }
- sorter.setSortInfo(sortInfo);
- setTreeStructure(idx == 0);
- treeViewer.refresh();
- }
-
- @Override
- public boolean setFocus() {
- return treeViewer.getControl().setFocus();
- }
-
- /*** DRAG AND DROP ***/
- protected void hookDragAndDrop() {
- GlossaryDragSource source = new GlossaryDragSource(treeViewer, manager);
- GlossaryDropTarget target = new GlossaryDropTarget(treeViewer, manager);
-
- // Initialize drag source for copy event
- DragSource dragSource = new DragSource(treeViewer.getControl(),
- DND.DROP_MOVE);
- dragSource.setTransfer(new Transfer[] { TermTransfer.getInstance() });
- dragSource.addDragListener(source);
-
- // Initialize drop target for copy event
- DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
- DND.DROP_MOVE);
- dropTarget.setTransfer(new Transfer[] { TermTransfer.getInstance() });
- dropTarget.addDropListener(target);
- }
-
- /*** ACTIONS ***/
-
- private void makeActions() {
- doubleClickAction = new Action() {
-
- @Override
- public void run() {
- // implement the cell edit event
- }
-
- };
- }
-
- private void hookDoubleClickAction() {
- treeViewer.addDoubleClickListener(new IDoubleClickListener() {
- public void doubleClick(DoubleClickEvent event) {
- doubleClickAction.run();
- }
- });
- }
-
- /*** SELECTION LISTENER ***/
-
-
- private void refreshViewer() {
- treeViewer.refresh();
- }
-
- public StructuredViewer getViewer() {
- return this.treeViewer;
- }
-
- public void setSearchString(String pattern) {
- matcher.setPattern(pattern);
- if (matcher.getPattern().trim().length() > 0)
- grouped = false;
- else
- grouped = true;
- labelProvider.setSearchEnabled(!grouped);
- this.setTreeStructure(grouped && sorter != null && sorter.getSortInfo().getColIdx() == 0);
- treeViewer.refresh();
- }
-
- public SortInfo getSortInfo() {
- if (this.sorter != null)
- return this.sorter.getSortInfo();
- else
- return null;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- if (sorter != null) {
- sorter.setSortInfo(sortInfo);
- setTreeStructure(sortInfo.getColIdx() == 0);
- treeViewer.refresh();
- }
- }
-
- public String getSearchString() {
- return matcher.getPattern();
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public void deleteSelectedItems() {
- List<String> ids = new ArrayList<String>();
- this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
-
- ISelection selection = site.getSelectionProvider().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof Term) {
- this.glossary.removeTerm ((Term)elem);
- this.manager.setGlossary(this.glossary);
- try {
- this.manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- this.refreshViewer();
- }
-
- public void addNewItem() {
- // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
- Term parentTerm = null;
-
- ISelection selection = site.getSelectionProvider().getSelection();
- if (selection instanceof IStructuredSelection) {
- for (Iterator<?> iter = ((IStructuredSelection) selection)
- .iterator(); iter.hasNext();) {
- Object elem = iter.next();
- if (elem instanceof Term) {
- parentTerm = ((Term) elem);
- break;
- }
- }
- }
-
- InputDialog dialog = new InputDialog (this.getShell(), "Neuer Begriff",
- "Please, define the new term:", "", null);
-
- if (dialog.open() == InputDialog.OK) {
- if (dialog.getValue() != null && dialog.getValue().trim().length() > 0) {
- this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
-
- // Construct a new term
- Term newTerm = new Term();
- Translation defaultTranslation = new Translation ();
- defaultTranslation.id = referenceLocale;
- defaultTranslation.value = dialog.getValue();
- newTerm.translations.add(defaultTranslation);
-
- this.glossary.addTerm (parentTerm, newTerm);
-
- this.manager.setGlossary(this.glossary);
- try {
- this.manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- this.refreshViewer();
- }
-
- public void setMatchingPrecision(float value) {
- matchingPrecision = value;
- if (matcher instanceof FuzzyMatcher) {
- ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
- treeViewer.refresh();
- }
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- public Control getControl() {
- return treeViewer.getControl();
- }
-
- public Glossary getGlossary () {
- return this.glossary;
- }
-
- public void addSelectionChangedListener(
- ISelectionChangedListener listener) {
- treeViewer.addSelectionChangedListener(listener);
- }
-
- public String getReferenceLanguage() {
- return referenceLocale;
- }
-
- public void setReferenceLanguage (String lang) {
- this.referenceLocale = lang;
- }
-
- public void bindContentToSelection(boolean enable) {
- this.selectiveViewEnabled = enable;
- initMatchers();
- }
-
- public boolean isSelectiveViewEnabled() {
- return selectiveViewEnabled;
- }
-
- @Override
- public void dispose() {
- super.dispose();
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- }
-
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- initMatchers();
- this.refreshViewer();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets;
+
+import java.awt.ComponentOrientation;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.jface.layout.TreeColumnLayout;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ColumnWeightData;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSource;
+import org.eclipse.swt.dnd.DropTarget;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeColumn;
+import org.eclipse.ui.IWorkbenchPartSite;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDragSource;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.GlossaryDropTarget;
+import org.eclipselabs.tapiji.translator.views.widgets.dnd.TermTransfer;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.ExactMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.FuzzyMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.SelectiveMatcher;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryLabelProvider;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.GlossaryEntrySorter;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
+
+
+public class GlossaryWidget extends Composite implements IResourceChangeListener {
+
+ private final int TERM_COLUMN_WEIGHT = 1;
+ private final int DESCRIPTION_COLUMN_WEIGHT = 1;
+
+ private boolean editable;
+
+ private IWorkbenchPartSite site;
+ private TreeColumnLayout basicLayout;
+ private TreeViewer treeViewer;
+ private TreeColumn termColumn;
+ private boolean grouped = true;
+ private boolean fuzzyMatchingEnabled = false;
+ private boolean selectiveViewEnabled = false;
+ private float matchingPrecision = .75f;
+ private String referenceLocale;
+ private List<String> displayedTranslations;
+ private String[] translationsToDisplay;
+
+ private SortInfo sortInfo;
+ private Glossary glossary;
+ private GlossaryManager manager;
+
+ private GlossaryContentProvider contentProvider;
+ private GlossaryLabelProvider labelProvider;
+
+ /*** MATCHER ***/
+ ExactMatcher matcher;
+
+ /*** SORTER ***/
+ GlossaryEntrySorter sorter;
+
+ /*** ACTIONS ***/
+ private Action doubleClickAction;
+
+ public GlossaryWidget(IWorkbenchPartSite site,
+ Composite parent, int style, GlossaryManager manager, String refLang, List<String> dls) {
+ super(parent, style);
+ this.site = site;
+
+ if (manager != null) {
+ this.manager = manager;
+ this.glossary = manager.getGlossary();
+
+ if (refLang != null)
+ this.referenceLocale = refLang;
+ else
+ this.referenceLocale = glossary.info.getTranslations()[0];
+
+ if (dls != null)
+ this.translationsToDisplay = dls.toArray(new String[dls.size()]);
+ else
+ this.translationsToDisplay = glossary.info.getTranslations();
+ }
+
+ constructWidget();
+
+ if (this.glossary!= null) {
+ initTreeViewer();
+ initMatchers();
+ initSorters();
+ }
+
+ hookDragAndDrop();
+ registerListeners();
+ }
+
+ protected void registerListeners() {
+ treeViewer.getControl().addKeyListener(new KeyAdapter() {
+ public void keyPressed (KeyEvent event) {
+ if (event.character == SWT.DEL &&
+ event.stateMask == 0) {
+ deleteSelectedItems();
+ }
+ }
+ });
+
+ // Listen resource changes
+ ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
+ }
+
+ protected void initSorters() {
+ sorter = new GlossaryEntrySorter(treeViewer, sortInfo, glossary.getIndexOfLocale (referenceLocale), glossary.info.translations);
+ treeViewer.setSorter(sorter);
+ }
+
+ public void enableFuzzyMatching(boolean enable) {
+ String pattern = "";
+ if (matcher != null) {
+ pattern = matcher.getPattern();
+
+ if (!fuzzyMatchingEnabled && enable) {
+ if (matcher.getPattern().trim().length() > 1
+ && matcher.getPattern().startsWith("*")
+ && matcher.getPattern().endsWith("*"))
+ pattern = pattern.substring(1).substring(0,
+ pattern.length() - 2);
+ matcher.setPattern(null);
+ }
+ }
+ fuzzyMatchingEnabled = enable;
+ initMatchers();
+
+ matcher.setPattern(pattern);
+ treeViewer.refresh();
+ }
+
+ public boolean isFuzzyMatchingEnabled() {
+ return fuzzyMatchingEnabled;
+ }
+
+ protected void initMatchers() {
+ treeViewer.resetFilters();
+
+ String patternBefore = matcher != null ? matcher.getPattern() : "";
+
+ if (fuzzyMatchingEnabled) {
+ matcher = new FuzzyMatcher(treeViewer);
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision);
+ } else
+ matcher = new ExactMatcher(treeViewer);
+
+ matcher.setPattern(patternBefore);
+
+ if (this.selectiveViewEnabled)
+ new SelectiveMatcher(treeViewer, site.getPage());
+ }
+
+ protected void initTreeViewer() {
+ // init content provider
+ contentProvider = new GlossaryContentProvider( this.glossary );
+ treeViewer.setContentProvider(contentProvider);
+
+ // init label provider
+ labelProvider = new GlossaryLabelProvider(this.displayedTranslations.indexOf(referenceLocale), this.displayedTranslations, site.getPage());
+ treeViewer.setLabelProvider(labelProvider);
+
+ setTreeStructure(grouped);
+ }
+
+ public void setTreeStructure(boolean grouped) {
+ this.grouped = grouped;
+ ((GlossaryContentProvider)treeViewer.getContentProvider()).setGrouped(this.grouped);
+ if (treeViewer.getInput() == null)
+ treeViewer.setUseHashlookup(false);
+ treeViewer.setInput(this.glossary);
+ treeViewer.refresh();
+ }
+
+ protected void constructWidget() {
+ basicLayout = new TreeColumnLayout();
+ this.setLayout(basicLayout);
+
+ treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE
+ | SWT.BORDER);
+ Tree tree = treeViewer.getTree();
+
+ if (glossary != null) {
+ tree.setHeaderVisible(true);
+ tree.setLinesVisible(true);
+
+ // create tree-columns
+ constructTreeColumns(tree);
+ } else {
+ tree.setHeaderVisible(false);
+ tree.setLinesVisible(false);
+ }
+
+ makeActions();
+ hookDoubleClickAction();
+
+ // register messages table as selection provider
+ site.setSelectionProvider(treeViewer);
+ }
+
+ /**
+ * Gets the orientation suited for a given locale.
+ * @param locale the locale
+ * @return <code>SWT.RIGHT_TO_LEFT</code> or <code>SWT.LEFT_TO_RIGHT</code>
+ */
+ private int getOrientation(Locale locale){
+ if(locale!=null){
+ ComponentOrientation orientation = ComponentOrientation.getOrientation(locale);
+ if(orientation==ComponentOrientation.RIGHT_TO_LEFT){
+ return SWT.RIGHT_TO_LEFT;
+ }
+ }
+ return SWT.LEFT_TO_RIGHT;
+ }
+
+ protected void constructTreeColumns(Tree tree) {
+ tree.removeAll();
+ if (this.displayedTranslations == null)
+ this.displayedTranslations = new ArrayList <String>();
+
+ this.displayedTranslations.clear();
+
+ /** Reference term */
+ String[] refDef = referenceLocale.split("_");
+ Locale l = refDef.length < 3 ? (refDef.length < 2 ? new Locale (refDef[0]) : new Locale(refDef[0], refDef[1])) : new Locale (refDef[0], refDef[1], refDef[2]);
+
+ this.displayedTranslations.add(referenceLocale);
+ termColumn = new TreeColumn(tree, SWT.RIGHT_TO_LEFT/*getOrientation(l)*/);
+
+ termColumn.setText(l.getDisplayName());
+ TreeViewerColumn termCol = new TreeViewerColumn(treeViewer, termColumn);
+ termCol.setEditingSupport(new EditingSupport(treeViewer) {
+ TextCellEditor editor = null;
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ if (element instanceof Term) {
+ Term term = (Term) element;
+ Translation translation = (Translation) term.getTranslation(referenceLocale);
+
+ if (translation != null) {
+ translation.value = (String) value;
+ Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
+ manager.setGlossary(gl);
+ try {
+ manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ treeViewer.refresh();
+ }
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ return labelProvider.getColumnText(element, 0);
+ }
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ if (editor == null) {
+ Composite tree = (Composite) treeViewer
+ .getControl();
+ editor = new TextCellEditor(tree);
+ }
+ return editor;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
+ termColumn.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(0);
+ }
+ });
+ basicLayout.setColumnData(termColumn, new ColumnWeightData(
+ TERM_COLUMN_WEIGHT));
+
+
+ /** Translations */
+ String[] allLocales = this.translationsToDisplay;
+
+ int iCol = 1;
+ for (String locale : allLocales) {
+ final int ifCall = iCol;
+ final String sfLocale = locale;
+ if (locale.equalsIgnoreCase(this.referenceLocale))
+ continue;
+
+ // trac the rendered translation
+ this.displayedTranslations.add(locale);
+
+ String [] locDef = locale.split("_");
+ l = locDef.length < 3 ? (locDef.length < 2 ? new Locale (locDef[0]) : new Locale(locDef[0], locDef[1])) : new Locale (locDef[0], locDef[1], locDef[2]);
+
+ // Add editing support to this table column
+ TreeColumn descriptionColumn = new TreeColumn(tree, SWT.NONE);
+ TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, descriptionColumn);
+ tCol.setEditingSupport(new EditingSupport(treeViewer) {
+ TextCellEditor editor = null;
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ if (element instanceof Term) {
+ Term term = (Term) element;
+ Translation translation = (Translation) term.getTranslation(sfLocale);
+
+ if (translation != null) {
+ translation.value = (String) value;
+ Glossary gl = ((GlossaryContentProvider)treeViewer.getContentProvider()).getGlossary();
+ manager.setGlossary(gl);
+ try {
+ manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ treeViewer.refresh();
+ }
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ return labelProvider.getColumnText(element, ifCall);
+ }
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ if (editor == null) {
+ Composite tree = (Composite) treeViewer
+ .getControl();
+ editor = new TextCellEditor(tree);
+ }
+ return editor;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ return editable;
+ }
+ });
+
+ descriptionColumn.setText(l.getDisplayName());
+ descriptionColumn.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateSorter(ifCall);
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ updateSorter(ifCall);
+ }
+ });
+ basicLayout.setColumnData(descriptionColumn, new ColumnWeightData(
+ DESCRIPTION_COLUMN_WEIGHT));
+ iCol ++;
+ }
+
+ }
+
+ protected void updateSorter(int idx) {
+ SortInfo sortInfo = sorter.getSortInfo();
+ if (idx == sortInfo.getColIdx())
+ sortInfo.setDESC(!sortInfo.isDESC());
+ else {
+ sortInfo.setColIdx(idx);
+ sortInfo.setDESC(false);
+ }
+ sorter.setSortInfo(sortInfo);
+ setTreeStructure(idx == 0);
+ treeViewer.refresh();
+ }
+
+ @Override
+ public boolean setFocus() {
+ return treeViewer.getControl().setFocus();
+ }
+
+ /*** DRAG AND DROP ***/
+ protected void hookDragAndDrop() {
+ GlossaryDragSource source = new GlossaryDragSource(treeViewer, manager);
+ GlossaryDropTarget target = new GlossaryDropTarget(treeViewer, manager);
+
+ // Initialize drag source for copy event
+ DragSource dragSource = new DragSource(treeViewer.getControl(),
+ DND.DROP_MOVE);
+ dragSource.setTransfer(new Transfer[] { TermTransfer.getInstance() });
+ dragSource.addDragListener(source);
+
+ // Initialize drop target for copy event
+ DropTarget dropTarget = new DropTarget(treeViewer.getControl(),
+ DND.DROP_MOVE);
+ dropTarget.setTransfer(new Transfer[] { TermTransfer.getInstance() });
+ dropTarget.addDropListener(target);
+ }
+
+ /*** ACTIONS ***/
+
+ private void makeActions() {
+ doubleClickAction = new Action() {
+
+ @Override
+ public void run() {
+ // implement the cell edit event
+ }
+
+ };
+ }
+
+ private void hookDoubleClickAction() {
+ treeViewer.addDoubleClickListener(new IDoubleClickListener() {
+ public void doubleClick(DoubleClickEvent event) {
+ doubleClickAction.run();
+ }
+ });
+ }
+
+ /*** SELECTION LISTENER ***/
+
+
+ private void refreshViewer() {
+ treeViewer.refresh();
+ }
+
+ public StructuredViewer getViewer() {
+ return this.treeViewer;
+ }
+
+ public void setSearchString(String pattern) {
+ matcher.setPattern(pattern);
+ if (matcher.getPattern().trim().length() > 0)
+ grouped = false;
+ else
+ grouped = true;
+ labelProvider.setSearchEnabled(!grouped);
+ this.setTreeStructure(grouped && sorter != null && sorter.getSortInfo().getColIdx() == 0);
+ treeViewer.refresh();
+ }
+
+ public SortInfo getSortInfo() {
+ if (this.sorter != null)
+ return this.sorter.getSortInfo();
+ else
+ return null;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ if (sorter != null) {
+ sorter.setSortInfo(sortInfo);
+ setTreeStructure(sortInfo.getColIdx() == 0);
+ treeViewer.refresh();
+ }
+ }
+
+ public String getSearchString() {
+ return matcher.getPattern();
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public void deleteSelectedItems() {
+ List<String> ids = new ArrayList<String>();
+ this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
+
+ ISelection selection = site.getSelectionProvider().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof Term) {
+ this.glossary.removeTerm ((Term)elem);
+ this.manager.setGlossary(this.glossary);
+ try {
+ this.manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ this.refreshViewer();
+ }
+
+ public void addNewItem() {
+ // event.feedback = DND.FEEDBACK_INSERT_BEFORE;
+ Term parentTerm = null;
+
+ ISelection selection = site.getSelectionProvider().getSelection();
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator<?> iter = ((IStructuredSelection) selection)
+ .iterator(); iter.hasNext();) {
+ Object elem = iter.next();
+ if (elem instanceof Term) {
+ parentTerm = ((Term) elem);
+ break;
+ }
+ }
+ }
+
+ InputDialog dialog = new InputDialog (this.getShell(), "Neuer Begriff",
+ "Please, define the new term:", "", null);
+
+ if (dialog.open() == InputDialog.OK) {
+ if (dialog.getValue() != null && dialog.getValue().trim().length() > 0) {
+ this.glossary = ((GlossaryContentProvider) treeViewer.getContentProvider()).getGlossary();
+
+ // Construct a new term
+ Term newTerm = new Term();
+ Translation defaultTranslation = new Translation ();
+ defaultTranslation.id = referenceLocale;
+ defaultTranslation.value = dialog.getValue();
+ newTerm.translations.add(defaultTranslation);
+
+ this.glossary.addTerm (parentTerm, newTerm);
+
+ this.manager.setGlossary(this.glossary);
+ try {
+ this.manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ this.refreshViewer();
+ }
+
+ public void setMatchingPrecision(float value) {
+ matchingPrecision = value;
+ if (matcher instanceof FuzzyMatcher) {
+ ((FuzzyMatcher) matcher).setMinimumSimilarity(value);
+ treeViewer.refresh();
+ }
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ public Control getControl() {
+ return treeViewer.getControl();
+ }
+
+ public Glossary getGlossary () {
+ return this.glossary;
+ }
+
+ public void addSelectionChangedListener(
+ ISelectionChangedListener listener) {
+ treeViewer.addSelectionChangedListener(listener);
+ }
+
+ public String getReferenceLanguage() {
+ return referenceLocale;
+ }
+
+ public void setReferenceLanguage (String lang) {
+ this.referenceLocale = lang;
+ }
+
+ public void bindContentToSelection(boolean enable) {
+ this.selectiveViewEnabled = enable;
+ initMatchers();
+ }
+
+ public boolean isSelectiveViewEnabled() {
+ return selectiveViewEnabled;
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
+ }
+
+ @Override
+ public void resourceChanged(IResourceChangeEvent event) {
+ initMatchers();
+ this.refreshViewer();
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
index 9456837b..6daea2d2 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java
@@ -1,57 +1,64 @@
-package org.eclipselabs.tapiji.translator.views.widgets.dnd;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-
-
-public class GlossaryDragSource implements DragSourceListener {
-
- private final TreeViewer source;
- private final GlossaryManager manager;
- private List<Term> selectionList;
-
- public GlossaryDragSource (TreeViewer sourceView, GlossaryManager manager) {
- source = sourceView;
- this.manager = manager;
- this.selectionList = new ArrayList<Term>();
- }
-
- @Override
- public void dragFinished(DragSourceEvent event) {
- GlossaryContentProvider contentProvider = ((GlossaryContentProvider) source.getContentProvider());
- Glossary glossary = contentProvider.getGlossary();
- for (Term selectionObject : selectionList)
- glossary.removeTerm(selectionObject);
- manager.setGlossary(glossary);
- this.source.refresh();
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void dragSetData(DragSourceEvent event) {
- selectionList = new ArrayList<Term> ();
- for (Object selectionObject : ((IStructuredSelection)source.getSelection()).toList())
- selectionList.add((Term) selectionObject);
-
- event.data = selectionList.toArray(new Term[selectionList.size()]);
- }
-
- @Override
- public void dragStart(DragSourceEvent event) {
- event.doit = !source.getSelection().isEmpty();
- }
-
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.DragSourceListener;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
+
+
+public class GlossaryDragSource implements DragSourceListener {
+
+ private final TreeViewer source;
+ private final GlossaryManager manager;
+ private List<Term> selectionList;
+
+ public GlossaryDragSource (TreeViewer sourceView, GlossaryManager manager) {
+ source = sourceView;
+ this.manager = manager;
+ this.selectionList = new ArrayList<Term>();
+ }
+
+ @Override
+ public void dragFinished(DragSourceEvent event) {
+ GlossaryContentProvider contentProvider = ((GlossaryContentProvider) source.getContentProvider());
+ Glossary glossary = contentProvider.getGlossary();
+ for (Term selectionObject : selectionList)
+ glossary.removeTerm(selectionObject);
+ manager.setGlossary(glossary);
+ this.source.refresh();
+ try {
+ manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void dragSetData(DragSourceEvent event) {
+ selectionList = new ArrayList<Term> ();
+ for (Object selectionObject : ((IStructuredSelection)source.getSelection()).toList())
+ selectionList.add((Term) selectionObject);
+
+ event.data = selectionList.toArray(new Term[selectionList.size()]);
+ }
+
+ @Override
+ public void dragStart(DragSourceEvent event) {
+ event.doit = !source.getSelection().isEmpty();
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
index 7f96ddd7..e23a3b6b 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java
@@ -1,71 +1,78 @@
-package org.eclipselabs.tapiji.translator.views.widgets.dnd;
-
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetAdapter;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipselabs.tapiji.translator.core.GlossaryManager;
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
-
-
-public class GlossaryDropTarget extends DropTargetAdapter {
- private final TreeViewer target;
- private final GlossaryManager manager;
-
- public GlossaryDropTarget (TreeViewer viewer, GlossaryManager manager) {
- super();
- this.target = viewer;
- this.manager = manager;
- }
-
- public void dragEnter (DropTargetEvent event) {
- if (event.detail == DND.DROP_MOVE || event.detail == DND.DROP_DEFAULT) {
- if ((event.operations & DND.DROP_MOVE) != 0)
- event.detail = DND.DROP_MOVE;
- else
- event.detail = DND.DROP_NONE;
- }
- }
-
- public void drop (DropTargetEvent event) {
- if (TermTransfer.getInstance().isSupportedType (event.currentDataType)) {
- Term parentTerm = null;
-
- event.detail = DND.DROP_MOVE;
- event.feedback = DND.FEEDBACK_INSERT_AFTER;
-
- if (event.item instanceof TreeItem &&
- ((TreeItem) event.item).getData() instanceof Term) {
- parentTerm = ((Term) ((TreeItem) event.item).getData());
- }
-
- Term[] moveTerm = (Term[]) event.data;
- Glossary glossary = ((GlossaryContentProvider) target.getContentProvider()).getGlossary();
-
- /* Remove the move term from its initial position
- for (Term selectionObject : moveTerm)
- glossary.removeTerm(selectionObject);*/
-
- /* Insert the move term on its target position */
- if (parentTerm == null) {
- for (Term t : moveTerm)
- glossary.terms.add(t);
- } else {
- for (Term t : moveTerm)
- parentTerm.subTerms.add(t);
- }
-
- manager.setGlossary(glossary);
- try {
- manager.saveGlossary();
- } catch (Exception e) {
- e.printStackTrace();
- }
- target.refresh();
- } else
- event.detail = DND.DROP_NONE;
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
+
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetAdapter;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipselabs.tapiji.translator.core.GlossaryManager;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider;
+
+
+public class GlossaryDropTarget extends DropTargetAdapter {
+ private final TreeViewer target;
+ private final GlossaryManager manager;
+
+ public GlossaryDropTarget (TreeViewer viewer, GlossaryManager manager) {
+ super();
+ this.target = viewer;
+ this.manager = manager;
+ }
+
+ public void dragEnter (DropTargetEvent event) {
+ if (event.detail == DND.DROP_MOVE || event.detail == DND.DROP_DEFAULT) {
+ if ((event.operations & DND.DROP_MOVE) != 0)
+ event.detail = DND.DROP_MOVE;
+ else
+ event.detail = DND.DROP_NONE;
+ }
+ }
+
+ public void drop (DropTargetEvent event) {
+ if (TermTransfer.getInstance().isSupportedType (event.currentDataType)) {
+ Term parentTerm = null;
+
+ event.detail = DND.DROP_MOVE;
+ event.feedback = DND.FEEDBACK_INSERT_AFTER;
+
+ if (event.item instanceof TreeItem &&
+ ((TreeItem) event.item).getData() instanceof Term) {
+ parentTerm = ((Term) ((TreeItem) event.item).getData());
+ }
+
+ Term[] moveTerm = (Term[]) event.data;
+ Glossary glossary = ((GlossaryContentProvider) target.getContentProvider()).getGlossary();
+
+ /* Remove the move term from its initial position
+ for (Term selectionObject : moveTerm)
+ glossary.removeTerm(selectionObject);*/
+
+ /* Insert the move term on its target position */
+ if (parentTerm == null) {
+ for (Term t : moveTerm)
+ glossary.terms.add(t);
+ } else {
+ for (Term t : moveTerm)
+ parentTerm.subTerms.add(t);
+ }
+
+ manager.setGlossary(glossary);
+ try {
+ manager.saveGlossary();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ target.refresh();
+ } else
+ event.detail = DND.DROP_NONE;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
index aa723853..ce50aaa7 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java
@@ -1,106 +1,113 @@
-package org.eclipselabs.tapiji.translator.views.widgets.dnd;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipselabs.tapiji.translator.model.Term;
-
-
-public class TermTransfer extends ByteArrayTransfer {
-
- private static final String TERM = "term";
-
- private static final int TYPEID = registerType(TERM);
-
- private static TermTransfer transfer = new TermTransfer();
-
- public static TermTransfer getInstance() {
- return transfer;
- }
-
- public void javaToNative(Object object, TransferData transferData) {
- if (!checkType(object) || !isSupportedType(transferData)) {
- DND.error(DND.ERROR_INVALID_DATA);
- }
- Term[] terms = (Term[]) object;
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ObjectOutputStream oOut = new ObjectOutputStream(out);
- for (int i = 0, length = terms.length; i < length; i++) {
- oOut.writeObject(terms[i]);
- }
- byte[] buffer = out.toByteArray();
- oOut.close();
-
- super.javaToNative(buffer, transferData);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public Object nativeToJava(TransferData transferData) {
- if (isSupportedType(transferData)) {
-
- byte[] buffer;
- try {
- buffer = (byte[]) super.nativeToJava(transferData);
- } catch (Exception e) {
- e.printStackTrace();
- buffer = null;
- }
- if (buffer == null)
- return null;
-
- List<Term> terms = new ArrayList<Term>();
- try {
- ByteArrayInputStream in = new ByteArrayInputStream(buffer);
- ObjectInputStream readIn = new ObjectInputStream(in);
- //while (readIn.available() > 0) {
- Term newTerm = (Term) readIn.readObject();
- terms.add(newTerm);
- //}
- readIn.close();
- } catch (Exception ex) {
- ex.printStackTrace();
- return null;
- }
- return terms.toArray(new Term[terms.size()]);
- }
-
- return null;
- }
-
- protected String[] getTypeNames() {
- return new String[] { TERM };
- }
-
- protected int[] getTypeIds() {
- return new int[] { TYPEID };
- }
-
- boolean checkType(Object object) {
- if (object == null || !(object instanceof Term[])
- || ((Term[]) object).length == 0) {
- return false;
- }
- Term[] myTypes = (Term[]) object;
- for (int i = 0; i < myTypes.length; i++) {
- if (myTypes[i] == null) {
- return false;
- }
- }
- return true;
- }
-
- protected boolean validate(Object object) {
- return checkType(object);
- }
-}
\ No newline at end of file
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.dnd;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.dnd.ByteArrayTransfer;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.TransferData;
+import org.eclipselabs.tapiji.translator.model.Term;
+
+
+public class TermTransfer extends ByteArrayTransfer {
+
+ private static final String TERM = "term";
+
+ private static final int TYPEID = registerType(TERM);
+
+ private static TermTransfer transfer = new TermTransfer();
+
+ public static TermTransfer getInstance() {
+ return transfer;
+ }
+
+ public void javaToNative(Object object, TransferData transferData) {
+ if (!checkType(object) || !isSupportedType(transferData)) {
+ DND.error(DND.ERROR_INVALID_DATA);
+ }
+ Term[] terms = (Term[]) object;
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ObjectOutputStream oOut = new ObjectOutputStream(out);
+ for (int i = 0, length = terms.length; i < length; i++) {
+ oOut.writeObject(terms[i]);
+ }
+ byte[] buffer = out.toByteArray();
+ oOut.close();
+
+ super.javaToNative(buffer, transferData);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public Object nativeToJava(TransferData transferData) {
+ if (isSupportedType(transferData)) {
+
+ byte[] buffer;
+ try {
+ buffer = (byte[]) super.nativeToJava(transferData);
+ } catch (Exception e) {
+ e.printStackTrace();
+ buffer = null;
+ }
+ if (buffer == null)
+ return null;
+
+ List<Term> terms = new ArrayList<Term>();
+ try {
+ ByteArrayInputStream in = new ByteArrayInputStream(buffer);
+ ObjectInputStream readIn = new ObjectInputStream(in);
+ //while (readIn.available() > 0) {
+ Term newTerm = (Term) readIn.readObject();
+ terms.add(newTerm);
+ //}
+ readIn.close();
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ return null;
+ }
+ return terms.toArray(new Term[terms.size()]);
+ }
+
+ return null;
+ }
+
+ protected String[] getTypeNames() {
+ return new String[] { TERM };
+ }
+
+ protected int[] getTypeIds() {
+ return new int[] { TYPEID };
+ }
+
+ boolean checkType(Object object) {
+ if (object == null || !(object instanceof Term[])
+ || ((Term[]) object).length == 0) {
+ return false;
+ }
+ Term[] myTypes = (Term[]) object;
+ for (int i = 0; i < myTypes.length; i++) {
+ if (myTypes[i] == null) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ protected boolean validate(Object object) {
+ return checkType(object);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
index 197aff7a..3227159b 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java
@@ -1,68 +1,75 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-
-
-public class ExactMatcher extends ViewerFilter {
-
- protected final StructuredViewer viewer;
- protected String pattern = "";
- protected StringMatcher matcher;
-
- public ExactMatcher (StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public String getPattern () {
- return pattern;
- }
-
- public void setPattern (String p) {
- boolean filtering = matcher != null;
- if (p != null && p.trim().length() > 0) {
- pattern = p;
- matcher = new StringMatcher ("*" + pattern + "*", true, false);
- if (!filtering)
- viewer.addFilter(this);
- else
- viewer.refresh();
- } else {
- pattern = "";
- matcher = null;
- if (filtering) {
- viewer.removeFilter(this);
- }
- }
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- Term term = (Term) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = false;
-
- // Iterate translations
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
- String locale = translation.id;
- if (matcher.match(value)) {
- filterInfo.addFoundInTranslation(locale);
- filterInfo.addSimilarity(locale, 1d);
- int start = -1;
- while ((start = value.toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
- filterInfo.addFoundInTranslationRange(locale, start, pattern.length());
- }
- selected = true;
- }
- }
-
- term.setInfo(filterInfo);
- return selected;
- }
-
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+
+public class ExactMatcher extends ViewerFilter {
+
+ protected final StructuredViewer viewer;
+ protected String pattern = "";
+ protected StringMatcher matcher;
+
+ public ExactMatcher (StructuredViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public String getPattern () {
+ return pattern;
+ }
+
+ public void setPattern (String p) {
+ boolean filtering = matcher != null;
+ if (p != null && p.trim().length() > 0) {
+ pattern = p;
+ matcher = new StringMatcher ("*" + pattern + "*", true, false);
+ if (!filtering)
+ viewer.addFilter(this);
+ else
+ viewer.refresh();
+ } else {
+ pattern = "";
+ matcher = null;
+ if (filtering) {
+ viewer.removeFilter(this);
+ }
+ }
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ Term term = (Term) element;
+ FilterInfo filterInfo = new FilterInfo();
+ boolean selected = false;
+
+ // Iterate translations
+ for (Translation translation : term.getAllTranslations()) {
+ String value = translation.value;
+ String locale = translation.id;
+ if (matcher.match(value)) {
+ filterInfo.addFoundInTranslation(locale);
+ filterInfo.addSimilarity(locale, 1d);
+ int start = -1;
+ while ((start = value.toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) {
+ filterInfo.addFoundInTranslationRange(locale, start, pattern.length());
+ }
+ selected = true;
+ }
+ }
+
+ term.setInfo(filterInfo);
+ return selected;
+ }
+
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
index ea3f05f6..5eb32ba5 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java
@@ -1,57 +1,64 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.jface.text.Region;
-
-public class FilterInfo {
-
- private List<String> foundInTranslation = new ArrayList<String> ();
- private Map<String, List<Region>> occurrences = new HashMap<String, List<Region>>();
- private Map<String, Double> localeSimilarity = new HashMap<String, Double>();
-
- public FilterInfo() {
-
- }
-
- public void addSimilarity (String l, Double similarity) {
- localeSimilarity.put (l, similarity);
- }
-
- public Double getSimilarityLevel (String l) {
- return localeSimilarity.get(l);
- }
-
- public void addFoundInTranslation (String loc) {
- foundInTranslation.add(loc);
- }
-
- public void removeFoundInTranslation (String loc) {
- foundInTranslation.remove(loc);
- }
-
- public void clearFoundInTranslation () {
- foundInTranslation.clear();
- }
-
- public boolean hasFoundInTranslation (String l) {
- return foundInTranslation.contains(l);
- }
-
- public List<Region> getFoundInTranslationRanges (String locale) {
- List<Region> reg = occurrences.get(locale);
- return (reg == null ? new ArrayList<Region>() : reg);
- }
-
- public void addFoundInTranslationRange (String locale, int start, int length) {
- List<Region> regions = occurrences.get(locale);
- if (regions == null)
- regions = new ArrayList<Region>();
- regions.add(new Region(start, length));
- occurrences.put(locale, regions);
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.jface.text.Region;
+
+public class FilterInfo {
+
+ private List<String> foundInTranslation = new ArrayList<String> ();
+ private Map<String, List<Region>> occurrences = new HashMap<String, List<Region>>();
+ private Map<String, Double> localeSimilarity = new HashMap<String, Double>();
+
+ public FilterInfo() {
+
+ }
+
+ public void addSimilarity (String l, Double similarity) {
+ localeSimilarity.put (l, similarity);
+ }
+
+ public Double getSimilarityLevel (String l) {
+ return localeSimilarity.get(l);
+ }
+
+ public void addFoundInTranslation (String loc) {
+ foundInTranslation.add(loc);
+ }
+
+ public void removeFoundInTranslation (String loc) {
+ foundInTranslation.remove(loc);
+ }
+
+ public void clearFoundInTranslation () {
+ foundInTranslation.clear();
+ }
+
+ public boolean hasFoundInTranslation (String l) {
+ return foundInTranslation.contains(l);
+ }
+
+ public List<Region> getFoundInTranslationRanges (String locale) {
+ List<Region> reg = occurrences.get(locale);
+ return (reg == null ? new ArrayList<Region>() : reg);
+ }
+
+ public void addFoundInTranslationRange (String locale, int start, int length) {
+ List<Region> regions = occurrences.get(locale);
+ if (regions == null)
+ regions = new ArrayList<Region>();
+ regions.add(new Region(start, length));
+ occurrences.put(locale, regions);
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
index 0f904e46..79578016 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java
@@ -1,55 +1,62 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import org.eclipse.babel.editor.api.AnalyzerFactory;
-import org.eclipse.babel.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-
-public class FuzzyMatcher extends ExactMatcher {
-
- protected ILevenshteinDistanceAnalyzer lvda;
- protected float minimumSimilarity = 0.75f;
-
- public FuzzyMatcher(StructuredViewer viewer) {
- super(viewer);
- lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
- }
-
- public double getMinimumSimilarity () {
- return minimumSimilarity;
- }
-
- public void setMinimumSimilarity (float similarity) {
- this.minimumSimilarity = similarity;
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- boolean exactMatch = super.select(viewer, parentElement, element);
- boolean match = exactMatch;
-
- Term term = (Term) element;
-
- FilterInfo filterInfo = (FilterInfo) term.getInfo();
-
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
- String locale = translation.id;
- if (filterInfo.hasFoundInTranslation(locale))
- continue;
- double dist = lvda.analyse(value, getPattern());
- if (dist >= minimumSimilarity) {
- filterInfo.addFoundInTranslation(locale);
- filterInfo.addSimilarity(locale, dist);
- match = true;
- filterInfo.addFoundInTranslationRange(locale, 0, value.length());
- }
- }
-
- term.setInfo(filterInfo);
- return match;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import org.eclipse.babel.editor.api.AnalyzerFactory;
+import org.eclipse.babel.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+public class FuzzyMatcher extends ExactMatcher {
+
+ protected ILevenshteinDistanceAnalyzer lvda;
+ protected float minimumSimilarity = 0.75f;
+
+ public FuzzyMatcher(StructuredViewer viewer) {
+ super(viewer);
+ lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();
+ }
+
+ public double getMinimumSimilarity () {
+ return minimumSimilarity;
+ }
+
+ public void setMinimumSimilarity (float similarity) {
+ this.minimumSimilarity = similarity;
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ boolean exactMatch = super.select(viewer, parentElement, element);
+ boolean match = exactMatch;
+
+ Term term = (Term) element;
+
+ FilterInfo filterInfo = (FilterInfo) term.getInfo();
+
+ for (Translation translation : term.getAllTranslations()) {
+ String value = translation.value;
+ String locale = translation.id;
+ if (filterInfo.hasFoundInTranslation(locale))
+ continue;
+ double dist = lvda.analyse(value, getPattern());
+ if (dist >= minimumSimilarity) {
+ filterInfo.addFoundInTranslation(locale);
+ filterInfo.addSimilarity(locale, dist);
+ match = true;
+ filterInfo.addFoundInTranslationRange(locale, 0, value.length());
+ }
+ }
+
+ term.setInfo(filterInfo);
+ return match;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
index af80ec8d..4e4c9207 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java
@@ -1,95 +1,102 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import org.eclipse.babel.editor.api.EditorUtil;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-
-public class SelectiveMatcher extends ViewerFilter
- implements ISelectionListener, ISelectionChangedListener {
-
- protected final StructuredViewer viewer;
- protected String pattern = "";
- protected StringMatcher matcher;
- protected IKeyTreeNode selectedItem;
- protected IWorkbenchPage page;
-
- public SelectiveMatcher (StructuredViewer viewer, IWorkbenchPage page) {
- this.viewer = viewer;
- if (page.getActiveEditor() != null) {
- this.selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
- }
-
- this.page = page;
- page.getWorkbenchWindow().getSelectionService().addSelectionListener(this);
-
- viewer.addFilter(this);
- viewer.refresh();
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (selectedItem == null)
- return false;
-
- Term term = (Term) element;
- FilterInfo filterInfo = new FilterInfo();
- boolean selected = false;
-
- // Iterate translations
- for (Translation translation : term.getAllTranslations()) {
- String value = translation.value;
-
- if (value.trim().length() == 0)
- continue;
-
- String locale = translation.id;
-
- for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
- String ev = entry.getValue();
- String[] subValues = ev.split("[\\s\\p{Punct}]+");
- for (String v : subValues) {
- if (v.trim().equalsIgnoreCase(value.trim()))
- return true;
- }
- }
- }
-
- return false;
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- try {
- if (selection.isEmpty())
- return;
-
- if (!(selection instanceof IStructuredSelection))
- return;
-
- IStructuredSelection sel = (IStructuredSelection) selection;
- selectedItem = (IKeyTreeNode) sel.iterator().next();
- viewer.refresh();
- } catch (Exception e) { }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- event.getSelection();
- }
-
- public void dispose () {
- page.getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import org.eclipse.babel.editor.api.EditorUtil;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+public class SelectiveMatcher extends ViewerFilter
+ implements ISelectionListener, ISelectionChangedListener {
+
+ protected final StructuredViewer viewer;
+ protected String pattern = "";
+ protected StringMatcher matcher;
+ protected IKeyTreeNode selectedItem;
+ protected IWorkbenchPage page;
+
+ public SelectiveMatcher (StructuredViewer viewer, IWorkbenchPage page) {
+ this.viewer = viewer;
+ if (page.getActiveEditor() != null) {
+ this.selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
+ }
+
+ this.page = page;
+ page.getWorkbenchWindow().getSelectionService().addSelectionListener(this);
+
+ viewer.addFilter(this);
+ viewer.refresh();
+ }
+
+ @Override
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ if (selectedItem == null)
+ return false;
+
+ Term term = (Term) element;
+ FilterInfo filterInfo = new FilterInfo();
+ boolean selected = false;
+
+ // Iterate translations
+ for (Translation translation : term.getAllTranslations()) {
+ String value = translation.value;
+
+ if (value.trim().length() == 0)
+ continue;
+
+ String locale = translation.id;
+
+ for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
+ String ev = entry.getValue();
+ String[] subValues = ev.split("[\\s\\p{Punct}]+");
+ for (String v : subValues) {
+ if (v.trim().equalsIgnoreCase(value.trim()))
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public void selectionChanged(IWorkbenchPart part, ISelection selection) {
+ try {
+ if (selection.isEmpty())
+ return;
+
+ if (!(selection instanceof IStructuredSelection))
+ return;
+
+ IStructuredSelection sel = (IStructuredSelection) selection;
+ selectedItem = (IKeyTreeNode) sel.iterator().next();
+ viewer.refresh();
+ } catch (Exception e) { }
+ }
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ event.getSelection();
+ }
+
+ public void dispose () {
+ page.getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
index 337d2c9b..939f074f 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java
@@ -1,441 +1,448 @@
-package org.eclipselabs.tapiji.translator.views.widgets.filter;
-
-import java.util.Vector;
-
-/**
- * A string pattern matcher, suppporting "*" and "?" wildcards.
- */
-public class StringMatcher {
- protected String fPattern;
-
- protected int fLength; // pattern length
-
- protected boolean fIgnoreWildCards;
-
- protected boolean fIgnoreCase;
-
- protected boolean fHasLeadingStar;
-
- protected boolean fHasTrailingStar;
-
- protected String fSegments[]; //the given pattern is split into * separated segments
-
- /* boundary value beyond which we don't need to search in the text */
- protected int fBound = 0;
-
- protected static final char fSingleWildCard = '\u0000';
-
- public static class Position {
- int start; //inclusive
-
- int end; //exclusive
-
- public Position(int start, int end) {
- this.start = start;
- this.end = end;
- }
-
- public int getStart() {
- return start;
- }
-
- public int getEnd() {
- return end;
- }
- }
-
- /**
- * StringMatcher constructor takes in a String object that is a simple
- * pattern which may contain '*' for 0 and many characters and
- * '?' for exactly one character.
- *
- * Literal '*' and '?' characters must be escaped in the pattern
- * e.g., "\*" means literal "*", etc.
- *
- * Escaping any other character (including the escape character itself),
- * just results in that character in the pattern.
- * e.g., "\a" means "a" and "\\" means "\"
- *
- * If invoking the StringMatcher with string literals in Java, don't forget
- * escape characters are represented by "\\".
- *
- * @param pattern the pattern to match text against
- * @param ignoreCase if true, case is ignored
- * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
- * (everything is taken literally).
- */
- public StringMatcher(String pattern, boolean ignoreCase,
- boolean ignoreWildCards) {
- if (pattern == null) {
- throw new IllegalArgumentException();
- }
- fIgnoreCase = ignoreCase;
- fIgnoreWildCards = ignoreWildCards;
- fPattern = pattern;
- fLength = pattern.length();
-
- if (fIgnoreWildCards) {
- parseNoWildCards();
- } else {
- parseWildCards();
- }
- }
-
- /**
- * Find the first occurrence of the pattern between <code>start</code)(inclusive)
- * and <code>end</code>(exclusive).
- * @param text the String object to search in
- * @param start the starting index of the search range, inclusive
- * @param end the ending index of the search range, exclusive
- * @return an <code>StringMatcher.Position</code> object that keeps the starting
- * (inclusive) and ending positions (exclusive) of the first occurrence of the
- * pattern in the specified range of the text; return null if not found or subtext
- * is empty (start==end). A pair of zeros is returned if pattern is empty string
- * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
- * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
- */
- public StringMatcher.Position find(String text, int start, int end) {
- if (text == null) {
- throw new IllegalArgumentException();
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
- if (end < 0 || start >= end) {
- return null;
- }
- if (fLength == 0) {
- return new Position(start, start);
- }
- if (fIgnoreWildCards) {
- int x = posIn(text, start, end);
- if (x < 0) {
- return null;
- }
- return new Position(x, x + fLength);
- }
-
- int segCount = fSegments.length;
- if (segCount == 0) {
- return new Position(start, end);
- }
-
- int curPos = start;
- int matchStart = -1;
- int i;
- for (i = 0; i < segCount && curPos < end; ++i) {
- String current = fSegments[i];
- int nextMatch = regExpPosIn(text, curPos, end, current);
- if (nextMatch < 0) {
- return null;
- }
- if (i == 0) {
- matchStart = nextMatch;
- }
- curPos = nextMatch + current.length();
- }
- if (i < segCount) {
- return null;
- }
- return new Position(matchStart, curPos);
- }
-
- /**
- * match the given <code>text</code> with the pattern
- * @return true if matched otherwise false
- * @param text a String object
- */
- public boolean match(String text) {
- if(text == null) {
- return false;
- }
- return match(text, 0, text.length());
- }
-
- /**
- * Given the starting (inclusive) and the ending (exclusive) positions in the
- * <code>text</code>, determine if the given substring matches with aPattern
- * @return true if the specified portion of the text matches the pattern
- * @param text a String object that contains the substring to match
- * @param start marks the starting position (inclusive) of the substring
- * @param end marks the ending index (exclusive) of the substring
- */
- public boolean match(String text, int start, int end) {
- if (null == text) {
- throw new IllegalArgumentException();
- }
-
- if (start > end) {
- return false;
- }
-
- if (fIgnoreWildCards) {
- return (end - start == fLength)
- && fPattern.regionMatches(fIgnoreCase, 0, text, start,
- fLength);
- }
- int segCount = fSegments.length;
- if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
- return true;
- }
- if (start == end) {
- return fLength == 0;
- }
- if (fLength == 0) {
- return start == end;
- }
-
- int tlen = text.length();
- if (start < 0) {
- start = 0;
- }
- if (end > tlen) {
- end = tlen;
- }
-
- int tCurPos = start;
- int bound = end - fBound;
- if (bound < 0) {
- return false;
- }
- int i = 0;
- String current = fSegments[i];
- int segLength = current.length();
-
- /* process first segment */
- if (!fHasLeadingStar) {
- if (!regExpRegionMatches(text, start, current, 0, segLength)) {
- return false;
- } else {
- ++i;
- tCurPos = tCurPos + segLength;
- }
- }
- if ((fSegments.length == 1) && (!fHasLeadingStar)
- && (!fHasTrailingStar)) {
- // only one segment to match, no wildcards specified
- return tCurPos == end;
- }
- /* process middle segments */
- while (i < segCount) {
- current = fSegments[i];
- int currentMatch;
- int k = current.indexOf(fSingleWildCard);
- if (k < 0) {
- currentMatch = textPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- } else {
- currentMatch = regExpPosIn(text, tCurPos, end, current);
- if (currentMatch < 0) {
- return false;
- }
- }
- tCurPos = currentMatch + current.length();
- i++;
- }
-
- /* process final segment */
- if (!fHasTrailingStar && tCurPos != end) {
- int clen = current.length();
- return regExpRegionMatches(text, end - clen, current, 0, clen);
- }
- return i == segCount;
- }
-
- /**
- * This method parses the given pattern into segments seperated by wildcard '*' characters.
- * Since wildcards are not being used in this case, the pattern consists of a single segment.
- */
- private void parseNoWildCards() {
- fSegments = new String[1];
- fSegments[0] = fPattern;
- fBound = fLength;
- }
-
- /**
- * Parses the given pattern into segments seperated by wildcard '*' characters.
- * @param p, a String object that is a simple regular expression with '*' and/or '?'
- */
- private void parseWildCards() {
- if (fPattern.startsWith("*")) { //$NON-NLS-1$
- fHasLeadingStar = true;
- }
- if (fPattern.endsWith("*")) {//$NON-NLS-1$
- /* make sure it's not an escaped wildcard */
- if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
- fHasTrailingStar = true;
- }
- }
-
- Vector temp = new Vector();
-
- int pos = 0;
- StringBuffer buf = new StringBuffer();
- while (pos < fLength) {
- char c = fPattern.charAt(pos++);
- switch (c) {
- case '\\':
- if (pos >= fLength) {
- buf.append(c);
- } else {
- char next = fPattern.charAt(pos++);
- /* if it's an escape sequence */
- if (next == '*' || next == '?' || next == '\\') {
- buf.append(next);
- } else {
- /* not an escape sequence, just insert literally */
- buf.append(c);
- buf.append(next);
- }
- }
- break;
- case '*':
- if (buf.length() > 0) {
- /* new segment */
- temp.addElement(buf.toString());
- fBound += buf.length();
- buf.setLength(0);
- }
- break;
- case '?':
- /* append special character representing single match wildcard */
- buf.append(fSingleWildCard);
- break;
- default:
- buf.append(c);
- }
- }
-
- /* add last buffer to segment list */
- if (buf.length() > 0) {
- temp.addElement(buf.toString());
- fBound += buf.length();
- }
-
- fSegments = new String[temp.size()];
- temp.copyInto(fSegments);
- }
-
- /**
- * @param text a string which contains no wildcard
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int posIn(String text, int start, int end) {//no wild card in pattern
- int max = end - fLength;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(fPattern, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, fPattern, 0, fLength)) {
- return i;
- }
- }
-
- return -1;
- }
-
- /**
- * @param text a simple regular expression that may only contain '?'(s)
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a simple regular expression that may contains '?'
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int regExpPosIn(String text, int start, int end, String p) {
- int plen = p.length();
-
- int max = end - plen;
- for (int i = start; i <= max; ++i) {
- if (regExpRegionMatches(text, i, p, 0, plen)) {
- return i;
- }
- }
- return -1;
- }
-
- /**
- *
- * @return boolean
- * @param text a String to match
- * @param start int that indicates the starting index of match, inclusive
- * @param end</code> int that indicates the ending index of match, exclusive
- * @param p String, String, a simple regular expression that may contain '?'
- * @param ignoreCase boolean indicating wether code>p</code> is case sensitive
- */
- protected boolean regExpRegionMatches(String text, int tStart, String p,
- int pStart, int plen) {
- while (plen-- > 0) {
- char tchar = text.charAt(tStart++);
- char pchar = p.charAt(pStart++);
-
- /* process wild cards */
- if (!fIgnoreWildCards) {
- /* skip single wild cards */
- if (pchar == fSingleWildCard) {
- continue;
- }
- }
- if (pchar == tchar) {
- continue;
- }
- if (fIgnoreCase) {
- if (Character.toUpperCase(tchar) == Character
- .toUpperCase(pchar)) {
- continue;
- }
- // comparing after converting to upper case doesn't handle all cases;
- // also compare after converting to lower case
- if (Character.toLowerCase(tchar) == Character
- .toLowerCase(pchar)) {
- continue;
- }
- }
- return false;
- }
- return true;
- }
-
- /**
- * @param text the string to match
- * @param start the starting index in the text for search, inclusive
- * @param end the stopping point of search, exclusive
- * @param p a pattern string that has no wildcard
- * @return the starting index in the text of the pattern , or -1 if not found
- */
- protected int textPosIn(String text, int start, int end, String p) {
-
- int plen = p.length();
- int max = end - plen;
-
- if (!fIgnoreCase) {
- int i = text.indexOf(p, start);
- if (i == -1 || i > max) {
- return -1;
- }
- return i;
- }
-
- for (int i = start; i <= max; ++i) {
- if (text.regionMatches(true, i, p, 0, plen)) {
- return i;
- }
- }
-
- return -1;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.filter;
+
+import java.util.Vector;
+
+/**
+ * A string pattern matcher, suppporting "*" and "?" wildcards.
+ */
+public class StringMatcher {
+ protected String fPattern;
+
+ protected int fLength; // pattern length
+
+ protected boolean fIgnoreWildCards;
+
+ protected boolean fIgnoreCase;
+
+ protected boolean fHasLeadingStar;
+
+ protected boolean fHasTrailingStar;
+
+ protected String fSegments[]; //the given pattern is split into * separated segments
+
+ /* boundary value beyond which we don't need to search in the text */
+ protected int fBound = 0;
+
+ protected static final char fSingleWildCard = '\u0000';
+
+ public static class Position {
+ int start; //inclusive
+
+ int end; //exclusive
+
+ public Position(int start, int end) {
+ this.start = start;
+ this.end = end;
+ }
+
+ public int getStart() {
+ return start;
+ }
+
+ public int getEnd() {
+ return end;
+ }
+ }
+
+ /**
+ * StringMatcher constructor takes in a String object that is a simple
+ * pattern which may contain '*' for 0 and many characters and
+ * '?' for exactly one character.
+ *
+ * Literal '*' and '?' characters must be escaped in the pattern
+ * e.g., "\*" means literal "*", etc.
+ *
+ * Escaping any other character (including the escape character itself),
+ * just results in that character in the pattern.
+ * e.g., "\a" means "a" and "\\" means "\"
+ *
+ * If invoking the StringMatcher with string literals in Java, don't forget
+ * escape characters are represented by "\\".
+ *
+ * @param pattern the pattern to match text against
+ * @param ignoreCase if true, case is ignored
+ * @param ignoreWildCards if true, wild cards and their escape sequences are ignored
+ * (everything is taken literally).
+ */
+ public StringMatcher(String pattern, boolean ignoreCase,
+ boolean ignoreWildCards) {
+ if (pattern == null) {
+ throw new IllegalArgumentException();
+ }
+ fIgnoreCase = ignoreCase;
+ fIgnoreWildCards = ignoreWildCards;
+ fPattern = pattern;
+ fLength = pattern.length();
+
+ if (fIgnoreWildCards) {
+ parseNoWildCards();
+ } else {
+ parseWildCards();
+ }
+ }
+
+ /**
+ * Find the first occurrence of the pattern between <code>start</code)(inclusive)
+ * and <code>end</code>(exclusive).
+ * @param text the String object to search in
+ * @param start the starting index of the search range, inclusive
+ * @param end the ending index of the search range, exclusive
+ * @return an <code>StringMatcher.Position</code> object that keeps the starting
+ * (inclusive) and ending positions (exclusive) of the first occurrence of the
+ * pattern in the specified range of the text; return null if not found or subtext
+ * is empty (start==end). A pair of zeros is returned if pattern is empty string
+ * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc"
+ * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned
+ */
+ public StringMatcher.Position find(String text, int start, int end) {
+ if (text == null) {
+ throw new IllegalArgumentException();
+ }
+
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+ if (end < 0 || start >= end) {
+ return null;
+ }
+ if (fLength == 0) {
+ return new Position(start, start);
+ }
+ if (fIgnoreWildCards) {
+ int x = posIn(text, start, end);
+ if (x < 0) {
+ return null;
+ }
+ return new Position(x, x + fLength);
+ }
+
+ int segCount = fSegments.length;
+ if (segCount == 0) {
+ return new Position(start, end);
+ }
+
+ int curPos = start;
+ int matchStart = -1;
+ int i;
+ for (i = 0; i < segCount && curPos < end; ++i) {
+ String current = fSegments[i];
+ int nextMatch = regExpPosIn(text, curPos, end, current);
+ if (nextMatch < 0) {
+ return null;
+ }
+ if (i == 0) {
+ matchStart = nextMatch;
+ }
+ curPos = nextMatch + current.length();
+ }
+ if (i < segCount) {
+ return null;
+ }
+ return new Position(matchStart, curPos);
+ }
+
+ /**
+ * match the given <code>text</code> with the pattern
+ * @return true if matched otherwise false
+ * @param text a String object
+ */
+ public boolean match(String text) {
+ if(text == null) {
+ return false;
+ }
+ return match(text, 0, text.length());
+ }
+
+ /**
+ * Given the starting (inclusive) and the ending (exclusive) positions in the
+ * <code>text</code>, determine if the given substring matches with aPattern
+ * @return true if the specified portion of the text matches the pattern
+ * @param text a String object that contains the substring to match
+ * @param start marks the starting position (inclusive) of the substring
+ * @param end marks the ending index (exclusive) of the substring
+ */
+ public boolean match(String text, int start, int end) {
+ if (null == text) {
+ throw new IllegalArgumentException();
+ }
+
+ if (start > end) {
+ return false;
+ }
+
+ if (fIgnoreWildCards) {
+ return (end - start == fLength)
+ && fPattern.regionMatches(fIgnoreCase, 0, text, start,
+ fLength);
+ }
+ int segCount = fSegments.length;
+ if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) {
+ return true;
+ }
+ if (start == end) {
+ return fLength == 0;
+ }
+ if (fLength == 0) {
+ return start == end;
+ }
+
+ int tlen = text.length();
+ if (start < 0) {
+ start = 0;
+ }
+ if (end > tlen) {
+ end = tlen;
+ }
+
+ int tCurPos = start;
+ int bound = end - fBound;
+ if (bound < 0) {
+ return false;
+ }
+ int i = 0;
+ String current = fSegments[i];
+ int segLength = current.length();
+
+ /* process first segment */
+ if (!fHasLeadingStar) {
+ if (!regExpRegionMatches(text, start, current, 0, segLength)) {
+ return false;
+ } else {
+ ++i;
+ tCurPos = tCurPos + segLength;
+ }
+ }
+ if ((fSegments.length == 1) && (!fHasLeadingStar)
+ && (!fHasTrailingStar)) {
+ // only one segment to match, no wildcards specified
+ return tCurPos == end;
+ }
+ /* process middle segments */
+ while (i < segCount) {
+ current = fSegments[i];
+ int currentMatch;
+ int k = current.indexOf(fSingleWildCard);
+ if (k < 0) {
+ currentMatch = textPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ } else {
+ currentMatch = regExpPosIn(text, tCurPos, end, current);
+ if (currentMatch < 0) {
+ return false;
+ }
+ }
+ tCurPos = currentMatch + current.length();
+ i++;
+ }
+
+ /* process final segment */
+ if (!fHasTrailingStar && tCurPos != end) {
+ int clen = current.length();
+ return regExpRegionMatches(text, end - clen, current, 0, clen);
+ }
+ return i == segCount;
+ }
+
+ /**
+ * This method parses the given pattern into segments seperated by wildcard '*' characters.
+ * Since wildcards are not being used in this case, the pattern consists of a single segment.
+ */
+ private void parseNoWildCards() {
+ fSegments = new String[1];
+ fSegments[0] = fPattern;
+ fBound = fLength;
+ }
+
+ /**
+ * Parses the given pattern into segments seperated by wildcard '*' characters.
+ * @param p, a String object that is a simple regular expression with '*' and/or '?'
+ */
+ private void parseWildCards() {
+ if (fPattern.startsWith("*")) { //$NON-NLS-1$
+ fHasLeadingStar = true;
+ }
+ if (fPattern.endsWith("*")) {//$NON-NLS-1$
+ /* make sure it's not an escaped wildcard */
+ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
+ fHasTrailingStar = true;
+ }
+ }
+
+ Vector temp = new Vector();
+
+ int pos = 0;
+ StringBuffer buf = new StringBuffer();
+ while (pos < fLength) {
+ char c = fPattern.charAt(pos++);
+ switch (c) {
+ case '\\':
+ if (pos >= fLength) {
+ buf.append(c);
+ } else {
+ char next = fPattern.charAt(pos++);
+ /* if it's an escape sequence */
+ if (next == '*' || next == '?' || next == '\\') {
+ buf.append(next);
+ } else {
+ /* not an escape sequence, just insert literally */
+ buf.append(c);
+ buf.append(next);
+ }
+ }
+ break;
+ case '*':
+ if (buf.length() > 0) {
+ /* new segment */
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ buf.setLength(0);
+ }
+ break;
+ case '?':
+ /* append special character representing single match wildcard */
+ buf.append(fSingleWildCard);
+ break;
+ default:
+ buf.append(c);
+ }
+ }
+
+ /* add last buffer to segment list */
+ if (buf.length() > 0) {
+ temp.addElement(buf.toString());
+ fBound += buf.length();
+ }
+
+ fSegments = new String[temp.size()];
+ temp.copyInto(fSegments);
+ }
+
+ /**
+ * @param text a string which contains no wildcard
+ * @param start the starting index in the text for search, inclusive
+ * @param end the stopping point of search, exclusive
+ * @return the starting index in the text of the pattern , or -1 if not found
+ */
+ protected int posIn(String text, int start, int end) {//no wild card in pattern
+ int max = end - fLength;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(fPattern, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
+
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, fPattern, 0, fLength)) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ /**
+ * @param text a simple regular expression that may only contain '?'(s)
+ * @param start the starting index in the text for search, inclusive
+ * @param end the stopping point of search, exclusive
+ * @param p a simple regular expression that may contains '?'
+ * @return the starting index in the text of the pattern , or -1 if not found
+ */
+ protected int regExpPosIn(String text, int start, int end, String p) {
+ int plen = p.length();
+
+ int max = end - plen;
+ for (int i = start; i <= max; ++i) {
+ if (regExpRegionMatches(text, i, p, 0, plen)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ *
+ * @return boolean
+ * @param text a String to match
+ * @param start int that indicates the starting index of match, inclusive
+ * @param end</code> int that indicates the ending index of match, exclusive
+ * @param p String, String, a simple regular expression that may contain '?'
+ * @param ignoreCase boolean indicating wether code>p</code> is case sensitive
+ */
+ protected boolean regExpRegionMatches(String text, int tStart, String p,
+ int pStart, int plen) {
+ while (plen-- > 0) {
+ char tchar = text.charAt(tStart++);
+ char pchar = p.charAt(pStart++);
+
+ /* process wild cards */
+ if (!fIgnoreWildCards) {
+ /* skip single wild cards */
+ if (pchar == fSingleWildCard) {
+ continue;
+ }
+ }
+ if (pchar == tchar) {
+ continue;
+ }
+ if (fIgnoreCase) {
+ if (Character.toUpperCase(tchar) == Character
+ .toUpperCase(pchar)) {
+ continue;
+ }
+ // comparing after converting to upper case doesn't handle all cases;
+ // also compare after converting to lower case
+ if (Character.toLowerCase(tchar) == Character
+ .toLowerCase(pchar)) {
+ continue;
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * @param text the string to match
+ * @param start the starting index in the text for search, inclusive
+ * @param end the stopping point of search, exclusive
+ * @param p a pattern string that has no wildcard
+ * @return the starting index in the text of the pattern , or -1 if not found
+ */
+ protected int textPosIn(String text, int start, int end, String p) {
+
+ int plen = p.length();
+ int max = end - plen;
+
+ if (!fIgnoreCase) {
+ int i = text.indexOf(p, start);
+ if (i == -1 || i > max) {
+ return -1;
+ }
+ return i;
+ }
+
+ for (int i = start; i <= max; ++i) {
+ if (text.regionMatches(true, i, p, 0, plen)) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
index 9280bd2d..1c3e965c 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java
@@ -1,212 +1,219 @@
-package org.eclipselabs.tapiji.translator.views.widgets.model;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
-
-
-public class GlossaryViewState {
-
- private static final String TAG_GLOSSARY_FILE = "glossary_file";
- private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
- private static final String TAG_SELECTIVE_VIEW = "selective_content";
- private static final String TAG_DISPLAYED_LOCALES = "displayed_locales";
- private static final String TAG_LOCALE = "locale";
- private static final String TAG_REFERENCE_LANG = "reference_language";
- private static final String TAG_MATCHING_PRECISION= "matching_precision";
- private static final String TAG_ENABLED = "enabled";
- private static final String TAG_VALUE = "value";
- private static final String TAG_SEARCH_STRING = "search_string";
- private static final String TAG_EDITABLE = "editable";
-
- private SortInfo sortings;
- private boolean fuzzyMatchingEnabled;
- private boolean selectiveViewEnabled;
- private float matchingPrecision = .75f;
- private String searchString;
- private boolean editable;
- private String glossaryFile;
- private String referenceLanguage;
- private List<String> displayLanguages;
-
- public void saveState (IMemento memento) {
- try {
- if (memento == null)
- return;
-
- if (sortings != null) {
- sortings.saveState(memento);
- }
-
- IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
- memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
-
- IMemento memSelectiveView = memento.createChild(TAG_SELECTIVE_VIEW);
- memSelectiveView.putBoolean(TAG_ENABLED, selectiveViewEnabled);
-
- IMemento memMatchingPrec = memento.createChild(TAG_MATCHING_PRECISION);
- memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
-
- IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
- memSStr.putString(TAG_VALUE, searchString);
-
- IMemento memEditable = memento.createChild(TAG_EDITABLE);
- memEditable.putBoolean(TAG_ENABLED, editable);
-
- IMemento memRefLang = memento.createChild(TAG_REFERENCE_LANG);
- memRefLang.putString(TAG_VALUE, referenceLanguage);
-
- IMemento memGlossaryFile = memento.createChild(TAG_GLOSSARY_FILE);
- memGlossaryFile.putString(TAG_VALUE, glossaryFile);
-
- IMemento memDispLoc = memento.createChild(TAG_DISPLAYED_LOCALES);
- if (displayLanguages != null) {
- for (String lang : displayLanguages) {
- IMemento memLoc = memDispLoc.createChild(TAG_LOCALE);
- memLoc.putString(TAG_VALUE, lang);
- }
- }
- } catch (Exception e) {
-
- }
- }
-
- public void init (IMemento memento) {
- try {
- if (memento == null)
- return;
-
- if (sortings == null)
- sortings = new SortInfo();
- sortings.init(memento);
-
- IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
- if (mFuzzyMatching != null)
- fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
-
- IMemento mSelectiveView = memento.getChild(TAG_SELECTIVE_VIEW);
- if (mSelectiveView != null)
- selectiveViewEnabled = mSelectiveView.getBoolean(TAG_ENABLED);
-
- IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
- if (mMP != null)
- matchingPrecision = mMP.getFloat(TAG_VALUE);
-
- IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
- if (mSStr != null)
- searchString = mSStr.getString(TAG_VALUE);
-
- IMemento mEditable = memento.getChild(TAG_EDITABLE);
- if (mEditable != null)
- editable = mEditable.getBoolean(TAG_ENABLED);
-
- IMemento mRefLang = memento.getChild(TAG_REFERENCE_LANG);
- if (mRefLang != null)
- referenceLanguage = mRefLang.getString(TAG_VALUE);
-
- IMemento mGlossaryFile = memento.getChild(TAG_GLOSSARY_FILE);
- if (mGlossaryFile != null)
- glossaryFile = mGlossaryFile.getString(TAG_VALUE);
-
- IMemento memDispLoc = memento.getChild(TAG_DISPLAYED_LOCALES);
- if (memDispLoc != null) {
- displayLanguages = new ArrayList<String>();
- for (IMemento locale : memDispLoc.getChildren(TAG_LOCALE)) {
- displayLanguages.add(locale.getString(TAG_VALUE));
- }
- }
- } catch (Exception e) {
-
- }
- }
-
- public GlossaryViewState(List<Locale> visibleLocales,
- SortInfo sortings, boolean fuzzyMatchingEnabled,
- String selectedBundleId) {
- super();
- this.sortings = sortings;
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- }
-
- public SortInfo getSortings() {
- return sortings;
- }
-
- public void setSortings(SortInfo sortings) {
- this.sortings = sortings;
- }
-
- public boolean isFuzzyMatchingEnabled() {
- return fuzzyMatchingEnabled;
- }
-
- public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
- this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
- }
-
- public void setSearchString(String searchString) {
- this.searchString = searchString;
- }
-
- public String getSearchString() {
- return searchString;
- }
-
- public boolean isEditable() {
- return editable;
- }
-
- public void setEditable(boolean editable) {
- this.editable = editable;
- }
-
- public float getMatchingPrecision() {
- return matchingPrecision;
- }
-
- public void setMatchingPrecision (float value) {
- this.matchingPrecision = value;
- }
-
- public String getReferenceLanguage() {
- return this.referenceLanguage;
- }
-
- public void setReferenceLanguage (String refLang) {
- this.referenceLanguage = refLang;
- }
-
- public List<String> getDisplayLanguages() {
- return displayLanguages;
- }
-
- public void setDisplayLanguages(List<String> displayLanguages) {
- this.displayLanguages = displayLanguages;
- }
-
- public void setDisplayLangArr (String[] displayLanguages) {
- this.displayLanguages = new ArrayList<String>();
- for (String dl : displayLanguages) {
- this.displayLanguages.add(dl);
- }
- }
-
- public void setGlossaryFile(String absolutePath) {
- this.glossaryFile = absolutePath;
- }
-
- public String getGlossaryFile() {
- return glossaryFile;
- }
-
- public void setSelectiveViewEnabled(boolean selectiveViewEnabled) {
- this.selectiveViewEnabled = selectiveViewEnabled;
- }
-
- public boolean isSelectiveViewEnabled() {
- return selectiveViewEnabled;
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.model;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.ui.IMemento;
+import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo;
+
+
+public class GlossaryViewState {
+
+ private static final String TAG_GLOSSARY_FILE = "glossary_file";
+ private static final String TAG_FUZZY_MATCHING = "fuzzy_matching";
+ private static final String TAG_SELECTIVE_VIEW = "selective_content";
+ private static final String TAG_DISPLAYED_LOCALES = "displayed_locales";
+ private static final String TAG_LOCALE = "locale";
+ private static final String TAG_REFERENCE_LANG = "reference_language";
+ private static final String TAG_MATCHING_PRECISION= "matching_precision";
+ private static final String TAG_ENABLED = "enabled";
+ private static final String TAG_VALUE = "value";
+ private static final String TAG_SEARCH_STRING = "search_string";
+ private static final String TAG_EDITABLE = "editable";
+
+ private SortInfo sortings;
+ private boolean fuzzyMatchingEnabled;
+ private boolean selectiveViewEnabled;
+ private float matchingPrecision = .75f;
+ private String searchString;
+ private boolean editable;
+ private String glossaryFile;
+ private String referenceLanguage;
+ private List<String> displayLanguages;
+
+ public void saveState (IMemento memento) {
+ try {
+ if (memento == null)
+ return;
+
+ if (sortings != null) {
+ sortings.saveState(memento);
+ }
+
+ IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING);
+ memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled);
+
+ IMemento memSelectiveView = memento.createChild(TAG_SELECTIVE_VIEW);
+ memSelectiveView.putBoolean(TAG_ENABLED, selectiveViewEnabled);
+
+ IMemento memMatchingPrec = memento.createChild(TAG_MATCHING_PRECISION);
+ memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision);
+
+ IMemento memSStr = memento.createChild(TAG_SEARCH_STRING);
+ memSStr.putString(TAG_VALUE, searchString);
+
+ IMemento memEditable = memento.createChild(TAG_EDITABLE);
+ memEditable.putBoolean(TAG_ENABLED, editable);
+
+ IMemento memRefLang = memento.createChild(TAG_REFERENCE_LANG);
+ memRefLang.putString(TAG_VALUE, referenceLanguage);
+
+ IMemento memGlossaryFile = memento.createChild(TAG_GLOSSARY_FILE);
+ memGlossaryFile.putString(TAG_VALUE, glossaryFile);
+
+ IMemento memDispLoc = memento.createChild(TAG_DISPLAYED_LOCALES);
+ if (displayLanguages != null) {
+ for (String lang : displayLanguages) {
+ IMemento memLoc = memDispLoc.createChild(TAG_LOCALE);
+ memLoc.putString(TAG_VALUE, lang);
+ }
+ }
+ } catch (Exception e) {
+
+ }
+ }
+
+ public void init (IMemento memento) {
+ try {
+ if (memento == null)
+ return;
+
+ if (sortings == null)
+ sortings = new SortInfo();
+ sortings.init(memento);
+
+ IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING);
+ if (mFuzzyMatching != null)
+ fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED);
+
+ IMemento mSelectiveView = memento.getChild(TAG_SELECTIVE_VIEW);
+ if (mSelectiveView != null)
+ selectiveViewEnabled = mSelectiveView.getBoolean(TAG_ENABLED);
+
+ IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION);
+ if (mMP != null)
+ matchingPrecision = mMP.getFloat(TAG_VALUE);
+
+ IMemento mSStr = memento.getChild(TAG_SEARCH_STRING);
+ if (mSStr != null)
+ searchString = mSStr.getString(TAG_VALUE);
+
+ IMemento mEditable = memento.getChild(TAG_EDITABLE);
+ if (mEditable != null)
+ editable = mEditable.getBoolean(TAG_ENABLED);
+
+ IMemento mRefLang = memento.getChild(TAG_REFERENCE_LANG);
+ if (mRefLang != null)
+ referenceLanguage = mRefLang.getString(TAG_VALUE);
+
+ IMemento mGlossaryFile = memento.getChild(TAG_GLOSSARY_FILE);
+ if (mGlossaryFile != null)
+ glossaryFile = mGlossaryFile.getString(TAG_VALUE);
+
+ IMemento memDispLoc = memento.getChild(TAG_DISPLAYED_LOCALES);
+ if (memDispLoc != null) {
+ displayLanguages = new ArrayList<String>();
+ for (IMemento locale : memDispLoc.getChildren(TAG_LOCALE)) {
+ displayLanguages.add(locale.getString(TAG_VALUE));
+ }
+ }
+ } catch (Exception e) {
+
+ }
+ }
+
+ public GlossaryViewState(List<Locale> visibleLocales,
+ SortInfo sortings, boolean fuzzyMatchingEnabled,
+ String selectedBundleId) {
+ super();
+ this.sortings = sortings;
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ }
+
+ public SortInfo getSortings() {
+ return sortings;
+ }
+
+ public void setSortings(SortInfo sortings) {
+ this.sortings = sortings;
+ }
+
+ public boolean isFuzzyMatchingEnabled() {
+ return fuzzyMatchingEnabled;
+ }
+
+ public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) {
+ this.fuzzyMatchingEnabled = fuzzyMatchingEnabled;
+ }
+
+ public void setSearchString(String searchString) {
+ this.searchString = searchString;
+ }
+
+ public String getSearchString() {
+ return searchString;
+ }
+
+ public boolean isEditable() {
+ return editable;
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = editable;
+ }
+
+ public float getMatchingPrecision() {
+ return matchingPrecision;
+ }
+
+ public void setMatchingPrecision (float value) {
+ this.matchingPrecision = value;
+ }
+
+ public String getReferenceLanguage() {
+ return this.referenceLanguage;
+ }
+
+ public void setReferenceLanguage (String refLang) {
+ this.referenceLanguage = refLang;
+ }
+
+ public List<String> getDisplayLanguages() {
+ return displayLanguages;
+ }
+
+ public void setDisplayLanguages(List<String> displayLanguages) {
+ this.displayLanguages = displayLanguages;
+ }
+
+ public void setDisplayLangArr (String[] displayLanguages) {
+ this.displayLanguages = new ArrayList<String>();
+ for (String dl : displayLanguages) {
+ this.displayLanguages.add(dl);
+ }
+ }
+
+ public void setGlossaryFile(String absolutePath) {
+ this.glossaryFile = absolutePath;
+ }
+
+ public String getGlossaryFile() {
+ return glossaryFile;
+ }
+
+ public void setSelectiveViewEnabled(boolean selectiveViewEnabled) {
+ this.selectiveViewEnabled = selectiveViewEnabled;
+ }
+
+ public boolean isSelectiveViewEnabled() {
+ return selectiveViewEnabled;
+ }
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
index c36862fa..4ffa91d6 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java
@@ -1,97 +1,104 @@
-package org.eclipselabs.tapiji.translator.views.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipselabs.tapiji.translator.model.Glossary;
-import org.eclipselabs.tapiji.translator.model.Term;
-
-
-public class GlossaryContentProvider implements ITreeContentProvider {
-
- private Glossary glossary;
- private boolean grouped = false;
-
- public GlossaryContentProvider (Glossary glossary) {
- this.glossary = glossary;
- }
-
- public Glossary getGlossary () {
- return glossary;
- }
-
- public void setGrouped (boolean grouped) {
- this.grouped = grouped;
- }
-
- @Override
- public void dispose() {
- this.glossary = null;
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (newInput instanceof Glossary)
- this.glossary = (Glossary) newInput;
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (!grouped)
- return getAllElements(glossary.terms).toArray(new Term[glossary.terms.size()]);
-
- if (glossary != null)
- return glossary.getAllTerms();
-
- return null;
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- if (!grouped)
- return null;
-
- if (parentElement instanceof Term) {
- Term t = (Term) parentElement;
- return t.getAllSubTerms ();
- }
- return null;
- }
-
- @Override
- public Object getParent(Object element) {
- if (element instanceof Term) {
- Term t = (Term) element;
- return t.getParentTerm();
- }
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (!grouped)
- return false;
-
- if (element instanceof Term) {
- Term t = (Term) element;
- return t.hasChildTerms();
- }
- return false;
- }
-
- public List<Term> getAllElements (List<Term> terms) {
- List<Term> allTerms = new ArrayList<Term>();
-
- if (terms != null) {
- for (Term term : terms) {
- allTerms.add(term);
- allTerms.addAll(getAllElements(term.subTerms));
- }
- }
-
- return allTerms;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipselabs.tapiji.translator.model.Glossary;
+import org.eclipselabs.tapiji.translator.model.Term;
+
+
+public class GlossaryContentProvider implements ITreeContentProvider {
+
+ private Glossary glossary;
+ private boolean grouped = false;
+
+ public GlossaryContentProvider (Glossary glossary) {
+ this.glossary = glossary;
+ }
+
+ public Glossary getGlossary () {
+ return glossary;
+ }
+
+ public void setGrouped (boolean grouped) {
+ this.grouped = grouped;
+ }
+
+ @Override
+ public void dispose() {
+ this.glossary = null;
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ if (newInput instanceof Glossary)
+ this.glossary = (Glossary) newInput;
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (!grouped)
+ return getAllElements(glossary.terms).toArray(new Term[glossary.terms.size()]);
+
+ if (glossary != null)
+ return glossary.getAllTerms();
+
+ return null;
+ }
+
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ if (!grouped)
+ return null;
+
+ if (parentElement instanceof Term) {
+ Term t = (Term) parentElement;
+ return t.getAllSubTerms ();
+ }
+ return null;
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ if (element instanceof Term) {
+ Term t = (Term) element;
+ return t.getParentTerm();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ if (!grouped)
+ return false;
+
+ if (element instanceof Term) {
+ Term t = (Term) element;
+ return t.hasChildTerms();
+ }
+ return false;
+ }
+
+ public List<Term> getAllElements (List<Term> terms) {
+ List<Term> allTerms = new ArrayList<Term>();
+
+ if (terms != null) {
+ for (Term term : terms) {
+ allTerms.add(term);
+ allTerms.addAll(getAllElements(term.subTerms));
+ }
+ }
+
+ return allTerms;
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
index 98ea72e7..aada0686 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java
@@ -1,169 +1,176 @@
-package org.eclipselabs.tapiji.translator.views.widgets.provider;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.babel.editor.api.EditorUtil;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
-import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-import org.eclipselabs.tapiji.translator.utils.FontUtils;
-import org.eclipselabs.tapiji.translator.views.widgets.filter.FilterInfo;
-
-public class GlossaryLabelProvider extends StyledCellLabelProvider implements
- ISelectionListener, ISelectionChangedListener {
-
- private boolean searchEnabled = false;
- private int referenceColumn = 0;
- private List<String> translations;
- private IKeyTreeNode selectedItem;
-
- /*** COLORS ***/
- private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
- private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
- private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
- private Color info_crossref = FontUtils.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- private Color info_crossref_foreground = FontUtils.getSystemColor(SWT.COLOR_INFO_FOREGROUND);
- private Color transparent = FontUtils.getSystemColor(SWT.COLOR_WHITE);
-
- /*** FONTS ***/
- private Font bold = FontUtils.createFont(SWT.BOLD);
- private Font bold_italic = FontUtils.createFont(SWT.ITALIC);
-
- public void setSearchEnabled(boolean b) {
- this.searchEnabled = b;
- }
-
- public GlossaryLabelProvider(int referenceColumn, List<String> translations, IWorkbenchPage page) {
- this.referenceColumn = referenceColumn;
- this.translations = translations;
- if (page.getActiveEditor() != null) {
- selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
- }
- }
-
- public String getColumnText(Object element, int columnIndex) {
- try {
- Term term = (Term) element;
- if (term != null) {
- Translation transl = term.getTranslation(this.translations.get(columnIndex));
- return transl != null ? transl.value : "";
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return "";
- }
-
- public boolean isSearchEnabled () {
- return this.searchEnabled;
- }
-
- protected boolean isMatchingToPattern (Object element, int columnIndex) {
- boolean matching = false;
-
- if (element instanceof Term) {
- Term term = (Term) element;
-
- if (term.getInfo() == null)
- return false;
-
- FilterInfo filterInfo = (FilterInfo) term.getInfo();
-
- matching = filterInfo.hasFoundInTranslation(translations.get(columnIndex));
- }
-
- return matching;
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int columnIndex = cell.getColumnIndex();
- cell.setText(this.getColumnText(element, columnIndex));
-
- if (isCrossRefRegion(cell.getText())) {
- cell.setFont (bold);
- cell.setBackground(info_crossref);
- cell.setForeground(info_crossref_foreground);
- } else {
- cell.setFont(this.getColumnFont(element, columnIndex));
- cell.setBackground(transparent);
- }
-
- if (isSearchEnabled()) {
- if (isMatchingToPattern(element, columnIndex) ) {
- List<StyleRange> styleRanges = new ArrayList<StyleRange>();
- FilterInfo filterInfo = (FilterInfo) ((Term)element).getInfo();
-
- for (Region reg : filterInfo.getFoundInTranslationRanges(translations.get(columnIndex < referenceColumn ? columnIndex + 1 : columnIndex))) {
- styleRanges.add(new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD));
- }
-
- cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()]));
- } else {
- cell.setForeground(gray);
- }
- }
- }
-
- private boolean isCrossRefRegion(String cellText) {
- if (selectedItem != null) {
- for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
- String value = entry.getValue();
- String[] subValues = value.split("[\\s\\p{Punct}]+");
- for (String v : subValues) {
- if (v.trim().equalsIgnoreCase(cellText.trim()))
- return true;
- }
- }
- }
-
- return false;
- }
-
- private Font getColumnFont(Object element, int columnIndex) {
- if (columnIndex == 0) {
- return bold_italic;
- }
- return null;
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- try {
- if (selection.isEmpty())
- return;
-
- if (!(selection instanceof IStructuredSelection))
- return;
-
- IStructuredSelection sel = (IStructuredSelection) selection;
- selectedItem = (IKeyTreeNode) sel.iterator().next();
- this.getViewer().refresh();
- } catch (Exception e) {
- // silent catch
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- event.getSelection();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.provider;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.babel.editor.api.EditorUtil;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IKeyTreeNode;
+import org.eclipse.babel.tapiji.translator.rbe.babel.bundle.IMessage;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StyledCellLabelProvider;
+import org.eclipse.jface.viewers.ViewerCell;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+import org.eclipselabs.tapiji.translator.utils.FontUtils;
+import org.eclipselabs.tapiji.translator.views.widgets.filter.FilterInfo;
+
+public class GlossaryLabelProvider extends StyledCellLabelProvider implements
+ ISelectionListener, ISelectionChangedListener {
+
+ private boolean searchEnabled = false;
+ private int referenceColumn = 0;
+ private List<String> translations;
+ private IKeyTreeNode selectedItem;
+
+ /*** COLORS ***/
+ private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY);
+ private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK);
+ private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW);
+ private Color info_crossref = FontUtils.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
+ private Color info_crossref_foreground = FontUtils.getSystemColor(SWT.COLOR_INFO_FOREGROUND);
+ private Color transparent = FontUtils.getSystemColor(SWT.COLOR_WHITE);
+
+ /*** FONTS ***/
+ private Font bold = FontUtils.createFont(SWT.BOLD);
+ private Font bold_italic = FontUtils.createFont(SWT.ITALIC);
+
+ public void setSearchEnabled(boolean b) {
+ this.searchEnabled = b;
+ }
+
+ public GlossaryLabelProvider(int referenceColumn, List<String> translations, IWorkbenchPage page) {
+ this.referenceColumn = referenceColumn;
+ this.translations = translations;
+ if (page.getActiveEditor() != null) {
+ selectedItem = EditorUtil.getSelectedKeyTreeNode(page);
+ }
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ try {
+ Term term = (Term) element;
+ if (term != null) {
+ Translation transl = term.getTranslation(this.translations.get(columnIndex));
+ return transl != null ? transl.value : "";
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return "";
+ }
+
+ public boolean isSearchEnabled () {
+ return this.searchEnabled;
+ }
+
+ protected boolean isMatchingToPattern (Object element, int columnIndex) {
+ boolean matching = false;
+
+ if (element instanceof Term) {
+ Term term = (Term) element;
+
+ if (term.getInfo() == null)
+ return false;
+
+ FilterInfo filterInfo = (FilterInfo) term.getInfo();
+
+ matching = filterInfo.hasFoundInTranslation(translations.get(columnIndex));
+ }
+
+ return matching;
+ }
+
+ @Override
+ public void update(ViewerCell cell) {
+ Object element = cell.getElement();
+ int columnIndex = cell.getColumnIndex();
+ cell.setText(this.getColumnText(element, columnIndex));
+
+ if (isCrossRefRegion(cell.getText())) {
+ cell.setFont (bold);
+ cell.setBackground(info_crossref);
+ cell.setForeground(info_crossref_foreground);
+ } else {
+ cell.setFont(this.getColumnFont(element, columnIndex));
+ cell.setBackground(transparent);
+ }
+
+ if (isSearchEnabled()) {
+ if (isMatchingToPattern(element, columnIndex) ) {
+ List<StyleRange> styleRanges = new ArrayList<StyleRange>();
+ FilterInfo filterInfo = (FilterInfo) ((Term)element).getInfo();
+
+ for (Region reg : filterInfo.getFoundInTranslationRanges(translations.get(columnIndex < referenceColumn ? columnIndex + 1 : columnIndex))) {
+ styleRanges.add(new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD));
+ }
+
+ cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()]));
+ } else {
+ cell.setForeground(gray);
+ }
+ }
+ }
+
+ private boolean isCrossRefRegion(String cellText) {
+ if (selectedItem != null) {
+ for (IMessage entry : selectedItem.getMessagesBundleGroup().getMessages(selectedItem.getMessageKey())) {
+ String value = entry.getValue();
+ String[] subValues = value.split("[\\s\\p{Punct}]+");
+ for (String v : subValues) {
+ if (v.trim().equalsIgnoreCase(cellText.trim()))
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private Font getColumnFont(Object element, int columnIndex) {
+ if (columnIndex == 0) {
+ return bold_italic;
+ }
+ return null;
+ }
+
+ @Override
+ public void selectionChanged(IWorkbenchPart part, ISelection selection) {
+ try {
+ if (selection.isEmpty())
+ return;
+
+ if (!(selection instanceof IStructuredSelection))
+ return;
+
+ IStructuredSelection sel = (IStructuredSelection) selection;
+ selectedItem = (IKeyTreeNode) sel.iterator().next();
+ this.getViewer().refresh();
+ } catch (Exception e) {
+ // silent catch
+ }
+ }
+
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ event.getSelection();
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
index e8de6d4c..fb4390a4 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java
@@ -1,85 +1,92 @@
-package org.eclipselabs.tapiji.translator.views.widgets.sorter;
-
-import java.util.List;
-
-import org.eclipse.jface.viewers.StructuredViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipselabs.tapiji.translator.model.Term;
-import org.eclipselabs.tapiji.translator.model.Translation;
-
-
-public class GlossaryEntrySorter extends ViewerSorter {
-
- private StructuredViewer viewer;
- private SortInfo sortInfo;
- private int referenceCol;
- private List<String> translations;
-
- public GlossaryEntrySorter (StructuredViewer viewer,
- SortInfo sortInfo,
- int referenceCol,
- List<String> translations) {
- this.viewer = viewer;
- this.referenceCol = referenceCol;
- this.translations = translations;
-
- if (sortInfo != null)
- this.sortInfo = sortInfo;
- else
- this.sortInfo = new SortInfo();
- }
-
- public StructuredViewer getViewer() {
- return viewer;
- }
-
- public void setViewer(StructuredViewer viewer) {
- this.viewer = viewer;
- }
-
- public SortInfo getSortInfo() {
- return sortInfo;
- }
-
- public void setSortInfo(SortInfo sortInfo) {
- this.sortInfo = sortInfo;
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- try {
- if (!(e1 instanceof Term && e2 instanceof Term))
- return super.compare(viewer, e1, e2);
- Term comp1 = (Term) e1;
- Term comp2 = (Term) e2;
-
- int result = 0;
-
- if (sortInfo == null)
- return 0;
-
- if (sortInfo.getColIdx() == 0) {
- Translation transComp1 = comp1.getTranslation(translations.get(referenceCol));
- Translation transComp2 = comp2.getTranslation(translations.get(referenceCol));
- if (transComp1 != null && transComp2 != null)
- result = transComp1.value.compareTo(transComp2.value);
- } else {
- int col = sortInfo.getColIdx() < referenceCol ? sortInfo.getColIdx() + 1 : sortInfo.getColIdx();
- Translation transComp1 = comp1.getTranslation(translations.get(col));
- Translation transComp2 = comp2.getTranslation(translations.get(col));
-
- if (transComp1 == null)
- transComp1 = new Translation();
- if (transComp2 == null)
- transComp2 = new Translation();
- result = transComp1.value.compareTo(transComp2.value);
- }
-
- return result * (sortInfo.isDESC() ? -1 : 1);
- } catch (Exception e) {
- return 0;
- }
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.sorter;
+
+import java.util.List;
+
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerSorter;
+import org.eclipselabs.tapiji.translator.model.Term;
+import org.eclipselabs.tapiji.translator.model.Translation;
+
+
+public class GlossaryEntrySorter extends ViewerSorter {
+
+ private StructuredViewer viewer;
+ private SortInfo sortInfo;
+ private int referenceCol;
+ private List<String> translations;
+
+ public GlossaryEntrySorter (StructuredViewer viewer,
+ SortInfo sortInfo,
+ int referenceCol,
+ List<String> translations) {
+ this.viewer = viewer;
+ this.referenceCol = referenceCol;
+ this.translations = translations;
+
+ if (sortInfo != null)
+ this.sortInfo = sortInfo;
+ else
+ this.sortInfo = new SortInfo();
+ }
+
+ public StructuredViewer getViewer() {
+ return viewer;
+ }
+
+ public void setViewer(StructuredViewer viewer) {
+ this.viewer = viewer;
+ }
+
+ public SortInfo getSortInfo() {
+ return sortInfo;
+ }
+
+ public void setSortInfo(SortInfo sortInfo) {
+ this.sortInfo = sortInfo;
+ }
+
+ @Override
+ public int compare(Viewer viewer, Object e1, Object e2) {
+ try {
+ if (!(e1 instanceof Term && e2 instanceof Term))
+ return super.compare(viewer, e1, e2);
+ Term comp1 = (Term) e1;
+ Term comp2 = (Term) e2;
+
+ int result = 0;
+
+ if (sortInfo == null)
+ return 0;
+
+ if (sortInfo.getColIdx() == 0) {
+ Translation transComp1 = comp1.getTranslation(translations.get(referenceCol));
+ Translation transComp2 = comp2.getTranslation(translations.get(referenceCol));
+ if (transComp1 != null && transComp2 != null)
+ result = transComp1.value.compareTo(transComp2.value);
+ } else {
+ int col = sortInfo.getColIdx() < referenceCol ? sortInfo.getColIdx() + 1 : sortInfo.getColIdx();
+ Translation transComp1 = comp1.getTranslation(translations.get(col));
+ Translation transComp2 = comp2.getTranslation(translations.get(col));
+
+ if (transComp1 == null)
+ transComp1 = new Translation();
+ if (transComp2 == null)
+ transComp2 = new Translation();
+ result = transComp1.value.compareTo(transComp2.value);
+ }
+
+ return result * (sortInfo.isDESC() ? -1 : 1);
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+
+}
diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
index a5f8e99e..ec08283b 100644
--- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java
@@ -1,56 +1,63 @@
-package org.eclipselabs.tapiji.translator.views.widgets.sorter;
-
-import java.util.List;
-import java.util.Locale;
-
-import org.eclipse.ui.IMemento;
-
-
-public class SortInfo {
-
- public static final String TAG_SORT_INFO = "sort_info";
- public static final String TAG_COLUMN_INDEX = "col_idx";
- public static final String TAG_ORDER = "order";
-
- private int colIdx;
- private boolean DESC;
- private List<Locale> visibleLocales;
-
- public void setDESC(boolean dESC) {
- DESC = dESC;
- }
-
- public boolean isDESC() {
- return DESC;
- }
-
- public void setColIdx(int colIdx) {
- this.colIdx = colIdx;
- }
-
- public int getColIdx() {
- return colIdx;
- }
-
- public void setVisibleLocales(List<Locale> visibleLocales) {
- this.visibleLocales = visibleLocales;
- }
-
- public List<Locale> getVisibleLocales() {
- return visibleLocales;
- }
-
- public void saveState (IMemento memento) {
- IMemento mCI = memento.createChild(TAG_SORT_INFO);
- mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
- mCI.putBoolean(TAG_ORDER, DESC);
- }
-
- public void init (IMemento memento) {
- IMemento mCI = memento.getChild(TAG_SORT_INFO);
- if (mCI == null)
- return;
- colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
- DESC = mCI.getBoolean(TAG_ORDER);
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2012 TapiJI.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator.views.widgets.sorter;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.eclipse.ui.IMemento;
+
+
+public class SortInfo {
+
+ public static final String TAG_SORT_INFO = "sort_info";
+ public static final String TAG_COLUMN_INDEX = "col_idx";
+ public static final String TAG_ORDER = "order";
+
+ private int colIdx;
+ private boolean DESC;
+ private List<Locale> visibleLocales;
+
+ public void setDESC(boolean dESC) {
+ DESC = dESC;
+ }
+
+ public boolean isDESC() {
+ return DESC;
+ }
+
+ public void setColIdx(int colIdx) {
+ this.colIdx = colIdx;
+ }
+
+ public int getColIdx() {
+ return colIdx;
+ }
+
+ public void setVisibleLocales(List<Locale> visibleLocales) {
+ this.visibleLocales = visibleLocales;
+ }
+
+ public List<Locale> getVisibleLocales() {
+ return visibleLocales;
+ }
+
+ public void saveState (IMemento memento) {
+ IMemento mCI = memento.createChild(TAG_SORT_INFO);
+ mCI.putInteger(TAG_COLUMN_INDEX, colIdx);
+ mCI.putBoolean(TAG_ORDER, DESC);
+ }
+
+ public void init (IMemento memento) {
+ IMemento mCI = memento.getChild(TAG_SORT_INFO);
+ if (mCI == null)
+ return;
+ colIdx = mCI.getInteger(TAG_COLUMN_INDEX);
+ DESC = mCI.getBoolean(TAG_ORDER);
+ }
+}
|
ebfb482c3ee955f24be4d2802c1e06d6f0aa0d1c
|
restlet-framework-java
|
Removed debug traces.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java b/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java
index 142b1c1b3a..4fee45c339 100755
--- a/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java
+++ b/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java
@@ -328,10 +328,8 @@ public void execute() throws Exception {
ClientResource resource = new ClientResource(targetUri);
resource.setChallengeResponse(service.getCredentials());
- Representation result = new StringRepresentation(resource.get(
- MediaType.APPLICATION_ATOM).getText());
- System.out.println(targetUri);
- System.out.println(result.getText());
+ Representation result = resource.get(MediaType.APPLICATION_ATOM);
+
service.setLatestRequest(resource.getRequest());
service.setLatestResponse(resource.getResponse());
|
08894a81b8ba840c6966aec9d7304769d8412b9d
|
orientdb
|
Fix failed WAL test.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java
index e04e3aa39b5..27178b452c8 100755
--- a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java
+++ b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java
@@ -6,18 +6,10 @@
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Random;
+import java.util.*;
import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
+import org.testng.annotations.*;
import com.orientechnologies.common.serialization.types.OIntegerSerializer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
@@ -1385,6 +1377,7 @@ public void testThirdPageCRCWasIncorrect() throws Exception {
RandomAccessFile rndFile = new RandomAccessFile(new File(testDir, "WriteAheadLogTest.0.wal"), "rw");
rndFile.seek(2 * OWALPage.PAGE_SIZE);
int bt = rndFile.read();
+ rndFile.seek(2 * OWALPage.PAGE_SIZE);
rndFile.write(bt + 1);
rndFile.close();
|
1e6e05830c8eb3f482ae40016879c7a835697b8b
|
arquillian$arquillian-graphene
|
ARQGRA-464 @Page method param injection - added support for @InFrame
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/api/src/main/java/org/jboss/arquillian/graphene/page/InFrame.java b/api/src/main/java/org/jboss/arquillian/graphene/page/InFrame.java
index 638711a61..1e0675317 100644
--- a/api/src/main/java/org/jboss/arquillian/graphene/page/InFrame.java
+++ b/api/src/main/java/org/jboss/arquillian/graphene/page/InFrame.java
@@ -39,7 +39,7 @@
* @author Juraj Huska
*/
@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.FIELD)
+@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface InFrame {
/**
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java
index e02a418a8..827d9d6c4 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/FieldAccessValidatorEnricher.java
@@ -62,8 +62,8 @@ protected void checkFieldValidity(final SearchContext searchContext, final Objec
}
@Override
- public Object[] resolve(SearchContext searchContext, Method method) {
- return new Object[method.getParameterTypes().length];
+ public Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams) {
+ return resolvedParams;
}
@Override
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java
index 9639fb82d..10b9841f4 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/GrapheneEnricher.java
@@ -77,12 +77,7 @@ public Object[] resolve(Method method) {
for (SearchContextTestEnricher enricher : sortedSearchContextEnrichers) {
if (isApplicableToTestClass(enricher)) {
- Object[] resolved = enricher.resolve(null, method);
- for (int i = 0; i < resolvedParams.length; i++) {
- if (resolved[i] != null) {
- resolvedParams[i] = resolved[i];
- }
- }
+ resolvedParams = enricher.resolve(null, method, resolvedParams);
}
}
return resolvedParams;
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/InFrameEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/InFrameEnricher.java
index 5cd5227bc..5906cd1a8 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/InFrameEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/InFrameEnricher.java
@@ -21,9 +21,12 @@
*/
package org.jboss.arquillian.graphene.enricher;
+import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
import org.jboss.arquillian.graphene.enricher.exception.GrapheneTestEnricherException;
import org.jboss.arquillian.graphene.page.InFrame;
@@ -64,14 +67,43 @@ public void enrich(SearchContext searchContext, Object objectToEnrich) {
}
@Override
- public Object[] resolve(SearchContext searchContext, Method method) {
- return new Object[method.getParameterTypes().length];
+ public Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams) {
+ StringBuffer errorMsgBegin = new StringBuffer("");
+ List<Object[]> paramCouple = new LinkedList<Object[]>();
+ paramCouple.addAll(ReflectionHelper.getParametersWithAnnotation(method, InFrame.class));
+
+ for (int i = 0; i < resolvedParams.length; i++) {
+ if (paramCouple.get(i) != null && resolvedParams[i] != null) {
+ Class<?> param = (Class<?>) paramCouple.get(i)[0];
+ Annotation[] parameterAnnotations = (Annotation[]) paramCouple.get(i)[1];
+ InFrame inFrame = ReflectionHelper.findAnnotation(parameterAnnotations, InFrame.class);
+ int index = inFrame.index();
+ String nameOrId = inFrame.nameOrId();
+ checkInFrameParameters(method, param, index, nameOrId);
+
+ try {
+ registerInFrameInterceptor((GrapheneProxyInstance) resolvedParams[i], index, nameOrId);
+ } catch (IllegalArgumentException e) {
+ throw new GrapheneTestEnricherException(
+ "Only org.openqa.selenium.WebElement, Page fragments fields and Page Object fields can be annotated with @InFrame. Check parameter "
+ + param + " of the method: " + method.getName() + " declared in: " + method
+ .getDeclaringClass(), e);
+ } catch (Exception e) {
+ throw new GrapheneTestEnricherException(e);
+ }
+ }
+ }
+ return resolvedParams;
}
private void registerInFrameInterceptor(Object objectToEnrich, Field field, int index, String nameOrId)
throws IllegalAccessException, ClassNotFoundException {
GrapheneProxyInstance proxy = (GrapheneProxyInstance) field.get(objectToEnrich);
+ registerInFrameInterceptor(proxy, index, nameOrId);
+ }
+
+ private void registerInFrameInterceptor(GrapheneProxyInstance proxy, int index, String nameOrId) {
if (index != -1) {
proxy.registerInterceptor(new InFrameInterceptor(index));
} else {
@@ -80,13 +112,25 @@ private void registerInFrameInterceptor(Object objectToEnrich, Field field, int
}
private void checkInFrameParameters(Field field, int index, String nameOrId) {
- if ((nameOrId.trim().equals("") && index < 0)) {
+ if (checkInFrameParameters(index, nameOrId)) {
throw new GrapheneTestEnricherException(
"You have to provide either non empty nameOrId or non negative index value of the frame/iframe in the @InFrame. Check field "
+ field + " declared in: " + field.getDeclaringClass());
}
}
+ private void checkInFrameParameters(Method method, Class<?> param, int index, String nameOrId) {
+ if (checkInFrameParameters(index, nameOrId)) {
+ throw new GrapheneTestEnricherException(
+ "You have to provide either non empty nameOrId or non negative index value of the frame/iframe in the @InFrame. Check parameter "
+ + param + " of the method: " + method.getName() + " declared in: " + method.getDeclaringClass());
+ }
+ }
+
+ private boolean checkInFrameParameters(int index, String nameOrId) {
+ return nameOrId.trim().equals("") && index < 0;
+ }
+
@Override
public int getPrecedence() {
return 0;
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java
index 0d35ff148..ecf9e1b3d 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/JavaScriptEnricher.java
@@ -56,8 +56,8 @@ public void enrich(final SearchContext searchContext, Object target) {
}
@Override
- public Object[] resolve(SearchContext searchContext, Method method) {
- return new Object[method.getParameterTypes().length];
+ public Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams) {
+ return resolvedParams;
}
@Override
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
index 8521839ed..13bcef02e 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageFragmentEnricher.java
@@ -98,8 +98,8 @@ public void enrich(final SearchContext searchContext, Object target) {
}
@Override
- public Object[] resolve(SearchContext searchContext, Method method) {
- return new Object[method.getParameterTypes().length];
+ public Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams) {
+ return resolvedParams;
}
protected final boolean isPageFragmentClass(Class<?> clazz, Object target) {
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java
index 90542e943..51eecb7d6 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/PageObjectEnricher.java
@@ -58,23 +58,20 @@ public void enrich(final SearchContext searchContext, Object target) {
}
@Override
- public Object[] resolve(SearchContext searchContext, Method method) {
+ public Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams) {
StringBuffer errorMsgBegin = new StringBuffer("");
List<Object[]> paramCouple = new LinkedList<Object[]>();
paramCouple.addAll(ReflectionHelper.getParametersWithAnnotation(method, Page.class));
- Object[] resolution = new Object[method.getParameterTypes().length];
- for (int i = 0; i < resolution.length; i++) {
- if (paramCouple.get(i) == null) {
- resolution[i] = null;
- } else {
+ for (int i = 0; i < resolvedParams.length; i++) {
+ if (paramCouple.get(i) != null) {
Class<?> param = (Class<?>) paramCouple.get(i)[0];
Annotation[] parameterAnnotations = (Annotation[]) paramCouple.get(i)[1];
Object page = createPage(searchContext, parameterAnnotations, null, null, method, param);
- resolution[i] = page;
+ resolvedParams[i] = page;
}
}
- return resolution;
+ return resolvedParams;
}
private Object createPage(SearchContext searchContext, Annotation[] annotations, Object target, Field field,
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java
index 0497f744a..72f7257ba 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/ReflectionHelper.java
@@ -273,11 +273,13 @@ public List<Method> run() {
}
/**
- * Returns all the parameters annotated with the given annotation for the specified method
+ * Returns all couples of found parameter annotated with the given annotation and an array of all annotations the
+ * parameter is annotated with for the given method
*
* @param method - the method where the parameters should be examined
* @param annotationClass - the annotation the parameters should be annotated with
- * @return list of found parameters annotated with the given annotation
+ * @return list of couples in an object array that consist of found parameter annotated with the given annotation
+ * and an array of all annotations the parameter is annotated with
*/
public static List<Object[]> getParametersWithAnnotation(final Method method,
final Class<? extends Annotation> annotationClass) {
@@ -324,7 +326,7 @@ private static boolean isAnnotationPresent(final Annotation[] annotations, final
* @return the found annotation
*/
@SuppressWarnings("unchecked")
- private static <T extends Annotation> T findAnnotation(final Annotation[] annotations, final Class<T> needle) {
+ public static <T extends Annotation> T findAnnotation(final Annotation[] annotations, final Class<T> needle) {
for (Annotation annotation : annotations) {
if (annotation.annotationType() == needle) {
return (T) annotation;
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
index e1994ce9e..eaec572e1 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementEnricher.java
@@ -84,8 +84,8 @@ && getListType(field).isAssignableFrom(WebElement.class)) {
}
@Override
- public Object[] resolve(SearchContext searchContext, Method method) {
- return new Object[method.getParameterTypes().length];
+ public Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams) {
+ return resolvedParams;
}
@Override
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java
index 0cdafa31f..fb6406143 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/enricher/WebElementWrapperEnricher.java
@@ -122,8 +122,8 @@ public void enrich(final SearchContext searchContext, Object target) {
}
@Override
- public Object[] resolve(SearchContext searchContext, Method method) {
- return new Object[method.getParameterTypes().length];
+ public Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams) {
+ return resolvedParams;
}
protected <T> T createWrapper(GrapheneContext grapheneContext, final Class<T> type, final WebElement element)
diff --git a/spi/src/main/java/org/jboss/arquillian/graphene/spi/enricher/SearchContextTestEnricher.java b/spi/src/main/java/org/jboss/arquillian/graphene/spi/enricher/SearchContextTestEnricher.java
index 1eb3b8f4e..a50671fce 100644
--- a/spi/src/main/java/org/jboss/arquillian/graphene/spi/enricher/SearchContextTestEnricher.java
+++ b/spi/src/main/java/org/jboss/arquillian/graphene/spi/enricher/SearchContextTestEnricher.java
@@ -45,11 +45,11 @@ public interface SearchContextTestEnricher {
/**
* Performs resolve for the given method with the given {@link SearchContext}.
- *
* @param searchContext the context which should be used for resolve
* @param method method to be resolved
+ * @param resolvedParams parameters that has (not) been resolved so far
*/
- Object[] resolve(SearchContext searchContext, Method method);
+ Object[] resolve(SearchContext searchContext, Method method, Object[] resolvedParams);
/**
* Returns the enricher precedence. Zero precedence is is the lowest one.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.