commit_id
stringlengths 40
40
| project
stringclasses 90
values | commit_message
stringlengths 5
2.21k
| type
stringclasses 3
values | url
stringclasses 89
values | git_diff
stringlengths 283
4.32M
|
|---|---|---|---|---|---|
2d2e9e06218153e725310e1b24cefb870cda12cc
|
elasticsearch
|
fixed issue from merge--
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DiversifiedSamplerIT.java b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DiversifiedSamplerIT.java
index f7cbfa7fcb894..23b0513545cbf 100644
--- a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DiversifiedSamplerIT.java
+++ b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DiversifiedSamplerIT.java
@@ -215,7 +215,7 @@ public void testPartiallyUnmappedDiversifyField() throws Exception {
.execute().actionGet();
assertSearchResponse(response);
Sampler sample = response.getAggregations().get("sample");
- assertThat(sample.getDocCount(), greaterThan(0l));
+ assertThat(sample.getDocCount(), greaterThan(0L));
Terms authors = sample.getAggregations().get("authors");
assertThat(authors.getBuckets().size(), greaterThan(0));
}
@@ -230,7 +230,7 @@ public void testWhollyUnmappedDiversifyField() throws Exception {
.setQuery(new TermQueryBuilder("genre", "fantasy")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet();
assertSearchResponse(response);
Sampler sample = response.getAggregations().get("sample");
- assertThat(sample.getDocCount(), equalTo(0l));
+ assertThat(sample.getDocCount(), equalTo(0L));
Terms authors = sample.getAggregations().get("authors");
assertNull(authors);
}
|
cd6cfc6a92d3e2666713c793e2a1b9db3c5ba485
|
eclipse$vert.x
|
Remove broken redeploy functionality, and change isolation group behaviour to only isolate explicitly declared classes and packages, this results in a much simpler (usually) parent first delegation model which generally helps us all to retain our sanity.
|
p
|
https://github.com/eclipse-vertx/vert.x
|
diff --git a/pom.xml b/pom.xml
index bbed52e89ef..c7860860bd0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -178,9 +178,6 @@
<version>${maven.surefire.plugin.version}</version>
<configuration>
<failIfNoSpecifiedTests>false</failIfNoSpecifiedTests>
- <excludes>
- <exclude>**/RedeploySourceVerticle.java</exclude>
- </excludes>
<additionalClasspathElements>
<additionalClasspathElement>${project.build.testSourceDirectory}</additionalClasspathElement>
<additionalClasspathElement>${basedir}/src/test/resources/webroot2.jar</additionalClasspathElement>
diff --git a/src/main/asciidoc/cheatsheet/DeploymentOptions.adoc b/src/main/asciidoc/cheatsheet/DeploymentOptions.adoc
index f7c380caa09..a0fc3eefde8 100644
--- a/src/main/asciidoc/cheatsheet/DeploymentOptions.adoc
+++ b/src/main/asciidoc/cheatsheet/DeploymentOptions.adoc
@@ -43,12 +43,6 @@ Set any extra classpath to be used when deploying the verticle.
|+++
Set the number of instances that should be deployed.+++
-|[[redeploy]]`redeploy`
-|`Boolean`
-|-
-|[[redeployScanInterval]]`redeployScanInterval`
-|`Number`
-|-
-|[[redeployGraceInterval]]`redeployGraceInterval`
-|`Number`
+|[[isolatedClasses]]`isolatedClasses`
+|`Array of String`
|-|===
diff --git a/src/main/asciidoc/java/index.adoc b/src/main/asciidoc/java/index.adoc
index fda542c8ffd..6ae6a463734 100644
--- a/src/main/asciidoc/java/index.adoc
+++ b/src/main/asciidoc/java/index.adoc
@@ -484,8 +484,8 @@ include::override/verticle-configuration.adoc[]
=== Verticle Isolation Groups
-By default, Vert.x has a _flat classpath_. I.e, it does everything, including deploying verticles without messing
-with class-loaders. In the majority of cases this is the simplest, clearest and sanest thing to do.
+By default, Vert.x has a _flat classpath_. I.e, when Vert.x deploys verticles it does so with the current classloader -
+it doesn't create a new one. In the majority of cases this is the simplest, clearest and sanest thing to do.
However, in some cases you may want to deploy a verticle so the classes of that verticle are isolated from others in
your application.
@@ -493,6 +493,18 @@ your application.
This might be the case, for example, if you want to deploy two different versions of a verticle with the same class name
in the same Vert.x instance, or if you have two different verticles which use different versions of the same jar library.
+When using an isolation group you provide a list of the class names that you want isolated using
+`link:../../apidocs/io/vertx/core/DeploymentOptions.html#setIsolatedClasses-java.util.List-[setIsolatedClasses]`- an entry can be a fully qualified
+classname such as `com.mycompany.myproject.engine.MyClass` or it can be a wildcard which will match any classes in a package and any
+sub-packages, e.g. `com.mycompany.myproject.*` would match any classes in the package `com.mycompany.myproject` or
+any sub-packages.
+
+Please note that _only_ the classes that match will be isolated - any other classes will be loaded by the current
+class loader.
+
+Extra classpath entries can also be provided with `link:../../apidocs/io/vertx/core/DeploymentOptions.html#setExtraClasspath-java.util.List-[setExtraClasspath]` so if
+you want to load classes or resources that aren't already present on the main claspath you can add this.
+
WARNING: Use this feature with caution. Class-loaders can be a can of worms, and can make debugging difficult, amongst
other things.
@@ -501,16 +513,11 @@ Here's an example of using an isolation group to isolate a verticle deployment.
[source,java]
----
DeploymentOptions options = new DeploymentOptions().setIsolationGroup("mygroup");
-options.setExtraClasspath(Arrays.asList("lib/jars/some-library.jar"));
-vertx.deployVerticle("com.mycompany.MyIsolatedVerticle", options);
+options.setIsolatedClasses(Arrays.asList("com.mycompany.myverticle.*",
+ "com.mycompany.somepkg.SomeClass", "org.somelibrary.*"));
+vertx.deployVerticle("com.mycompany.myverticle.VerticleClass", options);
----
-Isolation groups are identified by a name, and the name can be used between different deployments if you want them
-to share an isolated class-loader.
-
-Extra classpath entries can also be provided with `link:../../apidocs/io/vertx/core/DeploymentOptions.html#setExtraClasspath-java.util.List-[setExtraClasspath]` so they
-can locate resources that are isolated to them.
-
=== High Availability
Verticles can be deployed with High Availability (HA) enabled. In that context, when a verticle is deployed on
@@ -847,7 +854,6 @@ one instance. If omitted a single instance will be deployed.
* `-hagroup` - used in conjunction with `-ha`. It specifies the HA group this node will join. There can be
multiple HA groups in a cluster. Nodes will only failover to other nodes in the same group. The default value is `
+++__DEFAULT__+++`
- * `-redeploy` - Enables automatic redeployment of the verticle
Here are some more examples:
@@ -943,20 +949,6 @@ To display the vert.x version, just launch:
vertx -version
----
-=== Using the redeploy argument
-
-When a verticle is launched with `vertx run .... -redeploy`, vertx redeploys the verticle every time the verticle
-files change. This mode makes the development much more fun and efficient as you don't have to restart the
-application.
-
-[source]
-----
-vertx run server.js -redeploy
-vertx run Server.java -redeploy
-----
-
-When using Java source file, vert.x recompiles the class on the fly and redeploys the verticle.
-
== Cluster Managers
In Vert.x a cluster manager is used for various functions including:
diff --git a/src/main/java/examples/CoreExamples.java b/src/main/java/examples/CoreExamples.java
index 85bc3997f0f..c862f8318ca 100644
--- a/src/main/java/examples/CoreExamples.java
+++ b/src/main/java/examples/CoreExamples.java
@@ -149,8 +149,9 @@ public void example13(Vertx vertx) {
public void example14(Vertx vertx) {
DeploymentOptions options = new DeploymentOptions().setIsolationGroup("mygroup");
- options.setExtraClasspath(Arrays.asList("lib/jars/some-library.jar"));
- vertx.deployVerticle("com.mycompany.MyIsolatedVerticle", options);
+ options.setIsolatedClasses(Arrays.asList("com.mycompany.myverticle.*",
+ "com.mycompany.somepkg.SomeClass", "org.somelibrary.*"));
+ vertx.deployVerticle("com.mycompany.myverticle.VerticleClass", options);
}
public void example15(Vertx vertx) {
diff --git a/src/main/java/io/vertx/core/DeploymentOptions.java b/src/main/java/io/vertx/core/DeploymentOptions.java
index ba56b4a305c..41fb5dcdd27 100644
--- a/src/main/java/io/vertx/core/DeploymentOptions.java
+++ b/src/main/java/io/vertx/core/DeploymentOptions.java
@@ -38,9 +38,6 @@ public class DeploymentOptions {
public static final String DEFAULT_ISOLATION_GROUP = null;
public static final boolean DEFAULT_HA = false;
public static final int DEFAULT_INSTANCES = 1;
- public static final boolean DEFAULT_REDEPLOY = false;
- public static final long DEFAULT_REDEPLOY_SCAN_INTERVAL = 250;
- public static final long DEFAULT_REDEPLOY_GRACE_INTERVAL = 1000;
private JsonObject config;
private boolean worker;
@@ -49,9 +46,7 @@ public class DeploymentOptions {
private boolean ha;
private List<String> extraClasspath;
private int instances;
- private boolean redeploy;
- private long redeployScanInterval;
- private long redeployGraceInterval;
+ private List<String> isolatedClasses;
/**
* Default constructor
@@ -63,9 +58,6 @@ public DeploymentOptions() {
this.isolationGroup = DEFAULT_ISOLATION_GROUP;
this.ha = DEFAULT_HA;
this.instances = DEFAULT_INSTANCES;
- this.redeploy = DEFAULT_REDEPLOY;
- this.redeployScanInterval = DEFAULT_REDEPLOY_SCAN_INTERVAL;
- this.redeployGraceInterval = DEFAULT_REDEPLOY_GRACE_INTERVAL;
}
/**
@@ -81,9 +73,7 @@ public DeploymentOptions(DeploymentOptions other) {
this.ha = other.isHa();
this.extraClasspath = other.getExtraClasspath() == null ? null : new ArrayList<>(other.getExtraClasspath());
this.instances = other.instances;
- this.redeploy = other.redeploy;
- this.redeployScanInterval = other.redeployScanInterval;
- this.redeployGraceInterval = other.redeployGraceInterval;
+ this.isolatedClasses = other.getIsolatedClasses() == null ? null : new ArrayList<>(other.getIsolatedClasses());
}
/**
@@ -111,9 +101,10 @@ public void fromJson(JsonObject json) {
this.extraClasspath = arr.getList();
}
this.instances = json.getInteger("instances", DEFAULT_INSTANCES);
- this.redeploy = json.getBoolean("redeploy", DEFAULT_REDEPLOY);
- this.redeployScanInterval = json.getLong("redeployScanInterval", DEFAULT_REDEPLOY_SCAN_INTERVAL);
- this.redeployGraceInterval = json.getLong("redeployGraceInterval", DEFAULT_REDEPLOY_GRACE_INTERVAL);
+ JsonArray arrIsolated = json.getJsonArray("isolatedClasses", null);
+ if (arrIsolated != null) {
+ this.isolatedClasses = arrIsolated.getList();
+ }
}
/**
@@ -198,34 +189,6 @@ public DeploymentOptions setIsolationGroup(String isolationGroup) {
return this;
}
- /**
- * Convert this to JSON
- *
- * @return the JSON
- */
- public JsonObject toJson() {
- JsonObject json = new JsonObject();
- if (worker) json.put("worker", true);
- if (multiThreaded) json.put("multiThreaded", true);
- if (isolationGroup != null) json.put("isolationGroup", isolationGroup);
- if (ha) json.put("ha", true);
- if (config != null) json.put("config", config);
- if (extraClasspath != null) json.put("extraClasspath", new JsonArray(extraClasspath));
- if (instances != DEFAULT_INSTANCES) {
- json.put("instances", instances);
- }
- if (redeploy != DEFAULT_REDEPLOY) {
- json.put("redeploy", redeploy);
- }
- if (redeployScanInterval != DEFAULT_REDEPLOY_SCAN_INTERVAL) {
- json.put("redeployScanInterval", redeployScanInterval);
- }
- if (redeployGraceInterval != DEFAULT_REDEPLOY_GRACE_INTERVAL) {
- json.put("redeployGraceInterval", redeployGraceInterval);
- }
- return json;
- }
-
/**
* Will the verticle(s) be deployed as HA (highly available) ?
*
@@ -289,37 +252,33 @@ public DeploymentOptions setInstances(int instances) {
return this;
}
- public boolean isRedeploy() {
- return redeploy;
- }
-
- public DeploymentOptions setRedeploy(boolean redeploy) {
- this.redeploy = redeploy;
- return this;
+ public List<String> getIsolatedClasses() {
+ return isolatedClasses;
}
- public long getRedeployScanInterval() {
- return redeployScanInterval;
- }
-
- public DeploymentOptions setRedeployScanInterval(long redeployScanInterval) {
- if (redeployScanInterval < 1) {
- throw new IllegalArgumentException("redeployScanInterval must be > 0");
- }
- this.redeployScanInterval = redeployScanInterval;
+ public DeploymentOptions setIsolatedClasses(List<String> isolatedClasses) {
+ this.isolatedClasses = isolatedClasses;
return this;
}
- public long getRedeployGraceInterval() {
- return redeployGraceInterval;
- }
-
- public DeploymentOptions setRedeployGraceInterval(long redeployGraceInterval) {
- if (redeployGraceInterval < 1) {
- throw new IllegalArgumentException("redeployGraceInterval must be > 0");
+ /**
+ * Convert this to JSON
+ *
+ * @return the JSON
+ */
+ public JsonObject toJson() {
+ JsonObject json = new JsonObject();
+ if (worker) json.put("worker", true);
+ if (multiThreaded) json.put("multiThreaded", true);
+ if (isolationGroup != null) json.put("isolationGroup", isolationGroup);
+ if (ha) json.put("ha", true);
+ if (config != null) json.put("config", config);
+ if (extraClasspath != null) json.put("extraClasspath", new JsonArray(extraClasspath));
+ if (instances != DEFAULT_INSTANCES) {
+ json.put("instances", instances);
}
- this.redeployGraceInterval = redeployGraceInterval;
- return this;
+ if (isolatedClasses != null) json.put("isolatedClasses", new JsonArray(isolatedClasses));
+ return json;
}
@Override
@@ -329,20 +288,17 @@ public boolean equals(Object o) {
DeploymentOptions that = (DeploymentOptions) o;
- if (ha != that.ha) return false;
- if (multiThreaded != that.multiThreaded) return false;
if (worker != that.worker) return false;
+ if (multiThreaded != that.multiThreaded) return false;
+ if (ha != that.ha) return false;
+ if (instances != that.instances) return false;
if (config != null ? !config.equals(that.config) : that.config != null) return false;
- if (extraClasspath != null ? !extraClasspath.equals(that.extraClasspath) : that.extraClasspath != null)
- return false;
if (isolationGroup != null ? !isolationGroup.equals(that.isolationGroup) : that.isolationGroup != null)
return false;
- if (instances != that.instances) return false;
- if (redeploy != that.redeploy) return false;
- if (redeployScanInterval != that.redeployScanInterval) return false;
- if (redeployGraceInterval != that.redeployGraceInterval) return false;
+ if (extraClasspath != null ? !extraClasspath.equals(that.extraClasspath) : that.extraClasspath != null)
+ return false;
+ return !(isolatedClasses != null ? !isolatedClasses.equals(that.isolatedClasses) : that.isolatedClasses != null);
- return true;
}
@Override
@@ -354,9 +310,7 @@ public int hashCode() {
result = 31 * result + (ha ? 1 : 0);
result = 31 * result + (extraClasspath != null ? extraClasspath.hashCode() : 0);
result = 31 * result + instances;
- result = 31 * result + (redeploy ? 1 : 0);
- result = 31 * result + (int) (redeployScanInterval ^ (redeployScanInterval >>> 32));
- result = 31 * result + (int) (redeployGraceInterval ^ (redeployGraceInterval >>> 32));
+ result = 31 * result + (isolatedClasses != null ? isolatedClasses.hashCode() : 0);
return result;
}
}
diff --git a/src/main/java/io/vertx/core/Starter.java b/src/main/java/io/vertx/core/Starter.java
index 8aa45fe5877..a06541c0bad 100644
--- a/src/main/java/io/vertx/core/Starter.java
+++ b/src/main/java/io/vertx/core/Starter.java
@@ -17,7 +17,6 @@
package io.vertx.core;
import io.vertx.core.impl.Args;
-import io.vertx.core.impl.IsolatingClassLoader;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
@@ -31,13 +30,7 @@
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.*;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Properties;
-import java.util.Scanner;
-import java.util.ServiceLoader;
+import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -74,6 +67,8 @@ public static void main(String[] sargs) {
String extraCP = args.map.get("-cp");
if (extraCP != null) {
+ // If an extra CP is specified (e.g. to provide cp to a jar or cluster.xml) we must create a new classloader
+ // and run the starter using that so it's visible to the rest of the code
String[] parts = extraCP.split(PATH_SEP);
URL[] urls = new URL[parts.length];
for (int p = 0; p < parts.length; p++) {
@@ -86,7 +81,7 @@ public static void main(String[] sargs) {
throw new IllegalStateException(e);
}
}
- IsolatingClassLoader icl = new IsolatingClassLoader(urls, Starter.class.getClassLoader());
+ ClassLoader icl = new URLClassLoader(urls, Starter.class.getClassLoader());
ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(icl);
try {
@@ -273,7 +268,7 @@ private void runBare(Args args) {
return;
}
- // As we do not deploy a verticle, other options are irrelevant (instances, worker, conf and redeploy)
+ // As we do not deploy a verticle, other options are irrelevant (instances, worker, conf)
addShutdownHook(vertx);
block();
@@ -337,9 +332,13 @@ private void runVerticle(String main, Args args) {
deploymentOptions = new DeploymentOptions();
configureFromSystemProperties(deploymentOptions, DEPLOYMENT_OPTIONS_PROP_PREFIX);
- boolean redeploy = args.map.get("-redeploy") != null;
+ String cp = args.map.get("-cp");
+ if (cp == null) {
+ cp = "."; // default to current dir
+ }
+
+ deploymentOptions.setConfig(conf).setWorker(worker).setHa(ha).setInstances(instances);
- deploymentOptions.setConfig(conf).setWorker(worker).setHa(ha).setInstances(instances).setRedeploy(redeploy);
beforeDeployingVerticle(deploymentOptions);
vertx.deployVerticle(main, deploymentOptions, createLoggingHandler(message, res -> {
if (res.failed()) {
@@ -546,8 +545,7 @@ private void displaySyntax() {
" HA group this node will join. There can be \n" +
" multiple HA groups in a cluster. Nodes will only\n" +
" failover to other nodes in the same group. \n" +
- " Defaults to __DEFAULT__ \n" +
- " -redeploy Enable automatic redeployment \n\n" +
+ " Defaults to __DEFAULT__ \n\n" +
" vertx -version \n" +
" displays the version";
diff --git a/src/main/java/io/vertx/core/impl/DeploymentManager.java b/src/main/java/io/vertx/core/impl/DeploymentManager.java
index e64cf63d716..3a850defb54 100644
--- a/src/main/java/io/vertx/core/impl/DeploymentManager.java
+++ b/src/main/java/io/vertx/core/impl/DeploymentManager.java
@@ -16,12 +16,7 @@
package io.vertx.core.impl;
-import io.vertx.core.AsyncResult;
-import io.vertx.core.Context;
-import io.vertx.core.DeploymentOptions;
-import io.vertx.core.Future;
-import io.vertx.core.Handler;
-import io.vertx.core.Verticle;
+import io.vertx.core.*;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
@@ -29,20 +24,9 @@
import java.io.File;
import java.net.MalformedURLException;
-import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.Set;
-import java.util.UUID;
-import java.util.WeakHashMap;
+import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@@ -86,14 +70,17 @@ public void deployVerticle(Verticle verticle, DeploymentOptions options,
throw new IllegalArgumentException("Can't specify > 1 instances for already created verticle");
}
if (options.getExtraClasspath() != null) {
- throw new IllegalArgumentException("Can't specify extraClasspath instances for already created verticle");
+ throw new IllegalArgumentException("Can't specify extraClasspath for already created verticle");
}
if (options.getIsolationGroup() != null) {
- throw new IllegalArgumentException("Can't specify isolationGroup instances for already created verticle");
+ throw new IllegalArgumentException("Can't specify isolationGroup for already created verticle");
+ }
+ if (options.getIsolatedClasses() != null) {
+ throw new IllegalArgumentException("Can't specify isolatedClasses for already created verticle");
}
ContextImpl currentContext = vertx.getOrCreateContext();
doDeploy("java:" + verticle.getClass().getName(), generateDeploymentID(), options, currentContext, currentContext, completionHandler,
- getCurrentClassLoader(), null, verticle);
+ getCurrentClassLoader(), verticle);
}
public void deployVerticle(String identifier,
@@ -101,19 +88,7 @@ public void deployVerticle(String identifier,
Handler<AsyncResult<String>> completionHandler) {
ContextImpl callingContext = vertx.getOrCreateContext();
ClassLoader cl = getClassLoader(options, callingContext);
- Redeployer redeployer = getRedeployer(options, cl, callingContext);
- doDeployVerticle(identifier, generateDeploymentID(), options, callingContext, callingContext, cl, redeployer, completionHandler);
- }
-
- private void doRedeployVerticle(String identifier,
- String deploymentID,
- DeploymentOptions options,
- ContextImpl parentContext,
- ContextImpl callingContext,
- Redeployer redeployer,
- Handler<AsyncResult<String>> completionHandler) {
- ClassLoader cl = getClassLoader(options, parentContext);
- doDeployVerticle(identifier, deploymentID, options, parentContext, callingContext, cl, redeployer, completionHandler);
+ doDeployVerticle(identifier, generateDeploymentID(), options, callingContext, callingContext, cl, completionHandler);
}
private void doDeployVerticle(String identifier,
@@ -122,11 +97,10 @@ private void doDeployVerticle(String identifier,
ContextImpl parentContext,
ContextImpl callingContext,
ClassLoader cl,
- Redeployer redeployer,
Handler<AsyncResult<String>> completionHandler) {
List<VerticleFactory> verticleFactories = resolveFactories(identifier);
Iterator<VerticleFactory> iter = verticleFactories.iterator();
- doDeployVerticle(iter, null, identifier, deploymentID, options, parentContext, callingContext, cl, redeployer, completionHandler);
+ doDeployVerticle(iter, null, identifier, deploymentID, options, parentContext, callingContext, cl, completionHandler);
}
private void doDeployVerticle(Iterator<VerticleFactory> iter,
@@ -137,7 +111,6 @@ private void doDeployVerticle(Iterator<VerticleFactory> iter,
ContextImpl parentContext,
ContextImpl callingContext,
ClassLoader cl,
- Redeployer redeployer,
Handler<AsyncResult<String>> completionHandler) {
if (iter.hasNext()) {
VerticleFactory verticleFactory = iter.next();
@@ -171,7 +144,7 @@ private void doDeployVerticle(Iterator<VerticleFactory> iter,
throw new NullPointerException("VerticleFactory::createVerticle returned null");
}
}
- doDeploy(identifier, deploymentID, options, parentContext, callingContext, completionHandler, cl, redeployer, verticles);
+ doDeploy(identifier, deploymentID, options, parentContext, callingContext, completionHandler, cl, verticles);
return;
} catch (Exception e) {
err = e;
@@ -180,7 +153,7 @@ private void doDeployVerticle(Iterator<VerticleFactory> iter,
} else {
err = ar.cause();
}
- doDeployVerticle(iter, err, identifier, deploymentID, options, parentContext, callingContext, cl, redeployer, completionHandler);
+ doDeployVerticle(iter, err, identifier, deploymentID, options, parentContext, callingContext, cl, completionHandler);
});
} else {
if (prevErr != null) {
@@ -329,17 +302,7 @@ private List<VerticleFactory> resolveFactories(String identifier) {
return factoryList;
}
- private boolean isTopMostDeployment(ContextImpl context) {
- return context.getDeployment() == null;
- }
-
private ClassLoader getClassLoader(DeploymentOptions options, ContextImpl parentContext) {
- if (shouldEnableRedployment(options, parentContext)) {
- // For redeploy we need to use a unique value of isolationGroup as we need a new classloader each time
- // to ensure classes get reloaded, so we overwrite any value of isolation group
- // Also we only do redeploy on top most deploymentIDs
- setRedeployIsolationGroup(options);
- }
String isolationGroup = options.getIsolationGroup();
ClassLoader cl;
if (isolationGroup == null) {
@@ -352,7 +315,6 @@ private ClassLoader getClassLoader(DeploymentOptions options, ContextImpl parent
if (!(current instanceof URLClassLoader)) {
throw new IllegalStateException("Current classloader must be URLClassLoader");
}
- URLClassLoader urlc = (URLClassLoader)current;
List<URL> urls = new ArrayList<>();
// Add any extra URLs to the beginning of the classpath
List<String> extraClasspath = options.getExtraClasspath();
@@ -368,9 +330,12 @@ private ClassLoader getClassLoader(DeploymentOptions options, ContextImpl parent
}
}
// And add the URLs of the Vert.x classloader
+ URLClassLoader urlc = (URLClassLoader)current;
urls.addAll(Arrays.asList(urlc.getURLs()));
- // Copy the URLS into the isolating classloader
- cl = new IsolatingClassLoader(urls.toArray(new URL[urls.size()]), getCurrentClassLoader());
+
+ // Create an isolating cl with the urls
+ cl = new IsolatingClassLoader(urls.toArray(new URL[urls.size()]), getCurrentClassLoader(),
+ options.getIsolatedClasses());
classloaders.put(isolationGroup, cl);
}
}
@@ -378,35 +343,6 @@ private ClassLoader getClassLoader(DeploymentOptions options, ContextImpl parent
return cl;
}
- private void setRedeployIsolationGroup(DeploymentOptions options) {
- options.setIsolationGroup("redeploy-" + UUID.randomUUID().toString());
- }
-
- private boolean shouldEnableRedployment(DeploymentOptions options, ContextImpl parentContext) {
- return options.isRedeploy() && isTopMostDeployment(parentContext);
- }
-
- private Redeployer getRedeployer(DeploymentOptions options, ClassLoader cl, ContextImpl parentContext) {
- if (shouldEnableRedployment(options, parentContext)) {
- // We only do redeploy on top most deploymentIDs
- setRedeployIsolationGroup(options);
-
- URLClassLoader urlc = (URLClassLoader)cl;
- // Convert cp to files
- Set<File> filesToWatch = new HashSet<>();
- for (URL url: urlc.getURLs()) {
- try {
- filesToWatch.add(new File(url.toURI()));
- } catch (IllegalArgumentException | URISyntaxException ignore) {
- // Probably non file url
- }
- }
- return new Redeployer(filesToWatch, options.getRedeployGraceInterval());
- } else {
- return null;
- }
- }
-
private ClassLoader getCurrentClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
@@ -444,13 +380,13 @@ private void doDeploy(String identifier, String deploymentID, DeploymentOptions
ContextImpl parentContext,
ContextImpl callingContext,
Handler<AsyncResult<String>> completionHandler,
- ClassLoader tccl, Redeployer redeployer, Verticle... verticles) {
+ ClassLoader tccl, Verticle... verticles) {
if (options.isMultiThreaded() && !options.isWorker()) {
throw new IllegalArgumentException("If multi-threaded then must be worker too");
}
JsonObject conf = options.getConfig() == null ? new JsonObject() : options.getConfig().copy(); // Copy it
- DeploymentImpl deployment = new DeploymentImpl(deploymentID, identifier, options, redeployer, parentContext);
+ DeploymentImpl deployment = new DeploymentImpl(deploymentID, identifier, options);
Deployment parent = parentContext.getDeployment();
if (parent != null) {
@@ -475,7 +411,6 @@ private void doDeploy(String identifier, String deploymentID, DeploymentOptions
deployments.put(deploymentID, deployment);
if (deployCount.incrementAndGet() == verticles.length) {
reportSuccess(deploymentID, callingContext, completionHandler);
- deployment.startRedeployTimer();
}
} else if (!failureReported.get()) {
reportFailure(ar.cause(), callingContext, completionHandler);
@@ -505,20 +440,13 @@ private class DeploymentImpl implements Deployment {
private List<VerticleHolder> verticles = new ArrayList<>();
private final Set<Deployment> children = new ConcurrentHashSet<>();
private final DeploymentOptions options;
- private final Redeployer redeployer;
- private final ContextImpl parentContext; // This is the context that did the deploy, not the verticle context
private boolean undeployed;
- private boolean broken;
private volatile boolean child;
- private long redeployTimerID = -1;
- private DeploymentImpl(String deploymentID, String verticleIdentifier, DeploymentOptions options, Redeployer redeployer,
- ContextImpl parentContext) {
+ private DeploymentImpl(String deploymentID, String verticleIdentifier, DeploymentOptions options) {
this.deploymentID = deploymentID;
this.verticleIdentifier = verticleIdentifier;
this.options = options;
- this.redeployer = redeployer;
- this.parentContext = parentContext;
}
public void addVerticle(VerticleHolder holder) {
@@ -527,9 +455,6 @@ public void addVerticle(VerticleHolder holder) {
@Override
public void undeploy(Handler<AsyncResult<Void>> completionHandler) {
- if (redeployTimerID != -1) {
- vertx.cancelTimer(redeployTimerID);
- }
ContextImpl currentContext = vertx.getOrCreateContext();
if (!undeployed) {
doUndeploy(currentContext, completionHandler);
@@ -622,59 +547,6 @@ public String deploymentID() {
return deploymentID;
}
- // This is run on the context of the actual verticle, not the context that did the deploy
- private void startRedeployTimer() {
- // Redeployment is disabled.
- if (redeployer != null) {
- doStartRedeployTimer();
- }
- }
-
- private void doStartRedeployTimer() {
- redeployTimerID = vertx.setTimer(options.getRedeployScanInterval(), tid -> vertx.executeBlockingInternal(redeployer, res -> {
- if (res.succeeded()) {
- if (res.result()) {
- doRedeploy();
- } else if (!undeployed || broken) {
- doStartRedeployTimer();
- }
- } else {
- log.error("Failure in redeployer", res.cause());
- }
- }));
- }
-
- private void doRedeploy() {
- log.trace("Redeploying!");
- log.trace("Undeploying " + this.deploymentID);
- if (!broken) {
- undeploy(res -> {
- if (res.succeeded()) {
- log.trace("Undeployed ok");
- tryRedeploy();
- } else {
- log.error("Can't find verticle to undeploy", res.cause());
- }
- });
- } else {
- tryRedeploy();
- }
- }
-
- private void tryRedeploy() {
- ContextImpl callingContext = vertx.getContext();
- doRedeployVerticle(verticleIdentifier, deploymentID, options, parentContext, callingContext, redeployer, res2 -> {
- if (res2.succeeded()) {
- broken = false;
- undeployed = false;
- log.trace("Redeployed ok");
- } else {
- log.trace("Failed to deploy!!", res2.cause());
- broken = true;
- doStartRedeployTimer();
- }
- });
- }
}
}
diff --git a/src/main/java/io/vertx/core/impl/IsolatingClassLoader.java b/src/main/java/io/vertx/core/impl/IsolatingClassLoader.java
index 666edc88ac8..fb57e68e3b5 100644
--- a/src/main/java/io/vertx/core/impl/IsolatingClassLoader.java
+++ b/src/main/java/io/vertx/core/impl/IsolatingClassLoader.java
@@ -24,17 +24,16 @@
import java.util.List;
/**
- * Before delegating to the parent, this classloader attempts to load the class first
- * (opposite of normal delegation model).
- * This allows multiple versions of the same class to be loaded by different classloaders which allows
- * us to isolate verticles so they can't easily interact
*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class IsolatingClassLoader extends URLClassLoader {
- public IsolatingClassLoader(URL[] urls, ClassLoader parent) {
+ private List<String> isolatedClasses;
+
+ public IsolatingClassLoader(URL[] urls, ClassLoader parent, List<String> isolatedClasses) {
super(urls, parent);
+ this.isolatedClasses = isolatedClasses;
}
@Override
@@ -42,31 +41,55 @@ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundE
synchronized (getClassLoadingLock(name)) {
Class<?> c = findLoadedClass(name);
if (c == null) {
- // We don't want to load Vert.x (or Vert.x dependency) classes from an isolating loader
- if (isVertxOrSystemClass(name)) {
- try {
- c = super.loadClass(name, false);
- } catch (ClassNotFoundException e) {
- // Fall through
+ if (isIsolatedClass(name)) {
+ // We don't want to load Vert.x (or Vert.x dependency) classes from an isolating loader
+ if (isVertxOrSystemClass(name)) {
+ try {
+ c = getParent().loadClass(name);
+ } catch (ClassNotFoundException e) {
+ // Fall through
+ }
}
- }
- if (c == null) {
- // Try and load with this classloader
- try {
- c = findClass(name);
- } catch (ClassNotFoundException e) {
- // Now try with parent
- c = super.loadClass(name, false);
+ if (c == null) {
+ // Try and load with this classloader
+ try {
+ c = findClass(name);
+ } catch (ClassNotFoundException e) {
+ // Now try with parent
+ c = getParent().loadClass(name);
+ }
+ }
+ if (resolve) {
+ resolveClass(c);
}
+ } else {
+ // Parent first
+ c = super.loadClass(name, resolve);
}
}
- if (resolve) {
- resolveClass(c);
- }
return c;
}
}
+ private boolean isIsolatedClass(String name) {
+ if (isolatedClasses != null) {
+ for (String isolated : isolatedClasses) {
+ if (isolated.endsWith(".*")) {
+ String isolatedPackage = isolated.substring(0, isolated.length() - 1);
+ String paramPackage = name.substring(0, name.lastIndexOf('.') + 1);
+ if (paramPackage.startsWith(isolatedPackage)) {
+ // Matching package
+ return true;
+ }
+ } else if (isolated.equals(name)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+
/**
* {@inheritDoc}
*/
@@ -108,9 +131,9 @@ private boolean isVertxOrSystemClass(String name) {
return
name.startsWith("java.") ||
name.startsWith("javax.") ||
+ name.startsWith("sun.*") ||
name.startsWith("com.sun.") ||
name.startsWith("io.vertx.core") ||
- name.startsWith("com.hazelcast") ||
name.startsWith("io.netty.") ||
name.startsWith("com.fasterxml.jackson");
}
diff --git a/src/main/java/io/vertx/core/impl/Redeployer.java b/src/main/java/io/vertx/core/impl/Redeployer.java
deleted file mode 100644
index 61ad1d30cec..00000000000
--- a/src/main/java/io/vertx/core/impl/Redeployer.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright 2014 Red Hat, Inc.
- *
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * and Apache License v2.0 which accompanies this distribution.
- *
- * The Eclipse Public License is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * The Apache License v2.0 is available at
- * http://www.opensource.org/licenses/apache2.0.php
- *
- * You may elect to redistribute this code under either of these licenses.
- */
-
-package io.vertx.core.impl;
-
-import io.vertx.core.logging.Logger;
-import io.vertx.core.logging.LoggerFactory;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author <a href="http://tfox.org">Tim Fox</a>
- */
-public class Redeployer implements Action<Boolean> {
-
- private static final Logger log = LoggerFactory.getLogger(Redeployer.class);
-
- private final long gracePeriod;
- private final Map<File, Map<File, FileInfo>> fileMap = new HashMap<>();
- private final Set<File> filesToWatch = new HashSet<>();
- private long lastChange = -1;
-
- public Redeployer(Set<File> files, long gracePeriod) {
- this.gracePeriod = gracePeriod;
- for (File file : files) {
- addFileToWatch(file);
- }
- }
-
- private void addFileToWatch(File file) {
- // log.trace("Adding file to watch: " + file);
- filesToWatch.add(file);
- Map<File, FileInfo> map = new HashMap<>();
- if (file.isDirectory()) {
- // We're watching a directory contents and its children for changes
- File[] children = file.listFiles();
- if (children != null) {
- for (File child : children) {
- map.put(child, new FileInfo(child.lastModified(), child.length()));
- if (child.isDirectory()) {
- addFileToWatch(child);
- }
- }
- }
- } else {
- // Not a directory - we're watching a specific file - e.g. a jar
- map.put(file, new FileInfo(file.lastModified(), file.length()));
- }
- fileMap.put(file, map);
- }
-
- private boolean changesHaveOccurred() {
-
- boolean changed = false;
- for (File toWatch : new HashSet<>(filesToWatch)) {
- // The new files in the directory
- Map<File, File> newFiles = new HashMap<>();
- if (toWatch.isDirectory()) {
- File[] files = toWatch.exists() ? toWatch.listFiles() : new File[]{};
- for (File file : files) {
- newFiles.put(file, file);
- }
- } else {
- newFiles.put(toWatch, toWatch);
- }
- // Lookup the old list for that file/directory
- Map<File, FileInfo> currentFileMap = fileMap.get(toWatch);
- for (Map.Entry<File, FileInfo> currentEntry: new HashMap<>(currentFileMap).entrySet()) {
- File currFile = currentEntry.getKey();
- FileInfo currInfo = currentEntry.getValue();
- File newFile = newFiles.get(currFile);
- if (newFile == null) {
- // File has been deleted
- currentFileMap.remove(currFile);
- if (currentFileMap.isEmpty()) {
- fileMap.remove(toWatch);
- filesToWatch.remove(toWatch);
- }
- log.trace("File: " + currFile + " has been deleted");
- changed = true;
- } else if (newFile.lastModified() != currInfo.lastModified || newFile.length() != currInfo.length) {
- // File has been modified
- currentFileMap.put(newFile, new FileInfo(newFile.lastModified(), newFile.length()));
- log.trace("File: " + currFile + " has been modified");
- changed = true;
- }
- }
- // Now process any added files
- for (File newFile: newFiles.keySet()) {
- if (!currentFileMap.containsKey(newFile)) {
- // Add new file
- currentFileMap.put(newFile, new FileInfo(newFile.lastModified(), newFile.length()));
- if (newFile.isDirectory()) {
- addFileToWatch(newFile);
- }
- log.trace("File was added: " + newFile);
- changed = true;
- }
- }
- }
-
- long now = System.currentTimeMillis();
- if (changed) {
- lastChange = now;
- }
-
- if (lastChange != -1 && now - lastChange >= gracePeriod) {
- lastChange = -1;
- return true;
- }
-
- return false;
- }
-
- @Override
- public Boolean perform() {
- return changesHaveOccurred();
- }
-
- private static final class FileInfo {
- long lastModified;
- long length;
-
- private FileInfo(long lastModified, long length) {
- this.lastModified = lastModified;
- this.length = length;
- }
- }
-}
diff --git a/src/main/java/io/vertx/core/impl/verticle/CompilingClassLoader.java b/src/main/java/io/vertx/core/impl/verticle/CompilingClassLoader.java
index c593339fb7e..cfa08d93bc7 100644
--- a/src/main/java/io/vertx/core/impl/verticle/CompilingClassLoader.java
+++ b/src/main/java/io/vertx/core/impl/verticle/CompilingClassLoader.java
@@ -127,10 +127,14 @@ public String resolveMainClassName() {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
- byte[] bytecode = fileManager.getCompiledClass(name);
+ byte[] bytecode = getClassBytes(name);
if (bytecode == null) {
throw new ClassNotFoundException(name);
}
return defineClass(name, bytecode, 0, bytecode.length);
}
+
+ public byte[] getClassBytes(String name) {
+ return fileManager.getCompiledClass(name);
+ }
}
diff --git a/src/main/java/io/vertx/core/package-info.java b/src/main/java/io/vertx/core/package-info.java
index 1f7bbcd7c74..de968e79dfa 100644
--- a/src/main/java/io/vertx/core/package-info.java
+++ b/src/main/java/io/vertx/core/package-info.java
@@ -465,8 +465,8 @@
*
* === Verticle Isolation Groups
*
- * By default, Vert.x has a _flat classpath_. I.e, it does everything, including deploying verticles without messing
- * with class-loaders. In the majority of cases this is the simplest, clearest and sanest thing to do.
+ * By default, Vert.x has a _flat classpath_. I.e, when Vert.x deploys verticles it does so with the current classloader -
+ * it doesn't create a new one. In the majority of cases this is the simplest, clearest and sanest thing to do.
*
* However, in some cases you may want to deploy a verticle so the classes of that verticle are isolated from others in
* your application.
@@ -474,6 +474,18 @@
* This might be the case, for example, if you want to deploy two different versions of a verticle with the same class name
* in the same Vert.x instance, or if you have two different verticles which use different versions of the same jar library.
*
+ * When using an isolation group you provide a list of the class names that you want isolated using
+ * {@link io.vertx.core.DeploymentOptions#setIsolatedClasses(java.util.List)}- an entry can be a fully qualified
+ * classname such as `com.mycompany.myproject.engine.MyClass` or it can be a wildcard which will match any classes in a package and any
+ * sub-packages, e.g. `com.mycompany.myproject.*` would match any classes in the package `com.mycompany.myproject` or
+ * any sub-packages.
+ *
+ * Please note that _only_ the classes that match will be isolated - any other classes will be loaded by the current
+ * class loader.
+ *
+ * Extra classpath entries can also be provided with {@link io.vertx.core.DeploymentOptions#setExtraClasspath} so if
+ * you want to load classes or resources that aren't already present on the main claspath you can add this.
+ *
* WARNING: Use this feature with caution. Class-loaders can be a can of worms, and can make debugging difficult, amongst
* other things.
*
@@ -484,12 +496,6 @@
* {@link examples.CoreExamples#example14}
* ----
*
- * Isolation groups are identified by a name, and the name can be used between different deployments if you want them
- * to share an isolated class-loader.
- *
- * Extra classpath entries can also be provided with {@link io.vertx.core.DeploymentOptions#setExtraClasspath} so they
- * can locate resources that are isolated to them.
- *
* === High Availability
*
* Verticles can be deployed with High Availability (HA) enabled. In that context, when a verticle is deployed on
@@ -803,7 +809,6 @@
* * `-hagroup` - used in conjunction with `-ha`. It specifies the HA group this node will join. There can be
* multiple HA groups in a cluster. Nodes will only failover to other nodes in the same group. The default value is `
* +++__DEFAULT__+++`
- * * `-redeploy` - Enables automatic redeployment of the verticle
*
* Here are some more examples:
*
@@ -899,20 +904,6 @@
* vertx -version
* ----
*
- * === Using the redeploy argument
- *
- * When a verticle is launched with `vertx run .... -redeploy`, vertx redeploys the verticle every time the verticle
- * files change. This mode makes the development much more fun and efficient as you don't have to restart the
- * application.
- *
- * [source]
- * ----
- * vertx run server.js -redeploy
- * vertx run Server.java -redeploy
- * ----
- *
- * When using Java source file, vert.x recompiles the class on the fly and redeploys the verticle.
- *
* == Cluster Managers
*
* In Vert.x a cluster manager is used for various functions including:
diff --git a/src/test/java/io/vertx/test/core/DeploymentTest.java b/src/test/java/io/vertx/test/core/DeploymentTest.java
index 8ffc92a2e00..4283328ec67 100644
--- a/src/test/java/io/vertx/test/core/DeploymentTest.java
+++ b/src/test/java/io/vertx/test/core/DeploymentTest.java
@@ -16,31 +16,20 @@
package io.vertx.test.core;
-import io.vertx.core.AbstractVerticle;
-import io.vertx.core.AsyncResult;
-import io.vertx.core.Context;
-import io.vertx.core.DeploymentOptions;
-import io.vertx.core.Future;
-import io.vertx.core.Verticle;
-import io.vertx.core.Vertx;
+import io.vertx.core.*;
import io.vertx.core.eventbus.Message;
-import io.vertx.core.impl.Closeable;
-import io.vertx.core.impl.ContextImpl;
-import io.vertx.core.impl.Deployment;
-import io.vertx.core.impl.VertxInternal;
-import io.vertx.core.impl.WorkerContext;
+import io.vertx.core.impl.*;
+import io.vertx.core.impl.verticle.CompilingClassLoader;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.test.core.sourceverticle.SourceVerticle;
import org.junit.Test;
+import java.io.File;
+import java.net.URL;
import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
+import java.nio.file.Files;
+import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -83,41 +72,10 @@ public void testOptions() {
assertNull(options.getExtraClasspath());
List<String> cp = Arrays.asList("foo", "bar");
assertEquals(options, options.setExtraClasspath(cp));
- assertSame(cp, options.getExtraClasspath());
- assertFalse(options.isRedeploy());
- assertSame(options, options.setRedeploy(true));
- assertTrue(options.isRedeploy());
- assertEquals(DeploymentOptions.DEFAULT_REDEPLOY_GRACE_INTERVAL, options.getRedeployGraceInterval());
- int randInt = TestUtils.randomPositiveInt();
- assertEquals(options, options.setRedeployGraceInterval(randInt));
- assertEquals(randInt, options.getRedeployGraceInterval());
- randInt = TestUtils.randomPositiveInt();
- assertEquals(options, options.setRedeployScanInterval(randInt));
- assertEquals(randInt, options.getRedeployScanInterval());
- try {
- options.setRedeployGraceInterval(-1);
- fail();
- } catch (IllegalArgumentException e) {
- // OK
- }
- try {
- options.setRedeployScanInterval(-1);
- fail();
- } catch (IllegalArgumentException e) {
- // OK
- }
- try {
- options.setRedeployGraceInterval(0);
- fail();
- } catch (IllegalArgumentException e) {
- // OK
- }
- try {
- options.setRedeployScanInterval(0);
- fail();
- } catch (IllegalArgumentException e) {
- // OK
- }
+ assertNull(options.getIsolatedClasses());
+ List<String> isol = Arrays.asList("com.foo.MyClass", "org.foo.*");
+ assertEquals(options, options.setIsolatedClasses(isol));
+ assertSame(isol, options.getIsolatedClasses());
}
@Test
@@ -129,18 +87,15 @@ public void testCopyOptions() {
boolean multiThreaded = rand.nextBoolean();
String isolationGroup = TestUtils.randomAlphaString(100);
boolean ha = rand.nextBoolean();
- long gracePeriod = 7236;
- long scanPeriod = 7812673;
List<String> cp = Arrays.asList("foo", "bar");
+ List<String> isol = Arrays.asList("com.foo.MyClass", "org.foo.*");
options.setConfig(config);
options.setWorker(worker);
options.setMultiThreaded(multiThreaded);
options.setIsolationGroup(isolationGroup);
options.setHa(ha);
options.setExtraClasspath(cp);
- options.setRedeploy(true);
- options.setRedeployGraceInterval(gracePeriod);
- options.setRedeployScanInterval(scanPeriod);
+ options.setIsolatedClasses(isol);
DeploymentOptions copy = new DeploymentOptions(options);
assertEquals(worker, copy.isWorker());
assertEquals(multiThreaded, copy.isMultiThreaded());
@@ -150,9 +105,8 @@ public void testCopyOptions() {
assertEquals(ha, copy.isHa());
assertEquals(cp, copy.getExtraClasspath());
assertNotSame(cp, copy.getExtraClasspath());
- assertTrue(options.isRedeploy());
- assertEquals(gracePeriod, options.getRedeployGraceInterval());
- assertEquals(scanPeriod, options.getRedeployScanInterval());
+ assertEquals(isol, copy.getIsolatedClasses());
+ assertNotSame(isol, copy.getIsolatedClasses());
}
@Test
@@ -165,7 +119,7 @@ public void testDefaultJsonOptions() {
assertEquals(def.getIsolationGroup(), json.getIsolationGroup());
assertEquals(def.isHa(), json.isHa());
assertEquals(def.getExtraClasspath(), json.getExtraClasspath());
- assertEquals(def.isRedeploy(), json.isRedeploy());
+ assertEquals(def.getIsolatedClasses(), json.getIsolatedClasses());
}
@Test
@@ -177,6 +131,7 @@ public void testJsonOptions() {
String isolationGroup = TestUtils.randomAlphaString(100);
boolean ha = rand.nextBoolean();
List<String> cp = Arrays.asList("foo", "bar");
+ List<String> isol = Arrays.asList("com.foo.MyClass", "org.foo.*");
JsonObject json = new JsonObject();
json.put("config", config);
json.put("worker", worker);
@@ -184,9 +139,7 @@ public void testJsonOptions() {
json.put("isolationGroup", isolationGroup);
json.put("ha", ha);
json.put("extraClasspath", new JsonArray(cp));
- json.put("redeploy", true);
- json.put("redeployGraceInterval", 1234);
- json.put("redeployScanInterval", 4567);
+ json.put("isolatedClasses", new JsonArray(isol));
DeploymentOptions options = new DeploymentOptions(json);
assertEquals(worker, options.isWorker());
assertEquals(multiThreaded, options.isMultiThreaded());
@@ -194,9 +147,7 @@ public void testJsonOptions() {
assertEquals("bar", options.getConfig().getString("foo"));
assertEquals(ha, options.isHa());
assertEquals(cp, options.getExtraClasspath());
- assertTrue(options.isRedeploy());
- assertEquals(1234, options.getRedeployGraceInterval());
- assertEquals(4567, options.getRedeployScanInterval());
+ assertEquals(isol, options.getIsolatedClasses());
}
@Test
@@ -208,18 +159,15 @@ public void testToJson() {
boolean multiThreaded = rand.nextBoolean();
String isolationGroup = TestUtils.randomAlphaString(100);
boolean ha = rand.nextBoolean();
- long gracePeriod = 521445;
- long scanPeriod = 234234;
List<String> cp = Arrays.asList("foo", "bar");
+ List<String> isol = Arrays.asList("com.foo.MyClass", "org.foo.*");
options.setConfig(config);
options.setWorker(worker);
options.setMultiThreaded(multiThreaded);
options.setIsolationGroup(isolationGroup);
options.setHa(ha);
options.setExtraClasspath(cp);
- options.setRedeploy(true);
- options.setRedeployGraceInterval(gracePeriod);
- options.setRedeployScanInterval(scanPeriod);
+ options.setIsolatedClasses(isol);
JsonObject json = options.toJson();
DeploymentOptions copy = new DeploymentOptions(json);
assertEquals(worker, copy.isWorker());
@@ -228,8 +176,7 @@ public void testToJson() {
assertEquals("bar", copy.getConfig().getString("foo"));
assertEquals(ha, copy.isHa());
assertEquals(cp, copy.getExtraClasspath());
- assertEquals(gracePeriod, copy.getRedeployGraceInterval());
- assertEquals(scanPeriod, copy.getRedeployScanInterval());
+ assertEquals(isol, copy.getIsolatedClasses());
}
@Test
@@ -645,6 +592,11 @@ public void testDeployInstanceSetIsolationGroup() throws Exception {
vertx.deployVerticle(new MyVerticle(), new DeploymentOptions().setIsolationGroup("foo"));
}
+ @Test(expected = IllegalArgumentException.class)
+ public void testDeployInstanceSetIsolatedClasses() throws Exception {
+ vertx.deployVerticle(new MyVerticle(), new DeploymentOptions().setIsolatedClasses(Arrays.asList("foo")));
+ }
+
@Test
public void testDeployUsingClassName() throws Exception {
vertx.deployVerticle("java:" + TestVerticle.class.getCanonicalName(), ar -> {
@@ -964,7 +916,9 @@ public void testCloseHooksCalled() throws Exception {
@Test
public void testIsolationGroup1() throws Exception {
- vertx.deployVerticle("java:" + TestVerticle.class.getCanonicalName(), new DeploymentOptions().setIsolationGroup("somegroup"), ar -> {
+ List<String> isolatedClasses = Arrays.asList(TestVerticle.class.getCanonicalName());
+ vertx.deployVerticle("java:" + TestVerticle.class.getCanonicalName(),
+ new DeploymentOptions().setIsolationGroup("somegroup").setIsolatedClasses(isolatedClasses), ar -> {
assertTrue(ar.succeeded());
assertEquals(0, TestVerticle.instanceCount.get());
testComplete();
@@ -984,33 +938,57 @@ public void testNullIsolationGroup() throws Exception {
@Test
public void testIsolationGroupSameGroup() throws Exception {
- testIsolationGroup("somegroup", "somegroup", 1, 2);
+ List<String> isolatedClasses = Arrays.asList(TestVerticle.class.getCanonicalName());
+ testIsolationGroup("somegroup", "somegroup", 1, 2, isolatedClasses, "java:" + TestVerticle.class.getCanonicalName());
+ }
+
+ @Test
+ public void testIsolationGroupSameGroupWildcard() throws Exception {
+ List<String> isolatedClasses = Arrays.asList("io.vertx.test.core.*");
+ testIsolationGroup("somegroup", "somegroup", 1, 2, isolatedClasses, "java:" + TestVerticle.class.getCanonicalName());
}
@Test
public void testIsolationGroupDifferentGroup() throws Exception {
- testIsolationGroup("somegroup", "someothergroup", 1, 1);
+ List<String> isolatedClasses = Arrays.asList(TestVerticle.class.getCanonicalName());
+ testIsolationGroup("somegroup", "someothergroup", 1, 1, isolatedClasses, "java:" + TestVerticle.class.getCanonicalName());
}
@Test
- public void testExtraClasspath() throws Exception {
- String cp1 = "foo/bar/wibble";
- String cp2 = "blah/socks/mice";
- List<String> extraClasspath = Arrays.asList(cp1, cp2);
- vertx.deployVerticle("java:" + TestVerticle.class.getCanonicalName(), new DeploymentOptions().setIsolationGroup("somegroup").
+ public void testExtraClasspathLoader() throws Exception {
+
+ String dir = createClassOutsideClasspath("MyVerticle");
+
+ List<String> extraClasspath = Arrays.asList(dir);
+
+ vertx.deployVerticle("java:" + ExtraCPVerticle.class.getCanonicalName(), new DeploymentOptions().setIsolationGroup("somegroup").
setExtraClasspath(extraClasspath), ar -> {
assertTrue(ar.succeeded());
- Deployment deployment = ((VertxInternal) vertx).getDeployment(ar.result());
- Verticle verticle = deployment.getVerticles().iterator().next();
- ClassLoader cl = verticle.getClass().getClassLoader();
- URLClassLoader urlc = (URLClassLoader) cl;
- assertTrue(urlc.getURLs()[0].toString().endsWith(cp1));
- assertTrue(urlc.getURLs()[1].toString().endsWith(cp2));
testComplete();
});
await();
}
+ private String createClassOutsideClasspath(String className) throws Exception {
+ File dir = Files.createTempDirectory("vertx").toFile();
+ dir.deleteOnExit();
+ File source = new File(dir, className + ".java");
+ Files.write(source.toPath(), ("public class " + className + " extends io.vertx.core.AbstractVerticle {} ").getBytes());
+
+ URLClassLoader loader = new URLClassLoader(new URL[]{dir.toURI().toURL()}, Thread.currentThread().getContextClassLoader());
+
+ CompilingClassLoader compilingClassLoader = new CompilingClassLoader(loader, className + ".java");
+ compilingClassLoader.loadClass(className);
+
+ byte[] bytes = compilingClassLoader.getClassBytes(className);
+ assertNotNull(bytes);
+
+ File classFile = new File(dir, className + ".class");
+ Files.write(classFile.toPath(), bytes);
+
+ return dir.getAbsolutePath();
+ }
+
public static class ParentVerticle extends AbstractVerticle {
@Override
@@ -1130,8 +1108,8 @@ public void testGetInstanceCountMultipleVerticles() throws Exception {
// Multi-threaded workers
-
- private void testIsolationGroup(String group1, String group2, int count1, int count2) throws Exception {
+ private void testIsolationGroup(String group1, String group2, int count1, int count2, List<String> isolatedClasses,
+ String verticleID) throws Exception {
Map<String, Integer> countMap = new ConcurrentHashMap<>();
vertx.eventBus().<JsonObject>consumer("testcounts").handler((Message<JsonObject> msg) -> {
countMap.put(msg.body().getString("deploymentID"), msg.body().getInteger("count"));
@@ -1139,11 +1117,13 @@ private void testIsolationGroup(String group1, String group2, int count1, int co
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<String> deploymentID1 = new AtomicReference<>();
AtomicReference<String> deploymentID2 = new AtomicReference<>();
- vertx.deployVerticle("java:" + TestVerticle.class.getCanonicalName(), new DeploymentOptions().setIsolationGroup(group1), ar -> {
+ vertx.deployVerticle(verticleID, new DeploymentOptions().
+ setIsolationGroup(group1).setIsolatedClasses(isolatedClasses), ar -> {
assertTrue(ar.succeeded());
deploymentID1.set(ar.result());
assertEquals(0, TestVerticle.instanceCount.get());
- vertx.deployVerticle("java:" + TestVerticle.class.getCanonicalName(), new DeploymentOptions().setIsolationGroup(group2), ar2 -> {
+ vertx.deployVerticle(verticleID,
+ new DeploymentOptions().setIsolationGroup(group2).setIsolatedClasses(isolatedClasses), ar2 -> {
assertTrue(ar2.succeeded());
deploymentID2.set(ar2.result());
assertEquals(0, TestVerticle.instanceCount.get());
diff --git a/src/test/java/io/vertx/test/core/ExtraCPVerticle.java b/src/test/java/io/vertx/test/core/ExtraCPVerticle.java
new file mode 100644
index 00000000000..16eddba4d14
--- /dev/null
+++ b/src/test/java/io/vertx/test/core/ExtraCPVerticle.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2011-2013 The original author or authors
+ * ------------------------------------------------------
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * and Apache License v2.0 which accompanies this distribution.
+ *
+ * The Eclipse Public License is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * The Apache License v2.0 is available at
+ * http://www.opensource.org/licenses/apache2.0.php
+ *
+ * You may elect to redistribute this code under either of these licenses.
+ */
+
+package io.vertx.test.core;
+
+import io.vertx.core.AbstractVerticle;
+import io.vertx.core.impl.IsolatingClassLoader;
+import org.junit.Assert;
+
+/**
+* @author <a href="mailto:[email protected]">Julien Viet</a>
+*/
+public class ExtraCPVerticle extends AbstractVerticle {
+ @Override
+ public void start() throws Exception {
+ IsolatingClassLoader cl = (IsolatingClassLoader) Thread.currentThread().getContextClassLoader();
+ Class extraCPClass = cl.loadClass("MyVerticle");
+ Assert.assertSame(extraCPClass.getClassLoader(), cl);
+ try {
+ cl.getParent().loadClass("MyVerticle");
+ Assert.fail("Parent classloader should not see this class");
+ } catch (ClassNotFoundException expected) {
+ //
+ }
+ }
+}
diff --git a/src/test/java/io/vertx/test/core/IsolatingClassLoaderTest.java b/src/test/java/io/vertx/test/core/IsolatingClassLoaderTest.java
index ed868e28dfc..756e79ef077 100644
--- a/src/test/java/io/vertx/test/core/IsolatingClassLoaderTest.java
+++ b/src/test/java/io/vertx/test/core/IsolatingClassLoaderTest.java
@@ -21,7 +21,6 @@
*/
public class IsolatingClassLoaderTest {
- private String basePath = "src/test/resources/icl";
private String resourceName = "resource.json";
private URL url1;
private URL url2;
@@ -32,12 +31,14 @@ public class IsolatingClassLoaderTest {
@Before
public void setUp() throws Exception {
+ String basePath = "src/test/resources/icl";
+
url1 = new File(basePath, "pkg1").toURI().toURL();
url2 = new File(basePath, "pkg2").toURI().toURL();
url3 = new File(basePath, "pkg3").toURI().toURL();
ucl = new URLClassLoader(new URL[]{url2, url3});
- icl = new IsolatingClassLoader(new URL[]{url1}, ucl);
+ icl = new IsolatingClassLoader(new URL[]{url1}, ucl, null);
}
diff --git a/src/test/java/io/vertx/test/core/RedeployFailVerticle.java b/src/test/java/io/vertx/test/core/RedeployFailVerticle.java
deleted file mode 100644
index f0c2c6011a5..00000000000
--- a/src/test/java/io/vertx/test/core/RedeployFailVerticle.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2011-2014 The original author or authors
- * ------------------------------------------------------
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * and Apache License v2.0 which accompanies this distribution.
- *
- * The Eclipse Public License is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * The Apache License v2.0 is available at
- * http://www.opensource.org/licenses/apache2.0.php
- *
- * You may elect to redistribute this code under either of these licenses.
- */
-
-package io.vertx.test.core;
-
-import io.vertx.core.AbstractVerticle;
-import io.vertx.core.Future;
-import io.vertx.core.VertxException;
-
-/**
- * @author <a href="http://tfox.org">Tim Fox</a>
- */
-public class RedeployFailVerticle extends AbstractVerticle {
-
- @Override
- public void start(Future<Void> startFuture) throws Exception {
- vertx.eventBus().<Boolean>send("vertstartok", "foo", res -> {
- if (res.result().body()) {
- startFuture.complete();
- vertx.eventBus().publish("vertstarted", context.deploymentID());
- } else {
- startFuture.fail(new VertxException("foo"));
- }
- });
- }
-
- @Override
- public void stop() throws Exception {
- vertx.eventBus().publish("vertstopped", context.deploymentID());
- }
-
-
-
-}
diff --git a/src/test/java/io/vertx/test/core/RedeployVerticle.java b/src/test/java/io/vertx/test/core/RedeployVerticle.java
deleted file mode 100644
index eda24e81056..00000000000
--- a/src/test/java/io/vertx/test/core/RedeployVerticle.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 2011-2014 The original author or authors
- * ------------------------------------------------------
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * and Apache License v2.0 which accompanies this distribution.
- *
- * The Eclipse Public License is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * The Apache License v2.0 is available at
- * http://www.opensource.org/licenses/apache2.0.php
- *
- * You may elect to redistribute this code under either of these licenses.
- */
-
-package io.vertx.test.core;
-
-import io.vertx.core.AbstractVerticle;
-
-/**
- * @author <a href="http://tfox.org">Tim Fox</a>
- */
-public class RedeployVerticle extends AbstractVerticle {
- @Override
- public void start() throws Exception {
- vertx.eventBus().publish("vertstarted", context.deploymentID());
- }
-
- @Override
- public void stop() throws Exception {
- vertx.eventBus().publish("vertstopped", context.deploymentID());
- }
-}
diff --git a/src/test/java/io/vertx/test/core/RedeployVerticle2.java b/src/test/java/io/vertx/test/core/RedeployVerticle2.java
deleted file mode 100644
index 4d28e651e56..00000000000
--- a/src/test/java/io/vertx/test/core/RedeployVerticle2.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2011-2014 The original author or authors
- * ------------------------------------------------------
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * and Apache License v2.0 which accompanies this distribution.
- *
- * The Eclipse Public License is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * The Apache License v2.0 is available at
- * http://www.opensource.org/licenses/apache2.0.php
- *
- * You may elect to redistribute this code under either of these licenses.
- */
-
-package io.vertx.test.core;
-
-import io.vertx.core.AbstractVerticle;
-import io.vertx.core.DeploymentOptions;
-import io.vertx.core.Future;
-
-/**
- * @author <a href="http://tfox.org">Tim Fox</a>
- */
-public class RedeployVerticle2 extends AbstractVerticle {
-
- @Override
- public void start(Future<Void> startFuture) throws Exception {
-
- // The redeploy setting should be ignored on this as its not a top level verticle
- vertx.deployVerticle(RedeployVerticle.class.getName(), new DeploymentOptions().setRedeploy(true), res -> {
- if (res.succeeded()) {
- startFuture.complete();
- } else {
- startFuture.fail(res.cause());
- }
- });
- }
-}
diff --git a/src/test/java/io/vertx/test/core/RedeploymentTest.java b/src/test/java/io/vertx/test/core/RedeploymentTest.java
deleted file mode 100644
index 4bc1860fe24..00000000000
--- a/src/test/java/io/vertx/test/core/RedeploymentTest.java
+++ /dev/null
@@ -1,406 +0,0 @@
-/*
- * Copyright (c) 2011-2014 The original author or authors
- * ------------------------------------------------------
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * and Apache License v2.0 which accompanies this distribution.
- *
- * The Eclipse Public License is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * The Apache License v2.0 is available at
- * http://www.opensource.org/licenses/apache2.0.php
- *
- * You may elect to redistribute this code under either of these licenses.
- */
-
-package io.vertx.test.core;
-
-import io.vertx.core.DeploymentOptions;
-import io.vertx.core.VertxException;
-import io.vertx.core.buffer.Buffer;
-import io.vertx.core.impl.Utils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * @author <a href="http://tfox.org">Tim Fox</a>
- */
-public class RedeploymentTest extends VertxTestBase {
-
- @Rule
- public TemporaryFolder testFolder = new TemporaryFolder();
-
- protected File tempDir;
- protected File cpDir;
- protected File jarFile;
- protected DeploymentOptions options;
- protected File projectBaseDir;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- tempDir = testFolder.newFolder();
- cpDir = new File(tempDir, "cpDir");
- assertTrue(cpDir.mkdir());
- // Copy one jar into that directory
- URLClassLoader urlc = (URLClassLoader)getClass().getClassLoader();
- int count = 0;
- for (URL url: urlc.getURLs()) {
- String surl = url.toString();
- if (surl.endsWith(".jar") && surl.startsWith("file:")) {
- File file = new File(url.toURI());
- File dest = new File(tempDir.getAbsoluteFile(), file.getName());
- jarFile = dest;
- Files.copy(file.toPath(), dest.toPath());
- assertTrue(dest.exists());
- if (++count == 2) {
- break;
- }
- }
- }
- assertNotNull(jarFile);
- options = new DeploymentOptions().setRedeploy(true);
- List<String> extraCP = new ArrayList<>();
- extraCP.add(jarFile.getAbsolutePath());
- extraCP.add(cpDir.getAbsolutePath());
- options.setExtraClasspath(extraCP);
- String baseDir = System.getProperty("project.basedir");
- if (baseDir == null) {
-
- }
- }
-
- @Override
- public void tearDown() throws Exception {
- /* One of the temp files is a jar which is added to the classpath to test verticle redeploy on jar
- * changes. This jar remains locked by the JVM until all references to this class loader have been
- * removed and garbage collected. The following clean up statement fails because either there is
- * still some floating reference to the class loader or the JVM hasn't yet garbage collected it.
- */
- if(!Utils.isWindows())
- vertx.fileSystem().deleteRecursiveBlocking(tempDir.getPath(), true);
- }
-
- @Test
- public void testRedeployOnJarChanged() throws Exception {
- testRedeploy(() -> touchJar());
- }
-
- @Test
- public void testRedeployOnCreateFile() throws Exception {
- testRedeploy(() -> createFile(cpDir, "newfile.txt"));
- }
-
- @Test
- public void testRedeployOnTouchFile() throws Exception {
- createFile(cpDir, "newfile.txt");
- testRedeploy(() -> touchFile(cpDir, "newfile.txt"));
- }
-
- @Test
- public void testRedeployOnChangeFile() throws Exception {
- createFile(cpDir, "newfile.txt");
- testRedeploy(() -> modifyFile(cpDir, "newfile.txt"));
- }
-
- @Test
- public void testRedeployOnDeleteFile() throws Exception {
- createFile(cpDir, "newfile.txt");
- testRedeploy(() -> deleteFile(cpDir, "newfile.txt"));
- }
-
- @Test
- public void testRedeployOnCreateSubDir() throws Exception {
- testRedeploy(() -> createDirectory(cpDir, "subdir"));
- }
-
- @Test
- public void testRedeployOnCreateFileInSubDir() throws Exception {
- testRedeploy(() -> createDirectory(cpDir, "subdir"));
- testRedeploy(() -> createFile(new File(cpDir, "subdir"), "subfile.txt"));
- }
-
- @Test
- public void testRedeployOnTouchFileInSubDir() throws Exception {
- testRedeploy(() -> createDirectory(cpDir, "subdir"));
- testRedeploy(() -> createFile(new File(cpDir, "subdir"), "subfile.txt"));
- testRedeploy(() -> touchFile(new File(cpDir, "subdir"), "subfile.txt"));
- }
-
- @Test
- public void testRedeployOnChangeFileInSubDir() throws Exception {
- testRedeploy(() -> createDirectory(cpDir, "subdir"));
- testRedeploy(() -> createFile(new File(cpDir, "subdir"), "subfile.txt"));
- testRedeploy(() -> modifyFile(new File(cpDir, "subdir"), "subfile.txt"));
- }
-
- @Test
- public void testRedeployOnDeleteFileInSubDir() throws Exception {
- testRedeploy(() -> createDirectory(cpDir, "subdir"));
- testRedeploy(() -> createFile(new File(cpDir, "subdir"), "subfile.txt"));
- testRedeploy(() -> deleteFile(new File(cpDir, "subdir"), "subfile.txt"));
- }
-
- @Test
- public void testRedeployOnDeleteSubDir() throws Exception {
- testRedeploy(() -> createDirectory(cpDir, "subdir"));
- File subDir = new File(cpDir, "subdir");
- testRedeploy(() -> createFile(subDir, "subfile.txt"));
- testRedeploy(() -> deleteDirectory(subDir));
- }
-
- @Test
- public void testRedeployMultipleTimes() throws Exception {
- createFile(cpDir, "newfile.txt");
- testRedeploy(() -> touchFile(cpDir, "newfile.txt"), 5, 1500);
- }
-
- @Test
- public void testRedeploySourceVerticle() throws Exception {
- Files.copy(Paths.get(resolvePath("src/test/resources/redeployverticles/RedeploySourceVerticle.java")),
- new File(cpDir, "RedeploySourceVerticle.java").toPath());
- testRedeploy("java:RedeploySourceVerticle.java", () -> touchFile(cpDir, "RedeploySourceVerticle.java"), 1, 0, 1);
- }
-
- @Test
- public void testRedeployBrokenSourceVerticleThenFixIt() throws Exception {
- Files.copy(Paths.get(resolvePath("src/test/resources/redeployverticles/RedeploySourceVerticle.java")),
- new File(cpDir, "RedeploySourceVerticle.java").toPath());
- testRedeploy("java:RedeploySourceVerticle.java", () -> {
- // Replace with broken source flile
- try {
- Files.copy(Paths.get(resolvePath("src/test/resources/redeployverticles/BrokenRedeploySourceVerticle.java")),
- new File(cpDir, "RedeploySourceVerticle.java").toPath(), StandardCopyOption.REPLACE_EXISTING);
- } catch (Exception e) {
- throw new VertxException(e);
- }
- vertx.setTimer(2000, id -> {
- // Copy back the fixed file
- try {
- Files.copy(Paths.get(resolvePath("src/test/resources/redeployverticles/RedeploySourceVerticle.java")),
- new File(cpDir, "RedeploySourceVerticle.java").toPath(), StandardCopyOption.REPLACE_EXISTING);
- } catch (Exception e) {
- throw new VertxException(e);
- }
- });
- }, 1, 0, 1);
- }
-
- @Test
- public void testRedeployFailedAndFixIt() throws Exception {
-
- AtomicInteger startCount = new AtomicInteger();
- // Only fail the second time it's started
- vertx.eventBus().<String>consumer("vertstartok").handler(res -> res.reply(startCount.incrementAndGet() != 2));
-
- testRedeploy(RedeployFailVerticle.class.getName(), () -> {
- touchJar();
- // Now wait a bit and touch again
- vertx.setTimer(2000, id -> touchJar());
- }, 1, 0, 1);
- }
-
- @Test
- public void testRedeployFailedAndFixItWithManuallyUndeploy() throws Exception {
- AtomicInteger startCount = new AtomicInteger();
- // Only fail the second time it's started
- vertx.eventBus().<String>consumer("vertstartok").handler(res -> res.reply(startCount.incrementAndGet() != 2));
-
- String depID = testRedeploy(RedeployFailVerticle.class.getName(), () -> {
- touchJar();
- // Now wait a bit and touch again
- vertx.setTimer(2000, id -> touchJar());
- }, 1, 0, 1);
- vertx.undeploy(depID, onSuccess(v -> {
- testComplete();
- }));
- await();
- }
-
- @Test
- public void testManualUndeployAfterRedeply() throws Exception {
- String depID = testRedeploy(() -> touchJar());
- vertx.undeploy(depID, onSuccess(v -> {
- testComplete();
- }));
- await();
- }
-
- @Test
- public void testDelayedRedeployDueToSequenceOfChanges() throws Exception {
- testRedeploy(RedeployVerticle.class.getName(), () -> touchJar(), 10, DeploymentOptions.DEFAULT_REDEPLOY_GRACE_INTERVAL / 2, 1);
- }
-
- @Test
- public void testChangeAgainDuringRedeploy() throws Exception {
- testRedeploy(() -> {
- touchJar();
- vertx.setTimer(DeploymentOptions.DEFAULT_REDEPLOY_GRACE_INTERVAL + 1, id -> {
- touchJar();
- });
- });
- }
-
- @Test
- public void testOnlyTopMostVerticleRedeployed() throws Exception {
- AtomicInteger startCount = new AtomicInteger();
- vertx.eventBus().<String>consumer("vertstarted").handler(msg -> {
- startCount.incrementAndGet();
- });
-
- // Top most verticle is set NOT to redeploy
- options.setRedeploy(false);
- CountDownLatch latch = new CountDownLatch(1);
- vertx.deployVerticle(RedeployVerticle2.class.getName(), options, onSuccess(depID -> {
- touchJar();
- latch.countDown();
- }));
-
- awaitLatch(latch);
- // Now wait a bit, the verticle should not be redeployed
- vertx.setTimer(2000, id -> {
- assertEquals(1, startCount.get());
- testComplete();
- });
- await();
- }
-
- private void incCount(Map<String, Integer> counts, String depID) {
- Integer in = counts.get(depID);
- if (in == null) {
- in = 0;
- }
- counts.put(depID, 1 + in);
- }
-
- private void waitUntilCount(Map<String, Integer> counts, String depID, int count) {
- waitUntil(() -> {
- Integer in = counts.get(depID);
- if (in != null) {
- return count == in;
- } else {
- return false;
- }
- }, 60000000);
- }
-
- protected String testRedeploy(Runnable runner) throws Exception {
- return testRedeploy(RedeployVerticle.class.getName(), runner, 1, 0, 1);
- }
-
- protected String testRedeploy(Runnable runner, int times, long delay) throws Exception {
- return testRedeploy(RedeployVerticle.class.getName(), runner, times, delay, times);
- }
-
- protected String testRedeploy(String verticleID, Runnable runner, int times, long delay, int expectedRedeploys) throws Exception {
- Map<String, Integer> startedCounts = new HashMap<>();
- vertx.eventBus().<String>consumer("vertstarted").handler(msg -> {
- String depID = msg.body();
- incCount(startedCounts, depID);
- });
- Map<String, Integer> stoppedCounts = new HashMap<>();
- vertx.eventBus().<String>consumer("vertstopped").handler(msg -> {
- String depID = msg.body();
- incCount(stoppedCounts, depID);
- });
-
- AtomicReference<String> depRef = new AtomicReference<>();
- CountDownLatch deployLatch = new CountDownLatch(1);
-
- vertx.deployVerticle(verticleID, options, onSuccess(depID -> {
- depRef.set(depID);
- deployLatch.countDown();
- }));
-
- awaitLatch(deployLatch);
- runRunner(runner, times, delay);
-
- waitUntilCount(startedCounts, depRef.get(), 1 + expectedRedeploys);
- waitUntilCount(stoppedCounts, depRef.get(), expectedRedeploys);
-
- return depRef.get();
- }
-
- private void runRunner(Runnable runner, int times, long delay) {
- runner.run();
- if (times > 1) {
- vertx.setTimer(delay, id -> runRunner(runner, times - 1, delay));
- }
- }
-
-
- protected void touchJar() {
- touchFile(jarFile);
- }
-
- protected void touchFile(File dir, String fileName) {
- File f = new File(dir, fileName);
- touchFile(f);
- }
-
- protected void touchFile(File file) {
- long lastMod = file.lastModified();
- assertTrue(file.setLastModified(lastMod + 1001));
- }
-
- protected void createFile(File dir, String fileName) {
- File f = new File(dir, fileName);
- vertx.fileSystem().writeFileBlocking(f.getAbsolutePath(), Buffer.buffer(TestUtils.randomAlphaString(1000)));
- }
-
- protected void createFile(File dir, String fileName, String content) {
- File f = new File(dir, fileName);
- vertx.fileSystem().writeFileBlocking(f.getAbsolutePath(), Buffer.buffer(content));
- }
-
- protected void modifyFile(File dir, String fileName) {
- try {
- File f = new File(dir, fileName);
- FileWriter fw = new FileWriter(f, true);
- fw.write(TestUtils.randomAlphaString(500));
- fw.close();
- } catch (Exception e) {
- throw new VertxException(e);
- }
- }
-
- protected void deleteFile(File dir, String fileName) {
- File f = new File(dir, fileName);
- f.delete();
- }
-
- protected void createDirectory(File parent, String dirName) {
- File f = new File(parent, dirName);
- vertx.fileSystem().mkdirBlocking(f.getAbsolutePath());
- }
-
- protected void deleteDirectory(File directory) {
- vertx.fileSystem().deleteRecursiveBlocking(directory.getAbsolutePath(), true);
- }
-
- // Make sure resources are found when running in IDE and on command line
- protected String resolvePath(String path) {
- String buildDir = System.getProperty("buildDirectory");
- String prefix = buildDir != null ? buildDir + "/../" : "";
- return prefix + path;
- }
-
-}
-
diff --git a/src/test/java/io/vertx/test/core/StarterTest.java b/src/test/java/io/vertx/test/core/StarterTest.java
index 2d2233a2580..0a703eda595 100644
--- a/src/test/java/io/vertx/test/core/StarterTest.java
+++ b/src/test/java/io/vertx/test/core/StarterTest.java
@@ -218,8 +218,6 @@ private void testConfigureFromSystemProperties(boolean clustered) throws Excepti
System.setProperty(Starter.METRICS_OPTIONS_PROP_PREFIX + "enabled", "true");
System.setProperty(Starter.VERTX_OPTIONS_PROP_PREFIX + "haGroup", "somegroup");
- System.setProperty(Starter.DEPLOYMENT_OPTIONS_PROP_PREFIX + "redeployScanInterval", "612536253");
-
MyStarter starter = new MyStarter();
String[] args;
if (clustered) {
@@ -240,9 +238,6 @@ private void testConfigureFromSystemProperties(boolean clustered) throws Excepti
assertEquals(true, opts.getMetricsOptions().isEnabled());
assertEquals("somegroup", opts.getHAGroup());
- DeploymentOptions depOptions = starter.getDeploymentOptions();
-
- assertEquals(612536253, depOptions.getRedeployScanInterval());
}
private void clearProperties() {
diff --git a/src/test/java/io/vertx/test/core/TestVerticle.java b/src/test/java/io/vertx/test/core/TestVerticle.java
index 7dc1869a6b0..dd098e5eb87 100644
--- a/src/test/java/io/vertx/test/core/TestVerticle.java
+++ b/src/test/java/io/vertx/test/core/TestVerticle.java
@@ -38,9 +38,9 @@ public TestVerticle() {
public void start() throws Exception {
processArgs = context.processArgs();
conf = context.config();
- if (Thread.currentThread().getContextClassLoader() != getClass().getClassLoader()) {
- throw new IllegalStateException("Wrong tccl!");
- }
+// if (Thread.currentThread().getContextClassLoader() != getClass().getClassLoader()) {
+// throw new IllegalStateException("Wrong tccl!");
+// }
vertx.eventBus().send("testcounts",
new JsonObject().put("deploymentID", context.deploymentID()).put("count", instanceCount.incrementAndGet()));
}
diff --git a/src/test/resources/redeployverticles/BrokenRedeploySourceVerticle.java b/src/test/resources/redeployverticles/BrokenRedeploySourceVerticle.java
deleted file mode 100644
index 7cfad70562f..00000000000
--- a/src/test/resources/redeployverticles/BrokenRedeploySourceVerticle.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2011-2014 The original author or authors
- * ------------------------------------------------------
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * and Apache License v2.0 which accompanies this distribution.
- *
- * The Eclipse Public License is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * The Apache License v2.0 is available at
- * http://www.opensource.org/licenses/apache2.0.php
- *
- * You may elect to redistribute this code under either of these licenses.
- */
-
-import io.vertx.core.AbstractVerticle;
-import io.vertx.core.DeploymentOptions;
-import io.vertx.core.Future;
-
-/**
- *
- * NOTE - this file is deliberately supposed to be broken!
- *
- * @author <a href="http://tfox.org">Tim Fox</a>
- */
-public class RedeploySourceVerticle extends AbstractVerticle {
-
- @Override
- public void st art() throws Exception {
- vertx.eventBus().publish("vertstarted", context.deploymentID());
- }
-
- @Override
- public void st op() throws Exception {
- vertx.eventBus().publish("vertstopped", context.deploymentID());
- }
-}
\ No newline at end of file
diff --git a/src/test/resources/redeployverticles/RedeploySourceVerticle.java b/src/test/resources/redeployverticles/RedeploySourceVerticle.java
deleted file mode 100644
index 20f09f19bca..00000000000
--- a/src/test/resources/redeployverticles/RedeploySourceVerticle.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2011-2014 The original author or authors
- * ------------------------------------------------------
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * and Apache License v2.0 which accompanies this distribution.
- *
- * The Eclipse Public License is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * The Apache License v2.0 is available at
- * http://www.opensource.org/licenses/apache2.0.php
- *
- * You may elect to redistribute this code under either of these licenses.
- */
-
-import io.vertx.core.AbstractVerticle;
-import io.vertx.core.DeploymentOptions;
-import io.vertx.core.Future;
-import org.junit.Test;
-
-/**
- * @author <a href="http://tfox.org">Tim Fox</a>
- */
-public class RedeploySourceVerticle extends AbstractVerticle {
-
- @Override
- public void start() throws Exception {
- vertx.eventBus().publish("vertstarted", context.deploymentID());
- }
-
- @Override
- public void stop() throws Exception {
- vertx.eventBus().publish("vertstopped", context.deploymentID());
- }
-
- @Test
- public void testDummy() {
-
- }
-}
\ No newline at end of file
|
e4d34d3340b9467ac3d73b3c13f8dde20b428006
|
tapiji
|
Cleans up `tapiji.tools.java.ui`.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java
new file mode 100644
index 00000000..38b3fd3e
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java
@@ -0,0 +1,66 @@
+/*******************************************************************************
+ * 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.quickfix;
+
+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 ExcludeResourceFromInternationalization implements
+ IMarkerResolution2 {
+
+ @Override
+ public String getLabel() {
+ return "Exclude Resource";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ final IResource resource = marker.getResource();
+
+ IWorkbench wb = PlatformUI.getWorkbench();
+ IProgressService ps = wb.getProgressService();
+ try {
+ ps.busyCursorWhile(new IRunnableWithProgress() {
+ public void run(IProgressMonitor pm) {
+
+ ResourceBundleManager manager = null;
+ pm.beginTask(
+ "Excluding Resource from Internationalization", 1);
+
+ if (manager == null
+ || (manager.getProject() != resource.getProject()))
+ manager = ResourceBundleManager.getManager(resource
+ .getProject());
+ manager.excludeResource(resource, pm);
+ pm.worked(1);
+ pm.done();
+ }
+ });
+ } catch (Exception e) {
+ }
+ }
+
+ @Override
+ public String getDescription() {
+ return "Exclude Resource from Internationalization";
+ }
+
+ @Override
+ public Image getImage() {
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java
new file mode 100644
index 00000000..086ed3c3
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java
@@ -0,0 +1,95 @@
+/*******************************************************************************
+ * 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.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.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java
new file mode 100644
index 00000000..f6cc331c
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * 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.quickfix;
+
+import org.eclipse.babel.tapiji.tools.core.Logger;
+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.jdt.core.JavaModelException;
+import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.IMarkerResolution2;
+
+public class IgnoreStringFromInternationalization implements IMarkerResolution2 {
+
+ @Override
+ public String getLabel() {
+ return "Ignore String";
+ }
+
+ @Override
+ public void run(IMarker marker) {
+ IResource resource = marker.getResource();
+
+ CompilationUnit cu = ASTutils.getCompilationUnit(resource);
+
+ 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();
+
+ int position = marker.getAttribute(IMarker.CHAR_START, 0);
+
+ ASTutils.createReplaceNonInternationalisationComment(cu, document,
+ position);
+ textFileBuffer.commit(null, false);
+
+ } catch (JavaModelException e) {
+ Logger.logError(e);
+ } catch (CoreException e) {
+ Logger.logError(e);
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ return "Ignore String from Internationalization";
+ }
+
+ @Override
+ public Image getImage() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java
new file mode 100644
index 00000000..5cc5bd0f
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java
@@ -0,0 +1,94 @@
+/*******************************************************************************
+ * 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.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.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java
new file mode 100644
index 00000000..f75cf058
--- /dev/null
+++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java
@@ -0,0 +1,95 @@
+/*******************************************************************************
+ * 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.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();
+ }
+ }
+ }
+
+}
|
3e0502ea86cfb48d8fe1e1b117781491499b4e00
|
Mylyn Reviews
|
Fixed versions parent
|
p
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/versions/pom.xml b/versions/pom.xml
index 8c91afb3..34a3d638 100644
--- a/versions/pom.xml
+++ b/versions/pom.xml
@@ -3,10 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
- <groupId>org.eclipse.mylyn</groupId>
- <artifactId>mylyn-parent</artifactId>
- <version>3.5.0-SNAPSHOT</version>
- <relativePath>../../org.eclipse.mylyn/org.eclipse.mylyn.releng</relativePath>
+ <groupId>org.eclipse.mylyn.reviews</groupId>
+ <artifactId>mylyn-reviews-parent</artifactId>
+ <version>0.7.0-SNAPSHOT</version>
</parent>
<groupId>org.eclipse.mylyn.versions</groupId>
<artifactId>mylyn-versions-tasks-parent</artifactId>
|
d147f38c1454d3fffcbb85e8c9ce64e9079fc686
|
Valadoc
|
doclets/gtkdoc: Register struct type macro/function
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/doclets/gtkdoc/generator.vala b/src/doclets/gtkdoc/generator.vala
index 38f135a7c4..4c929ab7a2 100644
--- a/src/doclets/gtkdoc/generator.vala
+++ b/src/doclets/gtkdoc/generator.vala
@@ -543,6 +543,12 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
add_symbol (st.get_filename(), st.get_dup_function_cname ());
add_symbol (st.get_filename(), st.get_free_function_cname ());
+
+
+ var file_data = get_file_data (st.get_filename ());
+
+ file_data.register_standard_section_line (st.get_type_macro_name ());
+ file_data.register_standard_section_line (st.get_type_function_name ());
}
/**
|
59cedea0109946484c70601164689d499a8612b0
|
elasticsearch
|
Fix parsing of file based template loading--We support three different settings in templates--* "settings" : { "index" : { "number_of_shards" : 12 } }-* "settings" : { "index.number_of_shards" : 12 }-* "settings" : { "number_of_shards" : 12 }--The latter one was not supported by the fix in -4235--This commit fixes this issue and uses randomized testing to test any of the three cases above when running integration tests.--Closes -4411-
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetaData.java b/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetaData.java
index 6a15044657a73..3ab16f53d2e49 100644
--- a/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetaData.java
+++ b/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetaData.java
@@ -303,7 +303,15 @@ public static IndexTemplateMetaData fromXContent(XContentParser parser) throws I
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("settings".equals(currentFieldName)) {
- builder.settings(ImmutableSettings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered())));
+ ImmutableSettings.Builder templateSettingsBuilder = ImmutableSettings.settingsBuilder();
+ for (Map.Entry<String, String> entry : SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered()).entrySet()) {
+ if (!entry.getKey().startsWith("index.")) {
+ templateSettingsBuilder.put("index." + entry.getKey(), entry.getValue());
+ } else {
+ templateSettingsBuilder.put(entry.getKey(), entry.getValue());
+ }
+ }
+ builder.settings(templateSettingsBuilder.build());
} else if ("mappings".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
diff --git a/src/test/java/org/elasticsearch/indices/template/IndexTemplateFileLoadingTests.java b/src/test/java/org/elasticsearch/indices/template/IndexTemplateFileLoadingTests.java
index 606d78d166665..de451120370cf 100644
--- a/src/test/java/org/elasticsearch/indices/template/IndexTemplateFileLoadingTests.java
+++ b/src/test/java/org/elasticsearch/indices/template/IndexTemplateFileLoadingTests.java
@@ -38,7 +38,7 @@
/**
*
*/
-@ClusterScope(scope= Scope.SUITE, numNodes=1)
+@ClusterScope(scope=Scope.SUITE, numNodes=1)
public class IndexTemplateFileLoadingTests extends ElasticsearchIntegrationTest {
@Rule
@@ -57,7 +57,8 @@ protected Settings nodeSettings(int nodeOrdinal) {
templatesDir.mkdir();
File dst = new File(templatesDir, "template.json");
- String template = Streams.copyToStringFromClasspath("/org/elasticsearch/indices/template/template.json");
+ // random template, one uses the 'setting.index.number_of_shards', the other 'settings.number_of_shards'
+ String template = Streams.copyToStringFromClasspath("/org/elasticsearch/indices/template/template" + randomInt(1) + ".json");
Files.write(template, dst, Charsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException(e);
diff --git a/src/test/java/org/elasticsearch/indices/template/template.json b/src/test/java/org/elasticsearch/indices/template/template0.json
similarity index 100%
rename from src/test/java/org/elasticsearch/indices/template/template.json
rename to src/test/java/org/elasticsearch/indices/template/template0.json
diff --git a/src/test/java/org/elasticsearch/indices/template/template1.json b/src/test/java/org/elasticsearch/indices/template/template1.json
new file mode 100644
index 0000000000000..f91866865e7f5
--- /dev/null
+++ b/src/test/java/org/elasticsearch/indices/template/template1.json
@@ -0,0 +1,7 @@
+{
+ "template" : "foo*",
+ "settings" : {
+ "number_of_shards": 10,
+ "number_of_replicas": 0
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/org/elasticsearch/indices/template/template2.json b/src/test/java/org/elasticsearch/indices/template/template2.json
new file mode 100644
index 0000000000000..c48169f15a519
--- /dev/null
+++ b/src/test/java/org/elasticsearch/indices/template/template2.json
@@ -0,0 +1,9 @@
+{
+ "template" : "foo*",
+ "settings" : {
+ "index" : {
+ "number_of_shards": 10,
+ "number_of_replicas": 0
+ }
+ }
+}
\ No newline at end of file
|
1e7118488498b508c447c1abc5ded02d7c6f16d1
|
Mylyn Reviews
|
bug 380843: index commit messages of changesets
use iterator function to retrieve the changesets
added some more null checks
https://bugs.eclipse.org/bugs/show_bug.cgi?id=380843
Change-Id: I3484580c00372fd9276653e46ea8f552272af27f
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
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 3a4b6b97..aae50b2f 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
@@ -72,7 +72,9 @@ private List<ScmRepository> getRepositoriesFor(ITask task)
task.getConnectorKind(), task.getRepositoryUrl());
for (IProject p : projects) {
ScmRepository repository = getRepositoryForProject(p);
- repos.add(repository);
+ if(repository!=null) {
+ repos.add(repository);
+ }
}
return new ArrayList<ScmRepository>(repos);
}
@@ -80,6 +82,9 @@ private List<ScmRepository> getRepositoriesFor(ITask task)
private ScmRepository getRepositoryForProject(IProject p)
throws CoreException {
ScmConnector connector = ScmCore.getConnector(p);
+ if(connector==null) {
+ return null;
+ }
ScmRepository repository = connector.getRepository(p,
new NullProgressMonitor());
return repository;
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
index 1ea07839..deae9245 100644
--- 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
@@ -11,6 +11,7 @@
package org.eclipse.mylyn.versions.tasks.mapper.internal;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Set;
@@ -39,16 +40,18 @@ public void fetchAllChangesets(IProgressMonitor monitor,
.getProjects()) {
ScmConnector connector = ScmCore.getConnector(project);
if(connector!=null) {
- repositories.add(connector.getRepository(project, monitor));
+ ScmRepository repository = connector.getRepository(project, monitor);
+ repositories.add(repository);
}
}
for (ScmRepository repo : repositories) {
- List<ChangeSet> changesets;
- changesets = repo.getConnector().getChangeSets(repo, monitor);
- for (ChangeSet cs : changesets) {
+ Iterator<ChangeSet> changesets = repo.getConnector().getChangeSetsIterator(repo, monitor);
+ while (changesets.hasNext()) {
+ ChangeSet cs =changesets.next();
indexer.index(cs);
}
+
}
}
|
ebfe7b7411f413a8631fec22e704a0d8921f4417
|
Vala
|
codegen: Inherit array_{length,null_terminated} from base parameter
First commit to start inheriting ccode attributes of parameters
from base parameters of base methods.
Partially fixes bug 642885.
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valaccodeattribute.vala b/codegen/valaccodeattribute.vala
index 82a74f7c3b..05745df0cf 100644
--- a/codegen/valaccodeattribute.vala
+++ b/codegen/valaccodeattribute.vala
@@ -468,9 +468,36 @@ public class Vala.CCodeAttribute : AttributeCache {
}
}
- public bool array_length { get; private set; }
+ public bool array_length {
+ get {
+ if (_array_length == null) {
+ if (node.get_attribute ("NoArrayLength") != null) {
+ // deprecated
+ _array_length = false;
+ } else if (ccode != null && ccode.has_argument ("array_length")) {
+ _array_length = ccode.get_bool ("array_length");
+ } else {
+ _array_length = get_default_array_length ();
+ }
+ }
+ return _array_length;
+ }
+ }
+
+ public bool array_null_terminated {
+ get {
+ if (_array_null_terminated == null) {
+ if (ccode != null && ccode.has_argument ("array_null_terminated")) {
+ _array_null_terminated = ccode.get_bool ("array_null_terminated");
+ } else {
+ _array_null_terminated = get_default_array_null_terminated ();
+ }
+ }
+ return _array_null_terminated;
+ }
+ }
+
public string? array_length_type { get; private set; }
- public bool array_null_terminated { get; private set; }
public string? array_length_name { get; private set; }
public string? array_length_expr { get; private set; }
public bool delegate_target { get; private set; }
@@ -512,6 +539,8 @@ public class Vala.CCodeAttribute : AttributeCache {
private string _delegate_target_name;
private string _ctype;
private bool ctype_set = false;
+ private bool? _array_length;
+ private bool? _array_null_terminated;
private static int dynamic_method_id;
@@ -519,13 +548,10 @@ public class Vala.CCodeAttribute : AttributeCache {
this.node = node;
this.sym = node as Symbol;
- array_length = true;
delegate_target = true;
ccode = node.get_attribute ("CCode");
if (ccode != null) {
- array_length = ccode.get_bool ("array_length", true);
array_length_type = ccode.get_string ("array_length_type");
- array_null_terminated = ccode.get_bool ("array_null_terminated");
array_length_name = ccode.get_string ("array_length_cname");
array_length_expr = ccode.get_string ("array_length_cexpr");
if (ccode.has_argument ("pos")) {
@@ -534,10 +560,6 @@ public class Vala.CCodeAttribute : AttributeCache {
delegate_target = ccode.get_bool ("delegate_target", true);
sentinel = ccode.get_string ("sentinel");
}
- if (node.get_attribute ("NoArrayLength") != null) {
- // deprecated
- array_length = false;
- }
if (sentinel == null) {
sentinel = "NULL";
}
@@ -1274,4 +1296,24 @@ public class Vala.CCodeAttribute : AttributeCache {
}
}
}
+
+ private bool get_default_array_length () {
+ if (node is Parameter) {
+ var param = (Parameter) node;
+ if (param.base_parameter != null) {
+ return CCodeBaseModule.get_ccode_array_length (param.base_parameter);
+ }
+ }
+ return true;
+ }
+
+ private bool get_default_array_null_terminated () {
+ if (node is Parameter) {
+ var param = (Parameter) node;
+ if (param.base_parameter != null) {
+ return CCodeBaseModule.get_ccode_array_null_terminated (param.base_parameter);
+ }
+ }
+ return false;
+ }
}
diff --git a/tests/Makefile.am b/tests/Makefile.am
index b84d433ebd..de7e823236 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -48,6 +48,7 @@ TESTS = \
methods/bug620673.vala \
methods/bug622570.vala \
methods/bug639054.vala \
+ methods/bug642885.vala \
methods/bug642899.vala \
methods/bug646345.vala \
methods/bug648320.vala \
diff --git a/tests/methods/bug642885.vala b/tests/methods/bug642885.vala
new file mode 100644
index 0000000000..4acf97db53
--- /dev/null
+++ b/tests/methods/bug642885.vala
@@ -0,0 +1,36 @@
+public class Foo : Application {
+ public bool activated = false;
+
+ public Foo () {
+ Object (application_id: "org.foo.bar");
+ }
+
+ protected override void activate () {
+ activated = true;
+ }
+
+ protected override bool local_command_line (ref unowned string[] arguments, out int exit_status) {
+ var option_context = new OptionContext ();
+
+ // FIXME: https://bugzilla.gnome.org/show_bug.cgi?id=642885
+ unowned string[] args = arguments;
+
+ try {
+ option_context.parse (ref args);
+ } catch (OptionError e) {
+ exit_status = 1;
+ return true;
+ }
+
+ return base.local_command_line (ref arguments, out exit_status);
+ }
+}
+
+void main () {
+ string[] args = {""};
+ var app = new Foo ();
+ app.run (args);
+ assert (app.activated);
+}
+
+
diff --git a/vala/valaparameter.vala b/vala/valaparameter.vala
index c42d6f33a5..10f0eed1ec 100644
--- a/vala/valaparameter.vala
+++ b/vala/valaparameter.vala
@@ -44,6 +44,11 @@ public class Vala.Parameter : Variable {
public bool captured { get; set; }
+ /**
+ * The base parameter of this parameter relative to the base method.
+ */
+ public Parameter base_parameter { get; set; }
+
/**
* Creates a new formal parameter.
*
@@ -180,6 +185,15 @@ public class Vala.Parameter : Variable {
}
}
+ var m = parent_symbol as Method;
+ if (m != null) {
+ Method base_method = m.base_method != null ? m.base_method : m.base_interface_method;
+ if (base_method != null && base_method != m) {
+ int index = m.get_parameters ().index_of (this);
+ base_parameter = base_method.get_parameters ().get (index);
+ }
+ }
+
context.analyzer.current_source_file = old_source_file;
context.analyzer.current_symbol = old_symbol;
|
ff5df7d320c9819754586497eb36a07a2d384652
|
Delta Spike
|
DELTASPIKE-289 implement ClientWindowConfig
This can be used to determine the window handling behaviour
for each request.
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java
index 8acd0e663..b4acc468e 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java
@@ -43,12 +43,6 @@ public class WindowBeanHolder implements Serializable
*/
private volatile Map<String, ContextualStorage> storageMap = new ConcurrentHashMap<String, ContextualStorage>();
- //X TODO review usage
- public Map<String, ContextualStorage> getStorageMap()
- {
- return storageMap;
- }
-
/**
* This method will return the ContextualStorage or create a new one
* if no one is yet assigned to the current windowId.
@@ -90,6 +84,13 @@ public Map<String, ContextualStorage> forceNewStorage()
return oldStorageMap;
}
+ /**
+ * This method properly destroys all current @WindowScoped beans
+ * of the active session and also prepares the storage for new beans.
+ * It will automatically get called when the session context closes
+ * but can also get invoked manually, e.g. if a user likes to get rid
+ * of all it's @WindowScoped beans.
+ */
@PreDestroy
public void destroyBeans()
{
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java
index e9aa32661..ebda22914 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java
@@ -30,7 +30,9 @@
import org.apache.deltaspike.core.util.context.ContextualStorage;
/**
- * Context to handle @{@link WindowScoped} beans.
+ * CDI Context to handle @{@link WindowScoped} beans.
+ * This also implements the interface to control the id of
+ * the currently active 'window' (e.g. a web browser tab).
*/
@Typed()
public class WindowContextImpl extends AbstractContext implements WindowContext
diff --git a/deltaspike/modules/jsf/api/pom.xml b/deltaspike/modules/jsf/api/pom.xml
index cdc9c6319..874148c2b 100644
--- a/deltaspike/modules/jsf/api/pom.xml
+++ b/deltaspike/modules/jsf/api/pom.xml
@@ -36,6 +36,17 @@
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>deltaspike-core-api</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-servlet_2.5_spec</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.myfaces.core</groupId>
+ <artifactId>myfaces-api</artifactId>
+ </dependency>
+
+
</dependencies>
diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java
new file mode 100644
index 000000000..94690ec2a
--- /dev/null
+++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java
@@ -0,0 +1,79 @@
+/*
+ * 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.spi.window;
+
+import javax.faces.context.FacesContext;
+
+/**
+ * Configuration for ClientWindow handler which is used
+ * to determine the correct windowId for ?WindowScoped beans.
+ */
+public interface ClientWindowConfig
+{
+ public enum ClientWindowRenderMode
+ {
+ /**
+ * Any window or browser tab detection is disabled for this request
+ */
+ NONE,
+
+ /**
+ * <p>The GET request results in an intermediate small html page which
+ * checks if the browser tab fits the selected windowId</p>
+ * <p>The ClientWindow html extracts the windowId from the window.name and
+ * enforces a 2nd GET which will contain the windowId and will get routed
+ * through to the target JSF page.</p>
+ */
+ CLIENTWINDOW,
+
+ /**
+ * Render each GET request with the windowId you get during the request
+ * and perform a lazy check on the client side via JavaScript or similar.
+ */
+ LAZY
+
+ }
+
+ /**
+ * @return whether JavaScript is enabled
+ */
+ boolean isJavaScriptEnabled();
+
+ /**
+ * @param javaScriptEnabled whether JavaScript is enabled
+ */
+ void setJavaScriptEnabled(boolean javaScriptEnabled);
+
+ /**
+ * Determine whether this request should take care of clientWindow detection.
+ * This can e.g. get disabled for download pages or if a useragent doesn't
+ * support html5 or any other required technique.
+ * This only gets checked for GET requests!
+ *
+ * @param facesContext
+ * @return the selected ClientWindowRenderMode
+ */
+ ClientWindowRenderMode getClientWindowRenderMode(FacesContext facesContext);
+
+ /**
+ * @return the prepared html which gets sent out to the client as intermediate client window.
+ */
+ String getClientWindowHtml();
+
+}
diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java
new file mode 100644
index 000000000..dbec59177
--- /dev/null
+++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java
@@ -0,0 +1,215 @@
+/*
+ * 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.spi.window;
+
+import javax.enterprise.context.SessionScoped;
+import javax.faces.context.FacesContext;
+import javax.inject.Inject;
+import javax.servlet.http.Cookie;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Serializable;
+import java.util.Map;
+
+import org.apache.deltaspike.core.api.projectstage.ProjectStage;
+import org.apache.deltaspike.core.util.ClassUtils;
+import org.apache.deltaspike.core.util.ExceptionUtils;
+
+/**
+ * Default implementation of {@link ClientWindowConfig}.
+ * It will use the internal <code>windowhandler.html</code>
+ */
+@SessionScoped
+public class DefaultClientWindowConfig implements ClientWindowConfig, Serializable
+{
+ /**
+ * We will set a cookie with this very name if a noscript link got clicked by the user
+ */
+ public static final String COOKIE_NAME_NOSCRIPT_ENABLED = "deltaspikeNoScriptEnabled";
+
+ /**
+ * The location of the default windowhandler resource
+ */
+ private static final String DEFAULT_WINDOW_HANDLER_HTML_FILE = "static/windowhandler.html";
+
+
+ private volatile Boolean javaScriptEnabled = null;
+
+ /**
+ * lazily initiated via {@link #getUserAgent(javax.faces.context.FacesContext)}
+ */
+ private volatile String userAgent = null;
+
+ /**
+ * Contains the cached ClientWindow handler html for this session.
+ */
+ private String clientWindowtml;
+
+ @Inject
+ private ProjectStage projectStage;
+
+
+ @Override
+ public boolean isJavaScriptEnabled()
+ {
+ if (javaScriptEnabled == null)
+ {
+ synchronized (this)
+ {
+ // double lock checking idiom on volatile variable works since java5
+ if (javaScriptEnabled == null)
+ {
+ // no info means that it is default -> true
+ javaScriptEnabled = Boolean.TRUE;
+
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ if (facesContext != null)
+ {
+ Cookie cookie = (Cookie) facesContext.getExternalContext().
+ getRequestCookieMap().get(COOKIE_NAME_NOSCRIPT_ENABLED);
+ if (cookie != null)
+ {
+ javaScriptEnabled = Boolean.parseBoolean(cookie.getValue());
+ }
+ }
+ }
+ }
+ }
+ return javaScriptEnabled;
+ }
+
+
+ @Override
+ public void setJavaScriptEnabled(boolean javaScriptEnabled)
+ {
+ this.javaScriptEnabled = Boolean.valueOf(javaScriptEnabled);
+ }
+
+ /**
+ * By default we use {@link ClientWindowRenderMode#CLIENTWINDOW} unless
+ * we detect a bot.
+ * Override this method to exclude other requests from getting accessed.
+ *
+ * @param facesContext
+ * @return
+ */
+ @Override
+ public ClientWindowRenderMode getClientWindowRenderMode(FacesContext facesContext)
+ {
+ if (!isJavaScriptEnabled())
+ {
+ return ClientWindowRenderMode.NONE;
+ }
+
+ String userAgent = getUserAgent(facesContext);
+
+ if (userAgent != null &&
+ ( userAgent.indexOf("bot") >= 0 || // Googlebot, etc
+ userAgent.indexOf("Bot") >= 0 || // BingBot, etc
+ userAgent.indexOf("Slurp") >= 0 || // Yahoo Slurp
+ userAgent.indexOf("Crawler") >= 0 // various other Crawlers
+ ) )
+ {
+ return ClientWindowRenderMode.NONE;
+ }
+
+ return ClientWindowRenderMode.CLIENTWINDOW;
+ }
+
+ @Override
+ public String getClientWindowHtml()
+ {
+ if (projectStage != ProjectStage.Development && clientWindowtml != null)
+ {
+ // use cached windowHandlerHtml except in Development
+ return clientWindowtml;
+ }
+
+ InputStream is = ClassUtils.getClassLoader(null).getResourceAsStream(getClientWindowResourceLocation());
+ StringBuffer sb = new StringBuffer();
+ try
+ {
+ byte[] buf = new byte[16 * 1024];
+ int bytesRead;
+ while ((bytesRead = is.read(buf)) != -1)
+ {
+ String sbuf = new String(buf, 0, bytesRead);
+ sb.append(sbuf);
+ }
+ }
+ catch (IOException e)
+ {
+ ExceptionUtils.throwAsRuntimeException(e);
+ }
+ finally
+ {
+ try
+ {
+ is.close();
+ }
+ catch (IOException e)
+ {
+ // do nothing, all fine so far
+ }
+ }
+
+ clientWindowtml = sb.toString();
+
+ return clientWindowtml;
+ }
+
+ /**
+ * This information will get stored as it cannot
+ * change during the session anyway.
+ * @return the UserAgent of the request.
+ */
+ public String getUserAgent(FacesContext facesContext)
+ {
+ if (userAgent == null)
+ {
+ synchronized (this)
+ {
+ if (userAgent == null)
+ {
+ Map<String, String[]> requestHeaders =
+ facesContext.getExternalContext().getRequestHeaderValuesMap();
+
+ if (requestHeaders != null &&
+ requestHeaders.containsKey("User-Agent"))
+ {
+ String[] userAgents = requestHeaders.get("User-Agent");
+ userAgent = userAgents.length > 0 ? userAgents[0] : null;
+ }
+ }
+ }
+ }
+
+ return userAgent;
+ }
+
+
+ /**
+ * Overwrite this to define your own ClientWindow handler html location.
+ * This will get picked up as resource from the classpath.
+ */
+ public String getClientWindowResourceLocation()
+ {
+ return DEFAULT_WINDOW_HANDLER_HTML_FILE;
+ }
+}
|
2299b927c8dbfaad4761ed07c3c709e8e5d1c3b8
|
orientdb
|
fixed bug on shutdown--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/src/main/java/com/orientechnologies/lucene/manager/OLuceneIndexManagerAbstract.java b/src/main/java/com/orientechnologies/lucene/manager/OLuceneIndexManagerAbstract.java
index b36472b5846..f55130922a8 100644
--- a/src/main/java/com/orientechnologies/lucene/manager/OLuceneIndexManagerAbstract.java
+++ b/src/main/java/com/orientechnologies/lucene/manager/OLuceneIndexManagerAbstract.java
@@ -121,8 +121,8 @@ protected void initIndex(String indexName, OIndexDefinition indexDefinition, Str
private void reOpen(ODocument metadata) throws IOException {
ODatabaseRecord database = getDatabase();
final OStorageLocalAbstract storageLocalAbstract = (OStorageLocalAbstract) database.getStorage().getUnderlying();
- Directory dir = NIOFSDirectory.open(new File(storageLocalAbstract.getStoragePath() + File.separator + OLUCENE_BASE_DIR
- + File.separator + indexName));
+ String pathname = getIndexPath(storageLocalAbstract);
+ Directory dir = NIOFSDirectory.open(new File(pathname));
indexWriter = createIndexWriter(dir, metadata);
mgrWriter = new TrackingIndexWriter(indexWriter);
manager = new SearcherManager(indexWriter, true, null);
@@ -133,6 +133,10 @@ private void reOpen(ODocument metadata) throws IOException {
nrt.start();
}
+ private String getIndexPath(OStorageLocalAbstract storageLocalAbstract) {
+ return storageLocalAbstract.getStoragePath() + File.separator + OLUCENE_BASE_DIR + File.separator + indexName;
+ }
+
protected IndexSearcher getSearcher() throws IOException {
try {
nrt.waitForGeneration(reopenToken);
@@ -184,12 +188,15 @@ public void delete() {
try {
if (indexWriter != null) {
indexWriter.deleteAll();
+
+ nrt.interrupt();
+ nrt.close();
+
indexWriter.close();
- indexWriter.getDirectory().close();
}
ODatabaseRecord database = getDatabase();
final OStorageLocalAbstract storageLocalAbstract = (OStorageLocalAbstract) database.getStorage().getUnderlying();
- File f = new File(storageLocalAbstract.getStoragePath() + File.separator + indexName);
+ File f = new File(getIndexPath(storageLocalAbstract));
OLuceneIndexUtils.deleteFolder(f);
@@ -259,7 +266,9 @@ public void flush() {
@Override
public void close() {
try {
+ nrt.interrupt();
nrt.close();
+ indexWriter.commit();
indexWriter.close();
} catch (IOException e) {
e.printStackTrace();
@@ -329,7 +338,15 @@ public Analyzer getAnalyzer(ODocument metadata) {
} catch (ClassNotFoundException e) {
throw new OIndexException("Analyzer: " + analyzerString + " not found", e);
} catch (NoSuchMethodException e) {
- e.printStackTrace();
+ Class classAnalyzer = null;
+ try {
+ classAnalyzer = Class.forName(analyzerString);
+ analyzer = (Analyzer) classAnalyzer.newInstance();
+
+ } catch (Throwable e1) {
+ throw new OIndexException("Couldn't instantiate analyzer: public constructor not found", e1);
+ }
+
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
diff --git a/src/test/java/com/orientechnologies/test/lucene-local-test.xml b/src/test/java/com/orientechnologies/test/lucene-local-test.xml
new file mode 100755
index 00000000000..4a451ed031a
--- /dev/null
+++ b/src/test/java/com/orientechnologies/test/lucene-local-test.xml
@@ -0,0 +1,194 @@
+<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd">
+<suite name="Local Test Suite" verbose="2" parallel="false">
+
+ <parameter name="path" value="@PATH@"/>
+ <parameter name="url" value="@URL@"/>
+ <parameter name="testPath" value="@TESTPATH@"/>
+
+ <test name="Setup">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.base.DeleteDirectory"/>
+ </classes>
+ </test>
+
+ <test name="DbCreation">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DbListenerTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DbCreationTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.StorageTest"/>
+ </classes>
+ </test>
+ <test name="Schema">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.SchemaTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.AbstractClassTest"/>
+ </classes>
+ </test>
+ <test name="Security">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.SecurityTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.RestrictedTest"/>
+ </classes>
+ </test>
+ <test name="Hook">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.HookTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.HookTxTest"/>
+ </classes>
+ </test>
+ <test name="Population">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.ComplexTypesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDFlatPhysicalTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDObjectInheritanceTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDDocumentPhysicalTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDObjectPhysicalTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDFlatPhysicalTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDDocumentValidationTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.RecordMetadataTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectTreeTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectDetachingTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectEnhancingTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DocumentTrackingTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.EmbeddedObjectSerializationTest"/>
+ </classes>
+ </test>
+ <test name="PopulationObjectSchemaFull">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDObjectInheritanceTestSchemaFull"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDObjectPhysicalTestSchemaFull"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectTreeTestSchemaFull"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectDetachingTestSchemaFull"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectEnhancingTestSchemaFull"/>
+ </classes>
+ </test>
+ <test name="Tx">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.TransactionAtomicTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.TransactionOptimisticTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.TransactionConsistencyTest"/>
+ </classes>
+ </test>
+ <test name="Index">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DateIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLEscapingTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectHashIndexReuseTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexCustomKeyTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexClusterTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ByteArrayKeyTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.FullTextIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ClassIndexManagerTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectIndexReuseTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLCreateIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLDropIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLDropClassIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLDropPropertyIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SchemaIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ClassIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.PropertyIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CollectionIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectCompositeIndexDirectSearchTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareOneValueGetValuesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareMultiValueGetValuesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareMultiValueGetTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareOneValueGetTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareMultiValueGetEntriesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareOneValueGetEntriesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.MapIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectByLinkedPropertyIndexReuseTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.LinkListIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.LinkMapIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLIndexWithoutSchemaTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.OrderByIndexReuseTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.LinkSetIndexTest"/>
+ </classes>
+ </test>
+ <test name="Dictionary">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DictionaryTest"/>
+ </classes>
+ </test>
+ <test name="Query">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.WrongQueryTest"/>
+ </classes>
+ </test>
+ <test name="Parsing">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.JSONTest"/>
+ </classes>
+ </test>
+ <test name="Graph">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.GraphDatabaseTest"/>
+ <!-- <class name="com.orientechnologies.orient.test.database.auto.SQLCreateVertexAndEdgeTest"/> -->
+ </classes>
+ </test>
+ <test name="GEO">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.GEOTest"/>
+ </classes>
+ </test>
+ <test name="Index Manager">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexManagerTest"/>
+ </classes>
+ </test>
+ <test name="Binary">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.BinaryTest"/>
+ </classes>
+ </test>
+ <test name="sql-commands">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLCommandsTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLInsertTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLMetadataTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectProjectionsTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectGroupByTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLFunctionsTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLUpdateTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLDeleteTest"/>
+ </classes>
+ </test>
+ <test name="other-commands">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.TraverseTest"/>
+ </classes>
+ </test>
+ <test name="misc">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.TruncateTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DateTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLFindReferencesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLCreateLinkTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.MultipleDBTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ConcurrentUpdatesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ConcurrentQueriesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DatabaseThreadFactoryTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CollateTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.PoolTest"/>
+ </classes>
+ </test>
+ <test name="DbTools">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DbCheckTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DbImportExportTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DbCompareTest"/>
+ </classes>
+ </test>
+ <test name="DbToolsDelete">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DbDeleteTest"/>
+ </classes>
+ </test>
+ <test name="End">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DbClosedTest"/>
+ </classes>
+ </test>
+</suite>
\ No newline at end of file
|
6ffe00e3fa8e1cad4e965d087ab1a9c312e1bd8f
|
Vala
|
libsoup-2.4: SoupMessageBody.data should be uing8[], not string.
Fixes bug 605862.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/libsoup-2.4.vapi b/vapi/libsoup-2.4.vapi
index d58918dc17..64d2c4ca75 100644
--- a/vapi/libsoup-2.4.vapi
+++ b/vapi/libsoup-2.4.vapi
@@ -264,7 +264,8 @@ namespace Soup {
[Compact]
[CCode (type_id = "SOUP_TYPE_MESSAGE_BODY", cheader_filename = "libsoup/soup.h")]
public class MessageBody {
- public weak string data;
+ [CCode (array_length = false)]
+ public weak uint8[] data;
public int64 length;
[CCode (has_construct_function = false)]
public MessageBody ();
diff --git a/vapi/packages/libsoup-2.4/libsoup-2.4.metadata b/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
index 8b8ca42fce..00a69cd525 100644
--- a/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
+++ b/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
@@ -22,6 +22,7 @@ SoupMessage::wrote_informational has_emitter="1"
soup_message_headers_get_content_disposition.disposition transfer_ownership="1"
soup_message_headers_get_content_disposition.params is_out="1" transfer_ownership="1"
soup_message_headers_get_content_type.params is_out="1" transfer_ownership="1"
+SoupMessageBody.data type_name="uint8" is_array="1"
soup_server_new ellipsis="1"
soup_server_add_handler.destroy hidden="1"
soup_server_add_handler.callback transfer_ownership="1"
|
fc1965d648bf40466b46770bad874de80c480dd4
|
Mylyn Reviews
|
Merge branch '331862_move_review_parts'
|
p
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
deleted file mode 100644
index b93a9fc9..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,18 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Reviews Core (Incubation)
-Bundle-SymbolicName: org.eclipse.mylyn.reviews.core;singleton:=true
-Bundle-Version: 0.0.1
-Bundle-Activator: org.eclipse.mylyn.reviews.core.Activator
-Require-Bundle: org.eclipse.core.runtime,
- org.eclipse.emf.edit;bundle-version="2.5.0",
- org.eclipse.team.core;bundle-version="3.5.0",
- org.eclipse.core.resources;bundle-version="3.5.1",
- org.eclipse.mylyn.tasks.core;bundle-version="3.3.0",
- org.eclipse.compare;bundle-version="3.5.0"
-Bundle-ActivationPolicy: lazy
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Export-Package: org.eclipse.mylyn.reviews.core,
- org.eclipse.mylyn.reviews.core.model.review,
- org.eclipse.mylyn.reviews.core.model.review.impl,
- org.eclipse.mylyn.reviews.core.model.review.util
diff --git a/tbr/org.eclipse.mylyn.reviews.core/model/review.ecore b/tbr/org.eclipse.mylyn.reviews.core/model/review.ecore
deleted file mode 100644
index f2d227e6..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/model/review.ecore
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ecore:EPackage xmi:version="2.0"
- xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="review"
- nsURI="org.eclipse.mylyn.reviews" nsPrefix="">
- <eClassifiers xsi:type="ecore:EClass" name="Review">
- <eStructuralFeatures xsi:type="ecore:EReference" name="result" eType="#//ReviewResult"/>
- <eStructuralFeatures xsi:type="ecore:EReference" name="scope" upperBound="-1"
- eType="#//ScopeItem"/>
- </eClassifiers>
- <eClassifiers xsi:type="ecore:EClass" name="ReviewResult">
- <eStructuralFeatures xsi:type="ecore:EAttribute" name="text" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
- <eStructuralFeatures xsi:type="ecore:EAttribute" name="rating" eType="#//Rating"/>
- <eStructuralFeatures xsi:type="ecore:EAttribute" name="reviewer" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
- </eClassifiers>
- <eClassifiers xsi:type="ecore:EClass" name="Patch" eSuperTypes="#//ScopeItem">
- <eOperations name="parse" upperBound="-1" eType="#//IFilePatch2"/>
- <eStructuralFeatures xsi:type="ecore:EAttribute" name="contents" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
- <eStructuralFeatures xsi:type="ecore:EAttribute" name="creationDate" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EDate"/>
- <eStructuralFeatures xsi:type="ecore:EAttribute" name="fileName" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
- </eClassifiers>
- <eClassifiers xsi:type="ecore:EEnum" name="Rating">
- <eLiterals name="NONE"/>
- <eLiterals name="PASSED"/>
- <eLiterals name="WARNING"/>
- <eLiterals name="FAILED"/>
- </eClassifiers>
- <eClassifiers xsi:type="ecore:EDataType" name="IFilePatch2" instanceClassName="org.eclipse.compare.patch.IFilePatch2"/>
- <eClassifiers xsi:type="ecore:EDataType" name="IProgressMonitor" instanceClassName="org.eclipse.core.runtime.IProgressMonitor"/>
- <eClassifiers xsi:type="ecore:EClass" name="ScopeItem">
- <eStructuralFeatures xsi:type="ecore:EAttribute" name="author" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
- </eClassifiers>
-</ecore:EPackage>
diff --git a/tbr/org.eclipse.mylyn.reviews.core/model/review.genmodel b/tbr/org.eclipse.mylyn.reviews.core/model/review.genmodel
deleted file mode 100644
index c3b7f79e..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/model/review.genmodel
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<genmodel:GenModel xmi:version="2.0"
- xmlns:xmi="http://www.omg.org/XMI" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore"
- xmlns:genmodel="http://www.eclipse.org/emf/2002/GenModel" modelDirectory="/org.eclipse.mylyn.reviews.core/src"
- modelPluginID="org.eclipse.mylyn.reviews.core" modelName="Review" importerID="org.eclipse.emf.importer.ecore"
- complianceLevel="5.0" copyrightFields="false">
- <foreignModel>review.ecore</foreignModel>
- <genPackages prefix="Review" basePackage="org.eclipse.mylyn.reviews.core.model"
- disposableProviderFactory="true" ecorePackage="review.ecore#/">
- <genEnums typeSafeEnumCompatible="false" ecoreEnum="review.ecore#//Rating">
- <genEnumLiterals ecoreEnumLiteral="review.ecore#//Rating/NONE"/>
- <genEnumLiterals ecoreEnumLiteral="review.ecore#//Rating/PASSED"/>
- <genEnumLiterals ecoreEnumLiteral="review.ecore#//Rating/WARNING"/>
- <genEnumLiterals ecoreEnumLiteral="review.ecore#//Rating/FAILED"/>
- </genEnums>
- <genDataTypes ecoreDataType="review.ecore#//IFilePatch2"/>
- <genDataTypes ecoreDataType="review.ecore#//IProgressMonitor"/>
- <genClasses ecoreClass="review.ecore#//Review">
- <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference review.ecore#//Review/result"/>
- <genFeatures notify="false" createChild="false" propertySortChoices="true" ecoreFeature="ecore:EReference review.ecore#//Review/scope"/>
- </genClasses>
- <genClasses ecoreClass="review.ecore#//ReviewResult">
- <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//ReviewResult/text"/>
- <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//ReviewResult/rating"/>
- <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//ReviewResult/reviewer"/>
- </genClasses>
- <genClasses ecoreClass="review.ecore#//Patch">
- <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//Patch/contents"/>
- <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//Patch/creationDate"/>
- <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//Patch/fileName"/>
- <genOperations ecoreOperation="review.ecore#//Patch/parse"/>
- </genClasses>
- <genClasses ecoreClass="review.ecore#//ScopeItem">
- <genFeatures createChild="false" ecoreFeature="ecore:EAttribute review.ecore#//ScopeItem/author"/>
- </genClasses>
- </genPackages>
-</genmodel:GenModel>
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/Activator.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/Activator.java
deleted file mode 100644
index 16999003..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/Activator.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.core;
-
-import org.eclipse.core.runtime.Plugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- * @author Kilian Matt
- */
-public class Activator extends Plugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "org.eclipse.mylyn.reviews.core"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator plugin;
-
- /**
- * The constructor
- */
- public Activator() {
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- 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/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
deleted file mode 100644
index bcf8c548..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.eclipse.mylyn.reviews.core;
-
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.tasks.core.ITask;
-
-public class ReviewData {
- private boolean outgoing;
- private Review review;
- private ITask task;
- private boolean dirty;
-
- public ReviewData(ITask task, Review review) {
- this.task=task;
- this.review = review;
- }
-
- public boolean isOutgoing() {
- return outgoing;
- }
-
- public void setOutgoing() {
- this.outgoing = true;
- }
-
- public void setOutgoing(boolean outgoing) {
- this.outgoing = outgoing;
- }
-
- public ITask getTask() {
- return task;
- }
-
- public Review getReview() {
- return review;
- }
-
- public void setDirty(boolean isDirty) {
- this.dirty=isDirty;
- }
-
- public void setDirty() {
- setDirty(true);
- }
- public boolean isDirty() {
- return this.dirty;
- }
-
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
deleted file mode 100644
index 13ec95fd..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataManager.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package org.eclipse.mylyn.reviews.core;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.emf.common.notify.Adapter;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.common.notify.Notifier;
-import org.eclipse.emf.common.notify.impl.AdapterImpl;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.tasks.core.IRepositoryModel;
-import org.eclipse.mylyn.tasks.core.ITask;
-import org.eclipse.mylyn.tasks.core.data.ITaskDataManager;
-
-public class ReviewDataManager {
- private Map<ITask, ReviewData> cached = new HashMap<ITask, ReviewData>();
- private ReviewDataStore store;
- private ITaskDataManager taskDataManager;
- private IRepositoryModel repositoryModel;
-
- public ReviewDataManager(ReviewDataStore store,
- ITaskDataManager taskDataManager, IRepositoryModel repositoryModel) {
- this.store = store;
- this.taskDataManager = taskDataManager;
- this.repositoryModel = repositoryModel;
-
- }
-
- public void storeOutgoingTask(ITask task, Review review) {
- ReviewData reviewData = new ReviewData(task, review);
- reviewData.setOutgoing();
- cached.put(task, reviewData);
- store.storeReviewData(task.getRepositoryUrl(), task.getTaskId(),
- review, "review");
- }
-
- public ReviewData getReviewData(ITask task) {
- if (task == null)
- return null;
- ReviewData reviewData = cached.get(task);
- if (reviewData == null) {
- reviewData = loadFromDiskAddCache(task);
- }
- if (reviewData == null) {
- reviewData = loadFromTask(task);
- }
- return reviewData;
- }
-
- private ReviewData loadFromTask(ITask task) {
- try {
- List<Review> reviews = ReviewsUtil.getReviewAttachmentFromTask(
- taskDataManager, repositoryModel, task);
- storeTask(task, reviews.get(reviews.size() - 1));
-
- return getReviewData(task);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private ReviewData loadFromDiskAddCache(ITask task) {
- List<Review> reviews = store.loadReviewData(task.getRepositoryUrl(),
- task.getTaskId());
- if (reviews.size() > 0) {
- Review review = reviews.get(0);
- storeTask(task, review);
- return getReviewData(task);
- }
- return null;
- }
-
- public void storeTask(ITask task, Review review) {
- final ReviewData reviewData = new ReviewData(task, review);
- review.eAdapters().add(new AdapterImpl() {
- public void notifyChanged(Notification notification) {
- System.err.println("notification "+notification);
- reviewData.setDirty(true);
- }
-
- });
- cached.put(task, reviewData);
- store.storeReviewData(task.getRepositoryUrl(), task.getTaskId(),
- review, "review");
- }
-
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java
deleted file mode 100644
index f24ad5a6..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package org.eclipse.mylyn.reviews.core;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import org.eclipse.emf.common.util.URI;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-
-public class ReviewDataStore {
-
- private String storeRootDir;
-
- public ReviewDataStore(String storeRootDir) {
- this.storeRootDir = storeRootDir;
- }
-
- public void storeReviewData(String repositoryUrl, String taskId,
- Review review, String id) {
- try {
-
- File file = getFile(repositoryUrl, taskId);
- createDirectoriesIfNecessary(file);
- if (!file.exists()) {
- file.createNewFile();
- ZipOutputStream outputStream = new ZipOutputStream(
- new FileOutputStream(file));
- ResourceSet resourceSet = new ResourceSetImpl();
-
- Resource resource = resourceSet.createResource(URI
- .createFileURI("")); //$NON-NLS-1$
-
- resource.getContents().add(review);
- resource.getContents().add(review.getScope().get(0));
- if (review.getResult() != null)
- resource.getContents().add(review.getResult());
-
- outputStream.putNextEntry(new ZipEntry(id));
- resource.save(outputStream, null);
- outputStream.closeEntry();
- outputStream.close();
- } else {
- // TODO append
-
- }
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
-
- private void createDirectoriesIfNecessary(File file) {
- File parent = file.getParentFile();
- if(!parent.exists()) {
- parent.mkdirs();
- }
- }
-
- public List<Review> loadReviewData(String repositoryUrl, String taskId) {
- List<Review> reviews = new ArrayList<Review>();
- try {
-
- File file = getFile(repositoryUrl, taskId);
- if(!file.exists()) {
- return reviews;
- }
- ZipInputStream inputStream = new ZipInputStream(
- new FileInputStream(file));
- inputStream.getNextEntry();
- ResourceSet resourceSet = new ResourceSetImpl();
- resourceSet.getPackageRegistry().put(ReviewPackage.eNS_URI,
- ReviewPackage.eINSTANCE);
- Resource resource = resourceSet.createResource(URI.createURI(""));
- resource.load(inputStream, null);
- for (EObject item : resource.getContents()) {
- if (item instanceof Review) {
- Review review = (Review) item;
- reviews.add(review);
- }
- }
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- return reviews;
- }
-
- private File getFile(String repositoryUrl, String taskId) {
- File path = new File(storeRootDir + File.separator + "reviews"
- + File.separator + URLEncoder.encode(repositoryUrl)
- + File.separator);
- return new File(path, taskId);
- }
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewSubTask.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewSubTask.java
deleted file mode 100644
index db2ba150..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewSubTask.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.core;
-
-import java.util.Date;
-
-import org.eclipse.mylyn.reviews.core.model.review.Rating;
-import org.eclipse.mylyn.tasks.core.ITask;
-
-/**
- * @author Kilian Matt
- */
-public class ReviewSubTask {
-
- private String comment;
- private ITask task;
- private Date creationDate;
-
- public ReviewSubTask(String patchFile, Date creationDate, String author,
- String reviewer, Rating result, String comment, ITask task) {
- super();
- this.patchFile = patchFile;
- this.creationDate = new Date(creationDate.getTime());
- this.author = author;
- this.reviewer = reviewer;
- this.result = result;
- this.comment = comment;
- this.task = task;
- }
-
- private String patchFile;
- private String author;
- private String reviewer;
- private Rating result;
-
- public String getPatchFile() {
- return patchFile;
- }
-
- public Date getCreationDate() {
- return creationDate;
- }
-
- public String getPatchDescription() {
- return String.format("%s %s", patchFile, creationDate);
- }
-
- public String getAuthor() {
- return author;
- }
-
- public String getReviewer() {
- return reviewer;
- }
-
- public Rating getResult() {
- return result;
- }
-
- public String getComment() {
- return comment;
- }
-
- public ITask getTask() {
- return task;
- }
-
- @Override
- public String toString() {
- return "Review Subtask " + patchFile + " by " + author + " revd by "
- + reviewer + " rated as " + result;
- }
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java
deleted file mode 100644
index 2497d432..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.core;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.zip.ZipInputStream;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.emf.common.util.EList;
-import org.eclipse.emf.common.util.URI;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
-import org.eclipse.mylyn.internal.tasks.core.RepositoryModel;
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.Rating;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
-import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
-import org.eclipse.mylyn.tasks.core.IRepositoryModel;
-import org.eclipse.mylyn.tasks.core.ITask;
-import org.eclipse.mylyn.tasks.core.ITaskAttachment;
-import org.eclipse.mylyn.tasks.core.ITaskContainer;
-import org.eclipse.mylyn.tasks.core.data.ITaskDataManager;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.core.data.TaskData;
-
-/**
- * @author Kilian Matt
- */
-public class ReviewsUtil {
-
- public static List<ReviewSubTask> getReviewSubTasksFor(
- ITaskContainer taskContainer, ITaskDataManager taskDataManager,
- IRepositoryModel repositoryModel, IProgressMonitor monitor) {
- List<ReviewSubTask> resultList = new ArrayList<ReviewSubTask>();
- try {
- for (ITask subTask : taskContainer.getChildren()) {
- if (!ReviewsUtil.hasReviewMarker(subTask)) {
- TaskData taskData = taskDataManager.getTaskData(subTask);
- if (getReviewAttachments(repositoryModel, taskData).size() > 0) {
- ReviewsUtil.markAsReview(subTask);
- }
- }
-
- if (ReviewsUtil.isMarkedAsReview(subTask)) {//.getSummary().startsWith("Review")) { //$NON-NLS-1$
- // change to review data manager
- for (Review review : getReviewAttachmentFromTask(
- taskDataManager, repositoryModel, subTask)) {
- // TODO change to latest etc
- ReviewResult result = review.getResult();
- if (result == null) {
- result = ReviewFactory.eINSTANCE
- .createReviewResult();
- result.setRating(Rating.NONE);
- result.setText("");
- }
- resultList.add(new ReviewSubTask(getPatchFile(review
- .getScope()), getPatchCreationDate(review
- .getScope()),
- getAuthorString(review.getScope()), subTask
- .getOwner(), result.getRating(), result
- .getText(), subTask));
-
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return resultList;
-
- }
-
- private static String getPatchFile(EList<ScopeItem> scope) {
- if (scope.size() == 1 && scope.get(0) instanceof Patch) {
- return ((Patch) scope.get(0)).getFileName();
- } else {
- return "";
- }
- }
-
- private static Date getPatchCreationDate(EList<ScopeItem> scope) {
- if (scope.size() == 1 && scope.get(0) instanceof Patch) {
- return ((Patch) scope.get(0)).getCreationDate();
- } else {
- return null;
- }
- }
-
- private static String getAuthorString(EList<ScopeItem> scope) {
- if (scope.size() == 0) {
- return "none";
- } else if (scope.size() == 1) {
- return scope.get(0).getAuthor();
- } else if (scope.size() < 3) {
- StringBuilder sb = new StringBuilder();
- for (ScopeItem item : scope) {
- sb.append(item.getAuthor());
- sb.append(", ");
- }
- return sb.substring(0, sb.length() - 2);
- } else {
- return "Multiple Authors";
- }
- }
-
- static List<Review> parseAttachments(TaskAttribute attribute,
- IProgressMonitor monitor) {
- List<Review> reviewList = new ArrayList<Review>();
- try {
- URL url = new URL(attribute.getMappedAttribute(
- TaskAttribute.ATTACHMENT_URL).getValue());
-
- ZipInputStream stream = new ZipInputStream(url.openStream());
- while (!stream.getNextEntry().getName()
- .equals(ReviewConstants.REVIEW_DATA_FILE)) {
- }
-
- ResourceSet resourceSet = new ResourceSetImpl();
- resourceSet.getPackageRegistry().put(ReviewPackage.eNS_URI,
- ReviewPackage.eINSTANCE);
- Resource resource = resourceSet.createResource(URI.createURI(""));
- resource.load(stream, null);
- for (EObject item : resource.getContents()) {
- if (item instanceof Review) {
- Review review = (Review) item;
- reviewList.add(review);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return reviewList;
- }
-
- public static List<Review> getReviewAttachmentFromTask(
- ITaskDataManager taskDataManager, IRepositoryModel repositoryModel,
- ITask task) throws CoreException {
-
- List<Review> reviews = new ArrayList<Review>();
- TaskData taskData = taskDataManager.getTaskData(task);
- if (taskData != null) {
- List<TaskAttribute> attributesByType = taskData
- .getAttributeMapper().getAttributesByType(taskData,
- TaskAttribute.TYPE_ATTACHMENT);
- ITaskAttachment lastReview = null;
-
- for (TaskAttribute attribute : attributesByType) {
- // TODO move RepositoryModel.createTaskAttachment to interface?
- ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel)
- .createTaskAttachment(attribute);
- if (taskAttachment != null
- && taskAttachment.getFileName().equals(
- ReviewConstants.REVIEW_DATA_CONTAINER)) {
-
- if (lastReview == null
- || lastReview.getCreationDate().before(
- taskAttachment.getCreationDate())) {
- lastReview = taskAttachment;
- }
- }
-
- }
-
- if (lastReview != null) {
- reviews.addAll(parseAttachments(lastReview.getTaskAttribute(),
- new NullProgressMonitor()));
- }
-
- }
- return reviews;
- }
-
- public static List<TaskAttribute> getReviewAttachments(
- IRepositoryModel repositoryModel, TaskData taskData) {
-
- List<TaskAttribute> matchingAttributes = new ArrayList<TaskAttribute>();
- List<TaskAttribute> attributesByType = taskData.getAttributeMapper()
- .getAttributesByType(taskData, TaskAttribute.TYPE_ATTACHMENT);
- for (TaskAttribute attribute : attributesByType) {
- // TODO move RepositoryModel.createTaskAttachment to interface?
- ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel)
- .createTaskAttachment(attribute);
- if (taskAttachment != null
- && taskAttachment.getFileName().equals(
- ReviewConstants.REVIEW_DATA_CONTAINER)) {
- matchingAttributes.add(attribute);
- }
- }
- return matchingAttributes;
- }
-
- private static List<ITargetPathStrategy> strategies;
- static {
- strategies = new ArrayList<ITargetPathStrategy>();
- strategies.add(new SimplePathFindingStrategy());
- strategies.add(new GitPatchPathFindingStrategy());
- }
-
- public static List<? extends ITargetPathStrategy> getPathFindingStrategies() {
- return strategies;
- }
-
- public static boolean isMarkedAsReview(ITask task) {
- boolean isReview = Boolean.parseBoolean(task
- .getAttribute(ReviewConstants.ATTR_REVIEW_FLAG));
- return isReview;
- }
-
- public static void markAsReview(ITask task) {
- task.setAttribute(ReviewConstants.ATTR_REVIEW_FLAG,
- Boolean.TRUE.toString());
- }
-
- public static boolean hasReviewMarker(ITask task) {
- return task.getAttribute(ReviewConstants.ATTR_REVIEW_FLAG) != null;
- }
-
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Patch.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Patch.java
deleted file mode 100644
index 7521cb9f..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Patch.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review;
-
-import java.util.Date;
-
-import org.eclipse.compare.patch.IFilePatch2;
-
-import org.eclipse.emf.common.util.EList;
-
-/**
- * <!-- begin-user-doc -->
- * A representation of the model object '<em><b>Patch</b></em>'.
- * <!-- end-user-doc -->
- *
- * <p>
- * The following features are supported:
- * <ul>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getContents <em>Contents</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getCreationDate <em>Creation Date</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getFileName <em>File Name</em>}</li>
- * </ul>
- * </p>
- *
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getPatch()
- * @model
- * @generated
- */
-public interface Patch extends ScopeItem {
- /**
- * Returns the value of the '<em><b>Contents</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>Contents</em>' attribute isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>Contents</em>' attribute.
- * @see #setContents(String)
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getPatch_Contents()
- * @model
- * @generated
- */
- String getContents();
-
- /**
- * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getContents <em>Contents</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param value the new value of the '<em>Contents</em>' attribute.
- * @see #getContents()
- * @generated
- */
- void setContents(String value);
-
- /**
- * Returns the value of the '<em><b>Creation Date</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>Creation Date</em>' attribute isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>Creation Date</em>' attribute.
- * @see #setCreationDate(Date)
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getPatch_CreationDate()
- * @model
- * @generated
- */
- Date getCreationDate();
-
- /**
- * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getCreationDate <em>Creation Date</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param value the new value of the '<em>Creation Date</em>' attribute.
- * @see #getCreationDate()
- * @generated
- */
- void setCreationDate(Date value);
-
- /**
- * Returns the value of the '<em><b>File Name</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>File Name</em>' attribute isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>File Name</em>' attribute.
- * @see #setFileName(String)
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getPatch_FileName()
- * @model
- * @generated
- */
- String getFileName();
-
- /**
- * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getFileName <em>File Name</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param value the new value of the '<em>File Name</em>' attribute.
- * @see #getFileName()
- * @generated
- */
- void setFileName(String value);
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @model dataType="org.eclipse.mylyn.reviews.core.model.review.IFilePatch2"
- * @generated
- */
- EList<IFilePatch2> parse();
-
-} // Patch
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Rating.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Rating.java
deleted file mode 100644
index c4a04335..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Rating.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.emf.common.util.Enumerator;
-
-/**
- * <!-- begin-user-doc -->
- * A representation of the literals of the enumeration '<em><b>Rating</b></em>',
- * and utility methods for working with them.
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getRating()
- * @model
- * @generated
- */
-public enum Rating implements Enumerator {
- /**
- * The '<em><b>NONE</b></em>' literal object.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #NONE_VALUE
- * @generated
- * @ordered
- */
- NONE(0, "NONE", "NONE"),
-
- /**
- * The '<em><b>PASSED</b></em>' literal object.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #PASSED_VALUE
- * @generated
- * @ordered
- */
- PASSED(0, "PASSED", "PASSED"),
-
- /**
- * The '<em><b>WARNING</b></em>' literal object.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #WARNING_VALUE
- * @generated
- * @ordered
- */
- WARNING(0, "WARNING", "WARNING"),
-
- /**
- * The '<em><b>FAILED</b></em>' literal object.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #FAILED_VALUE
- * @generated
- * @ordered
- */
- FAILED(0, "FAILED", "FAILED");
-
- /**
- * The '<em><b>NONE</b></em>' literal value.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of '<em><b>NONE</b></em>' literal object isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @see #NONE
- * @model
- * @generated
- * @ordered
- */
- public static final int NONE_VALUE = 0;
-
- /**
- * The '<em><b>PASSED</b></em>' literal value.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of '<em><b>PASSED</b></em>' literal object isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @see #PASSED
- * @model
- * @generated
- * @ordered
- */
- public static final int PASSED_VALUE = 0;
-
- /**
- * The '<em><b>WARNING</b></em>' literal value.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of '<em><b>WARNING</b></em>' literal object isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @see #WARNING
- * @model
- * @generated
- * @ordered
- */
- public static final int WARNING_VALUE = 0;
-
- /**
- * The '<em><b>FAILED</b></em>' literal value.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of '<em><b>FAILED</b></em>' literal object isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @see #FAILED
- * @model
- * @generated
- * @ordered
- */
- public static final int FAILED_VALUE = 0;
-
- /**
- * An array of all the '<em><b>Rating</b></em>' enumerators.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private static final Rating[] VALUES_ARRAY =
- new Rating[] {
- NONE,
- PASSED,
- WARNING,
- FAILED,
- };
-
- /**
- * A public read-only list of all the '<em><b>Rating</b></em>' enumerators.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public static final List<Rating> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
-
- /**
- * Returns the '<em><b>Rating</b></em>' literal with the specified literal value.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public static Rating get(String literal) {
- for (int i = 0; i < VALUES_ARRAY.length; ++i) {
- Rating result = VALUES_ARRAY[i];
- if (result.toString().equals(literal)) {
- return result;
- }
- }
- return null;
- }
-
- /**
- * Returns the '<em><b>Rating</b></em>' literal with the specified name.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public static Rating getByName(String name) {
- for (int i = 0; i < VALUES_ARRAY.length; ++i) {
- Rating result = VALUES_ARRAY[i];
- if (result.getName().equals(name)) {
- return result;
- }
- }
- return null;
- }
-
- /**
- * Returns the '<em><b>Rating</b></em>' literal with the specified integer value.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public static Rating get(int value) {
- switch (value) {
- case NONE_VALUE: return NONE;
- }
- return null;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private final int value;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private final String name;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private final String literal;
-
- /**
- * Only this class can construct instances.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private Rating(int value, String name, String literal) {
- this.value = value;
- this.name = name;
- this.literal = literal;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public int getValue() {
- return value;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public String getName() {
- return name;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public String getLiteral() {
- return literal;
- }
-
- /**
- * Returns the literal value of the enumerator, which is its string representation.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public String toString() {
- return literal;
- }
-
-} //Rating
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java
deleted file mode 100644
index 5d3bf277..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/Review.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review;
-
-import org.eclipse.emf.common.util.EList;
-import org.eclipse.emf.ecore.EObject;
-
-/**
- * <!-- begin-user-doc -->
- * A representation of the model object '<em><b>Review</b></em>'.
- * <!-- end-user-doc -->
- *
- * <p>
- * The following features are supported:
- * <ul>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Review#getResult <em>Result</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.Review#getScope <em>Scope</em>}</li>
- * </ul>
- * </p>
- *
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReview()
- * @model
- * @generated
- */
-public interface Review extends EObject {
- /**
- * Returns the value of the '<em><b>Result</b></em>' reference.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>Result</em>' reference isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>Result</em>' reference.
- * @see #setResult(ReviewResult)
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReview_Result()
- * @model
- * @generated
- */
- ReviewResult getResult();
-
- /**
- * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.Review#getResult <em>Result</em>}' reference.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param value the new value of the '<em>Result</em>' reference.
- * @see #getResult()
- * @generated
- */
- void setResult(ReviewResult value);
-
- /**
- * Returns the value of the '<em><b>Scope</b></em>' reference list.
- * The list contents are of type {@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem}.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>Scope</em>' reference list isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>Scope</em>' reference list.
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReview_Scope()
- * @model
- * @generated
- */
- EList<ScopeItem> getScope();
-
-} // Review
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewFactory.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewFactory.java
deleted file mode 100644
index 288649cd..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewFactory.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review;
-
-import org.eclipse.emf.ecore.EFactory;
-
-/**
- * <!-- begin-user-doc -->
- * The <b>Factory</b> for the model.
- * It provides a create method for each non-abstract class of the model.
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage
- * @generated
- */
-public interface ReviewFactory extends EFactory {
- /**
- * The singleton instance of the factory.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- ReviewFactory eINSTANCE = org.eclipse.mylyn.reviews.core.model.review.impl.ReviewFactoryImpl.init();
-
- /**
- * Returns a new object of class '<em>Review</em>'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return a new object of class '<em>Review</em>'.
- * @generated
- */
- Review createReview();
-
- /**
- * Returns a new object of class '<em>Result</em>'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return a new object of class '<em>Result</em>'.
- * @generated
- */
- ReviewResult createReviewResult();
-
- /**
- * Returns a new object of class '<em>Patch</em>'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return a new object of class '<em>Patch</em>'.
- * @generated
- */
- Patch createPatch();
-
- /**
- * Returns a new object of class '<em>Scope Item</em>'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return a new object of class '<em>Scope Item</em>'.
- * @generated
- */
- ScopeItem createScopeItem();
-
- /**
- * Returns the package supported by this factory.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the package supported by this factory.
- * @generated
- */
- ReviewPackage getReviewPackage();
-
-} //ReviewFactory
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewPackage.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewPackage.java
deleted file mode 100644
index 20ed8ed5..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewPackage.java
+++ /dev/null
@@ -1,602 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review;
-
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EDataType;
-import org.eclipse.emf.ecore.EEnum;
-import org.eclipse.emf.ecore.EPackage;
-import org.eclipse.emf.ecore.EReference;
-
-/**
- * <!-- begin-user-doc -->
- * The <b>Package</b> for the model.
- * It contains accessors for the meta objects to represent
- * <ul>
- * <li>each class,</li>
- * <li>each feature of each class,</li>
- * <li>each enum,</li>
- * <li>and each data type</li>
- * </ul>
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewFactory
- * @model kind="package"
- * @generated
- */
-public interface ReviewPackage extends EPackage {
- /**
- * The package name.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- String eNAME = "review";
-
- /**
- * The package namespace URI.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- String eNS_URI = "org.eclipse.mylyn.reviews";
-
- /**
- * The package namespace name.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- String eNS_PREFIX = "";
-
- /**
- * The singleton instance of the package.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- ReviewPackage eINSTANCE = org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl.init();
-
- /**
- * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl <em>Review</em>}' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getReview()
- * @generated
- */
- int REVIEW = 0;
-
- /**
- * The feature id for the '<em><b>Result</b></em>' reference.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int REVIEW__RESULT = 0;
-
- /**
- * The feature id for the '<em><b>Scope</b></em>' reference list.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int REVIEW__SCOPE = 1;
-
- /**
- * The number of structural features of the '<em>Review</em>' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int REVIEW_FEATURE_COUNT = 2;
-
- /**
- * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl <em>Result</em>}' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getReviewResult()
- * @generated
- */
- int REVIEW_RESULT = 1;
-
- /**
- * The feature id for the '<em><b>Text</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int REVIEW_RESULT__TEXT = 0;
-
- /**
- * The feature id for the '<em><b>Rating</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int REVIEW_RESULT__RATING = 1;
-
- /**
- * The feature id for the '<em><b>Reviewer</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int REVIEW_RESULT__REVIEWER = 2;
-
- /**
- * The number of structural features of the '<em>Result</em>' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int REVIEW_RESULT_FEATURE_COUNT = 3;
-
- /**
- * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl <em>Scope Item</em>}' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getScopeItem()
- * @generated
- */
- int SCOPE_ITEM = 3;
-
- /**
- * The feature id for the '<em><b>Author</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int SCOPE_ITEM__AUTHOR = 0;
-
- /**
- * The number of structural features of the '<em>Scope Item</em>' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int SCOPE_ITEM_FEATURE_COUNT = 1;
-
- /**
- * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl <em>Patch</em>}' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getPatch()
- * @generated
- */
- int PATCH = 2;
-
- /**
- * The feature id for the '<em><b>Author</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int PATCH__AUTHOR = SCOPE_ITEM__AUTHOR;
-
- /**
- * The feature id for the '<em><b>Contents</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int PATCH__CONTENTS = SCOPE_ITEM_FEATURE_COUNT + 0;
-
- /**
- * The feature id for the '<em><b>Creation Date</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int PATCH__CREATION_DATE = SCOPE_ITEM_FEATURE_COUNT + 1;
-
- /**
- * The feature id for the '<em><b>File Name</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int PATCH__FILE_NAME = SCOPE_ITEM_FEATURE_COUNT + 2;
-
- /**
- * The number of structural features of the '<em>Patch</em>' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- * @ordered
- */
- int PATCH_FEATURE_COUNT = SCOPE_ITEM_FEATURE_COUNT + 3;
-
- /**
- * The meta object id for the '{@link org.eclipse.mylyn.reviews.core.model.review.Rating <em>Rating</em>}' enum.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.Rating
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getRating()
- * @generated
- */
- int RATING = 4;
-
- /**
- * The meta object id for the '<em>IFile Patch2</em>' data type.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.compare.patch.IFilePatch2
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getIFilePatch2()
- * @generated
- */
- int IFILE_PATCH2 = 5;
-
- /**
- * The meta object id for the '<em>IProgress Monitor</em>' data type.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.core.runtime.IProgressMonitor
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getIProgressMonitor()
- * @generated
- */
- int IPROGRESS_MONITOR = 6;
-
-
- /**
- * Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.review.Review <em>Review</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for class '<em>Review</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.Review
- * @generated
- */
- EClass getReview();
-
- /**
- * Returns the meta object for the reference '{@link org.eclipse.mylyn.reviews.core.model.review.Review#getResult <em>Result</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the reference '<em>Result</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.Review#getResult()
- * @see #getReview()
- * @generated
- */
- EReference getReview_Result();
-
- /**
- * Returns the meta object for the reference list '{@link org.eclipse.mylyn.reviews.core.model.review.Review#getScope <em>Scope</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the reference list '<em>Scope</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.Review#getScope()
- * @see #getReview()
- * @generated
- */
- EReference getReview_Scope();
-
- /**
- * Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult <em>Result</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for class '<em>Result</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult
- * @generated
- */
- EClass getReviewResult();
-
- /**
- * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getText <em>Text</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the attribute '<em>Text</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getText()
- * @see #getReviewResult()
- * @generated
- */
- EAttribute getReviewResult_Text();
-
- /**
- * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getRating <em>Rating</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the attribute '<em>Rating</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getRating()
- * @see #getReviewResult()
- * @generated
- */
- EAttribute getReviewResult_Rating();
-
- /**
- * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getReviewer <em>Reviewer</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the attribute '<em>Reviewer</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getReviewer()
- * @see #getReviewResult()
- * @generated
- */
- EAttribute getReviewResult_Reviewer();
-
- /**
- * Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.review.Patch <em>Patch</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for class '<em>Patch</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.Patch
- * @generated
- */
- EClass getPatch();
-
- /**
- * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getContents <em>Contents</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the attribute '<em>Contents</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.Patch#getContents()
- * @see #getPatch()
- * @generated
- */
- EAttribute getPatch_Contents();
-
- /**
- * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getCreationDate <em>Creation Date</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the attribute '<em>Creation Date</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.Patch#getCreationDate()
- * @see #getPatch()
- * @generated
- */
- EAttribute getPatch_CreationDate();
-
- /**
- * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.Patch#getFileName <em>File Name</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the attribute '<em>File Name</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.Patch#getFileName()
- * @see #getPatch()
- * @generated
- */
- EAttribute getPatch_FileName();
-
- /**
- * Returns the meta object for class '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem <em>Scope Item</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for class '<em>Scope Item</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.ScopeItem
- * @generated
- */
- EClass getScopeItem();
-
- /**
- * Returns the meta object for the attribute '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem#getAuthor <em>Author</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for the attribute '<em>Author</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.ScopeItem#getAuthor()
- * @see #getScopeItem()
- * @generated
- */
- EAttribute getScopeItem_Author();
-
- /**
- * Returns the meta object for enum '{@link org.eclipse.mylyn.reviews.core.model.review.Rating <em>Rating</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for enum '<em>Rating</em>'.
- * @see org.eclipse.mylyn.reviews.core.model.review.Rating
- * @generated
- */
- EEnum getRating();
-
- /**
- * Returns the meta object for data type '{@link org.eclipse.compare.patch.IFilePatch2 <em>IFile Patch2</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for data type '<em>IFile Patch2</em>'.
- * @see org.eclipse.compare.patch.IFilePatch2
- * @model instanceClass="org.eclipse.compare.patch.IFilePatch2"
- * @generated
- */
- EDataType getIFilePatch2();
-
- /**
- * Returns the meta object for data type '{@link org.eclipse.core.runtime.IProgressMonitor <em>IProgress Monitor</em>}'.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the meta object for data type '<em>IProgress Monitor</em>'.
- * @see org.eclipse.core.runtime.IProgressMonitor
- * @model instanceClass="org.eclipse.core.runtime.IProgressMonitor"
- * @generated
- */
- EDataType getIProgressMonitor();
-
- /**
- * Returns the factory that creates the instances of the model.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @return the factory that creates the instances of the model.
- * @generated
- */
- ReviewFactory getReviewFactory();
-
- /**
- * <!-- begin-user-doc -->
- * Defines literals for the meta objects that represent
- * <ul>
- * <li>each class,</li>
- * <li>each feature of each class,</li>
- * <li>each enum,</li>
- * <li>and each data type</li>
- * </ul>
- * <!-- end-user-doc -->
- * @generated
- */
- interface Literals {
- /**
- * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl <em>Review</em>}' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getReview()
- * @generated
- */
- EClass REVIEW = eINSTANCE.getReview();
-
- /**
- * The meta object literal for the '<em><b>Result</b></em>' reference feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EReference REVIEW__RESULT = eINSTANCE.getReview_Result();
-
- /**
- * The meta object literal for the '<em><b>Scope</b></em>' reference list feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EReference REVIEW__SCOPE = eINSTANCE.getReview_Scope();
-
- /**
- * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl <em>Result</em>}' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getReviewResult()
- * @generated
- */
- EClass REVIEW_RESULT = eINSTANCE.getReviewResult();
-
- /**
- * The meta object literal for the '<em><b>Text</b></em>' attribute feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EAttribute REVIEW_RESULT__TEXT = eINSTANCE.getReviewResult_Text();
-
- /**
- * The meta object literal for the '<em><b>Rating</b></em>' attribute feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EAttribute REVIEW_RESULT__RATING = eINSTANCE.getReviewResult_Rating();
-
- /**
- * The meta object literal for the '<em><b>Reviewer</b></em>' attribute feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EAttribute REVIEW_RESULT__REVIEWER = eINSTANCE.getReviewResult_Reviewer();
-
- /**
- * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl <em>Patch</em>}' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getPatch()
- * @generated
- */
- EClass PATCH = eINSTANCE.getPatch();
-
- /**
- * The meta object literal for the '<em><b>Contents</b></em>' attribute feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EAttribute PATCH__CONTENTS = eINSTANCE.getPatch_Contents();
-
- /**
- * The meta object literal for the '<em><b>Creation Date</b></em>' attribute feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EAttribute PATCH__CREATION_DATE = eINSTANCE.getPatch_CreationDate();
-
- /**
- * The meta object literal for the '<em><b>File Name</b></em>' attribute feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EAttribute PATCH__FILE_NAME = eINSTANCE.getPatch_FileName();
-
- /**
- * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl <em>Scope Item</em>}' class.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getScopeItem()
- * @generated
- */
- EClass SCOPE_ITEM = eINSTANCE.getScopeItem();
-
- /**
- * The meta object literal for the '<em><b>Author</b></em>' attribute feature.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- EAttribute SCOPE_ITEM__AUTHOR = eINSTANCE.getScopeItem_Author();
-
- /**
- * The meta object literal for the '{@link org.eclipse.mylyn.reviews.core.model.review.Rating <em>Rating</em>}' enum.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.Rating
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getRating()
- * @generated
- */
- EEnum RATING = eINSTANCE.getRating();
-
- /**
- * The meta object literal for the '<em>IFile Patch2</em>' data type.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.compare.patch.IFilePatch2
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getIFilePatch2()
- * @generated
- */
- EDataType IFILE_PATCH2 = eINSTANCE.getIFilePatch2();
-
- /**
- * The meta object literal for the '<em>IProgress Monitor</em>' data type.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.core.runtime.IProgressMonitor
- * @see org.eclipse.mylyn.reviews.core.model.review.impl.ReviewPackageImpl#getIProgressMonitor()
- * @generated
- */
- EDataType IPROGRESS_MONITOR = eINSTANCE.getIProgressMonitor();
-
- }
-
-} //ReviewPackage
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java
deleted file mode 100644
index 59c089de..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ReviewResult.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review;
-
-import org.eclipse.emf.ecore.EObject;
-
-/**
- * <!-- begin-user-doc -->
- * A representation of the model object '<em><b>Result</b></em>'.
- * <!-- end-user-doc -->
- *
- * <p>
- * The following features are supported:
- * <ul>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getText <em>Text</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getRating <em>Rating</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getReviewer <em>Reviewer</em>}</li>
- * </ul>
- * </p>
- *
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult()
- * @model
- * @generated
- */
-public interface ReviewResult extends EObject {
- /**
- * Returns the value of the '<em><b>Text</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>Text</em>' attribute isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>Text</em>' attribute.
- * @see #setText(String)
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult_Text()
- * @model
- * @generated
- */
- String getText();
-
- /**
- * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getText <em>Text</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param value the new value of the '<em>Text</em>' attribute.
- * @see #getText()
- * @generated
- */
- void setText(String value);
-
- /**
- * Returns the value of the '<em><b>Rating</b></em>' attribute.
- * The literals are from the enumeration {@link org.eclipse.mylyn.reviews.core.model.review.Rating}.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>Rating</em>' attribute isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>Rating</em>' attribute.
- * @see org.eclipse.mylyn.reviews.core.model.review.Rating
- * @see #setRating(Rating)
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult_Rating()
- * @model
- * @generated
- */
- Rating getRating();
-
- /**
- * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getRating <em>Rating</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param value the new value of the '<em>Rating</em>' attribute.
- * @see org.eclipse.mylyn.reviews.core.model.review.Rating
- * @see #getRating()
- * @generated
- */
- void setRating(Rating value);
-
- /**
- * Returns the value of the '<em><b>Reviewer</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>Reviewer</em>' attribute isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>Reviewer</em>' attribute.
- * @see #setReviewer(String)
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getReviewResult_Reviewer()
- * @model
- * @generated
- */
- String getReviewer();
-
- /**
- * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult#getReviewer <em>Reviewer</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param value the new value of the '<em>Reviewer</em>' attribute.
- * @see #getReviewer()
- * @generated
- */
- void setReviewer(String value);
-
-} // ReviewResult
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java
deleted file mode 100644
index 252a01a1..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/ScopeItem.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review;
-
-import org.eclipse.emf.ecore.EObject;
-
-/**
- * <!-- begin-user-doc -->
- * A representation of the model object '<em><b>Scope Item</b></em>'.
- * <!-- end-user-doc -->
- *
- * <p>
- * The following features are supported:
- * <ul>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem#getAuthor <em>Author</em>}</li>
- * </ul>
- * </p>
- *
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getScopeItem()
- * @model
- * @generated
- */
-public interface ScopeItem extends EObject {
- /**
- * Returns the value of the '<em><b>Author</b></em>' attribute.
- * <!-- begin-user-doc -->
- * <p>
- * If the meaning of the '<em>Author</em>' attribute isn't clear,
- * there really should be more of a description here...
- * </p>
- * <!-- end-user-doc -->
- * @return the value of the '<em>Author</em>' attribute.
- * @see #setAuthor(String)
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#getScopeItem_Author()
- * @model
- * @generated
- */
- String getAuthor();
-
- /**
- * Sets the value of the '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem#getAuthor <em>Author</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param value the new value of the '<em>Author</em>' attribute.
- * @see #getAuthor()
- * @generated
- */
- void setAuthor(String value);
-
-} // ScopeItem
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java
deleted file mode 100644
index 15f58c54..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/PatchImpl.java
+++ /dev/null
@@ -1,299 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review.impl;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.util.Date;
-
-import org.eclipse.compare.patch.IFilePatch2;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.compare.patch.PatchParser;
-import org.eclipse.compare.patch.ReaderCreator;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.emf.common.util.BasicEList;
-import org.eclipse.emf.common.util.EList;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.impl.ENotificationImpl;
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-
-/**
- * <!-- begin-user-doc --> An implementation of the model object '
- * <em><b>Patch</b></em>'. <!-- end-user-doc -->
- * <p>
- * The following features are implemented:
- * <ul>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getContents <em>Contents</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getCreationDate <em>Creation Date</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.PatchImpl#getFileName <em>File Name</em>}</li>
- * </ul>
- * </p>
- *
- * @generated
- */
-public class PatchImpl extends ScopeItemImpl implements Patch {
- /**
- * The default value of the '{@link #getContents() <em>Contents</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getContents()
- * @generated
- * @ordered
- */
- protected static final String CONTENTS_EDEFAULT = null;
- /**
- * The cached value of the '{@link #getContents() <em>Contents</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getContents()
- * @generated
- * @ordered
- */
- protected String contents = CONTENTS_EDEFAULT;
- /**
- * The default value of the '{@link #getCreationDate() <em>Creation Date</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getCreationDate()
- * @generated
- * @ordered
- */
- protected static final Date CREATION_DATE_EDEFAULT = null;
- /**
- * The cached value of the '{@link #getCreationDate() <em>Creation Date</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getCreationDate()
- * @generated
- * @ordered
- */
- protected Date creationDate = CREATION_DATE_EDEFAULT;
- /**
- * The default value of the '{@link #getFileName() <em>File Name</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getFileName()
- * @generated
- * @ordered
- */
- protected static final String FILE_NAME_EDEFAULT = null;
- /**
- * The cached value of the '{@link #getFileName() <em>File Name</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getFileName()
- * @generated
- * @ordered
- */
- protected String fileName = FILE_NAME_EDEFAULT;
-
- /*
- * owner* <!-- begin-user-doc --> <!-- end-user-doc -->
- *
- * @generated
- */
- protected PatchImpl() {
- super();
- }
-
- /**
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- @Override
- protected EClass eStaticClass() {
- return ReviewPackage.Literals.PATCH;
- }
-
- /**
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- public String getContents() {
- return contents;
- }
-
- /**
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- public void setContents(String newContents) {
- String oldContents = contents;
- contents = newContents;
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__CONTENTS, oldContents, contents));
- }
-
- /**
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- public Date getCreationDate() {
- return creationDate;
- }
-
- /**
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- public void setCreationDate(Date newCreationDate) {
- Date oldCreationDate = creationDate;
- creationDate = newCreationDate;
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__CREATION_DATE, oldCreationDate, creationDate));
- }
-
- /**
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- public String getFileName() {
- return fileName;
- }
-
- /**
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- public void setFileName(String newFileName) {
- String oldFileName = fileName;
- fileName = newFileName;
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.PATCH__FILE_NAME, oldFileName, fileName));
- }
-
- /**
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- */
- public EList<IFilePatch2> parse() {
- try {
- IFilePatch2[] patches = PatchParser.parsePatch(new ReaderCreator() {
- @Override
- public Reader createReader() throws CoreException {
- return new InputStreamReader(new ByteArrayInputStream(
- getContents().getBytes()));
- }
- });
-
- EList<IFilePatch2> list = new BasicEList<IFilePatch2>();
-
- for (IFilePatch2 patch : patches) {
- list.add(patch);
- }
- return list;
- } catch (Exception ex) {
- // TODO
- ex.printStackTrace();
- throw new RuntimeException(ex);
- }
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public Object eGet(int featureID, boolean resolve, boolean coreType) {
- switch (featureID) {
- case ReviewPackage.PATCH__CONTENTS:
- return getContents();
- case ReviewPackage.PATCH__CREATION_DATE:
- return getCreationDate();
- case ReviewPackage.PATCH__FILE_NAME:
- return getFileName();
- }
- return super.eGet(featureID, resolve, coreType);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public void eSet(int featureID, Object newValue) {
- switch (featureID) {
- case ReviewPackage.PATCH__CONTENTS:
- setContents((String)newValue);
- return;
- case ReviewPackage.PATCH__CREATION_DATE:
- setCreationDate((Date)newValue);
- return;
- case ReviewPackage.PATCH__FILE_NAME:
- setFileName((String)newValue);
- return;
- }
- super.eSet(featureID, newValue);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public void eUnset(int featureID) {
- switch (featureID) {
- case ReviewPackage.PATCH__CONTENTS:
- setContents(CONTENTS_EDEFAULT);
- return;
- case ReviewPackage.PATCH__CREATION_DATE:
- setCreationDate(CREATION_DATE_EDEFAULT);
- return;
- case ReviewPackage.PATCH__FILE_NAME:
- setFileName(FILE_NAME_EDEFAULT);
- return;
- }
- super.eUnset(featureID);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public boolean eIsSet(int featureID) {
- switch (featureID) {
- case ReviewPackage.PATCH__CONTENTS:
- return CONTENTS_EDEFAULT == null ? contents != null : !CONTENTS_EDEFAULT.equals(contents);
- case ReviewPackage.PATCH__CREATION_DATE:
- return CREATION_DATE_EDEFAULT == null ? creationDate != null : !CREATION_DATE_EDEFAULT.equals(creationDate);
- case ReviewPackage.PATCH__FILE_NAME:
- return FILE_NAME_EDEFAULT == null ? fileName != null : !FILE_NAME_EDEFAULT.equals(fileName);
- }
- return super.eIsSet(featureID);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public String toString() {
- if (eIsProxy()) return super.toString();
-
- StringBuffer result = new StringBuffer(super.toString());
- result.append(" (contents: ");
- result.append(contents);
- result.append(", creationDate: ");
- result.append(creationDate);
- result.append(", fileName: ");
- result.append(fileName);
- result.append(')');
- return result.toString();
- }
-
-} // PatchImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java
deleted file mode 100644
index 0ef56ca2..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewFactoryImpl.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review.impl;
-
-import org.eclipse.compare.patch.IFilePatch2;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EDataType;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EPackage;
-
-import org.eclipse.emf.ecore.impl.EFactoryImpl;
-
-import org.eclipse.emf.ecore.plugin.EcorePlugin;
-
-import org.eclipse.mylyn.reviews.core.model.review.*;
-
-/**
- * <!-- begin-user-doc -->
- * An implementation of the model <b>Factory</b>.
- * <!-- end-user-doc -->
- * @generated
- */
-public class ReviewFactoryImpl extends EFactoryImpl implements ReviewFactory {
- /**
- * Creates the default factory implementation.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public static ReviewFactory init() {
- try {
- ReviewFactory theReviewFactory = (ReviewFactory)EPackage.Registry.INSTANCE.getEFactory("org.eclipse.mylyn.reviews");
- if (theReviewFactory != null) {
- return theReviewFactory;
- }
- }
- catch (Exception exception) {
- EcorePlugin.INSTANCE.log(exception);
- }
- return new ReviewFactoryImpl();
- }
-
- /**
- * Creates an instance of the factory.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public ReviewFactoryImpl() {
- super();
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public EObject create(EClass eClass) {
- switch (eClass.getClassifierID()) {
- case ReviewPackage.REVIEW: return createReview();
- case ReviewPackage.REVIEW_RESULT: return createReviewResult();
- case ReviewPackage.PATCH: return createPatch();
- case ReviewPackage.SCOPE_ITEM: return createScopeItem();
- default:
- throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
- }
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public Object createFromString(EDataType eDataType, String initialValue) {
- switch (eDataType.getClassifierID()) {
- case ReviewPackage.RATING:
- return createRatingFromString(eDataType, initialValue);
- case ReviewPackage.IFILE_PATCH2:
- return createIFilePatch2FromString(eDataType, initialValue);
- case ReviewPackage.IPROGRESS_MONITOR:
- return createIProgressMonitorFromString(eDataType, initialValue);
- default:
- throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
- }
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public String convertToString(EDataType eDataType, Object instanceValue) {
- switch (eDataType.getClassifierID()) {
- case ReviewPackage.RATING:
- return convertRatingToString(eDataType, instanceValue);
- case ReviewPackage.IFILE_PATCH2:
- return convertIFilePatch2ToString(eDataType, instanceValue);
- case ReviewPackage.IPROGRESS_MONITOR:
- return convertIProgressMonitorToString(eDataType, instanceValue);
- default:
- throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
- }
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public Review createReview() {
- ReviewImpl review = new ReviewImpl();
- return review;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public ReviewResult createReviewResult() {
- ReviewResultImpl reviewResult = new ReviewResultImpl();
- return reviewResult;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public Patch createPatch() {
- PatchImpl patch = new PatchImpl();
- return patch;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public ScopeItem createScopeItem() {
- ScopeItemImpl scopeItem = new ScopeItemImpl();
- return scopeItem;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public Rating createRatingFromString(EDataType eDataType, String initialValue) {
- Rating result = Rating.get(initialValue);
- if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
- return result;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public String convertRatingToString(EDataType eDataType, Object instanceValue) {
- return instanceValue == null ? null : instanceValue.toString();
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public IFilePatch2 createIFilePatch2FromString(EDataType eDataType, String initialValue) {
- return (IFilePatch2)super.createFromString(eDataType, initialValue);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public String convertIFilePatch2ToString(EDataType eDataType, Object instanceValue) {
- return super.convertToString(eDataType, instanceValue);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public IProgressMonitor createIProgressMonitorFromString(EDataType eDataType, String initialValue) {
- return (IProgressMonitor)super.createFromString(eDataType, initialValue);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public String convertIProgressMonitorToString(EDataType eDataType, Object instanceValue) {
- return super.convertToString(eDataType, instanceValue);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public ReviewPackage getReviewPackage() {
- return (ReviewPackage)getEPackage();
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @deprecated
- * @generated
- */
- @Deprecated
- public static ReviewPackage getPackage() {
- return ReviewPackage.eINSTANCE;
- }
-
-} //ReviewFactoryImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java
deleted file mode 100644
index 4cebc515..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewImpl.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review.impl;
-
-import java.util.Collection;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.common.util.EList;
-
-import org.eclipse.emf.ecore.EClass;
-
-import org.eclipse.emf.ecore.InternalEObject;
-import org.eclipse.emf.ecore.impl.ENotificationImpl;
-import org.eclipse.emf.ecore.impl.EObjectImpl;
-import org.eclipse.emf.ecore.util.EObjectResolvingEList;
-
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
-import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
-
-/**
- * <!-- begin-user-doc -->
- * An implementation of the model object '<em><b>Review</b></em>'.
- * <!-- end-user-doc -->
- * <p>
- * The following features are implemented:
- * <ul>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl#getResult <em>Result</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewImpl#getScope <em>Scope</em>}</li>
- * </ul>
- * </p>
- *
- * @generated
- */
-public class ReviewImpl extends EObjectImpl implements Review {
- /**
- * The cached value of the '{@link #getResult() <em>Result</em>}' reference.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getResult()
- * @generated
- * @ordered
- */
- protected ReviewResult result;
- /**
- * The cached value of the '{@link #getScope() <em>Scope</em>}' reference list.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getScope()
- * @generated
- * @ordered
- */
- protected EList<ScopeItem> scope;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- protected ReviewImpl() {
- super();
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- protected EClass eStaticClass() {
- return ReviewPackage.Literals.REVIEW;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public ReviewResult getResult() {
- if (result != null && result.eIsProxy()) {
- InternalEObject oldResult = (InternalEObject)result;
- result = (ReviewResult)eResolveProxy(oldResult);
- if (result != oldResult) {
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.RESOLVE, ReviewPackage.REVIEW__RESULT, oldResult, result));
- }
- }
- return result;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public ReviewResult basicGetResult() {
- return result;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public void setResult(ReviewResult newResult) {
- ReviewResult oldResult = result;
- result = newResult;
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW__RESULT, oldResult, result));
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @SuppressWarnings("unchecked")
- public EList<ScopeItem> getScope() {
- if (scope == null) {
- scope = new EObjectResolvingEList<ScopeItem>(ScopeItem.class, this, ReviewPackage.REVIEW__SCOPE);
- }
- return scope;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public Object eGet(int featureID, boolean resolve, boolean coreType) {
- switch (featureID) {
- case ReviewPackage.REVIEW__RESULT:
- if (resolve) return getResult();
- return basicGetResult();
- case ReviewPackage.REVIEW__SCOPE:
- return getScope();
- }
- return super.eGet(featureID, resolve, coreType);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @SuppressWarnings("unchecked")
- @Override
- public void eSet(int featureID, Object newValue) {
- switch (featureID) {
- case ReviewPackage.REVIEW__RESULT:
- setResult((ReviewResult)newValue);
- return;
- case ReviewPackage.REVIEW__SCOPE:
- getScope().clear();
- getScope().addAll((Collection<? extends ScopeItem>)newValue);
- return;
- }
- super.eSet(featureID, newValue);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public void eUnset(int featureID) {
- switch (featureID) {
- case ReviewPackage.REVIEW__RESULT:
- setResult((ReviewResult)null);
- return;
- case ReviewPackage.REVIEW__SCOPE:
- getScope().clear();
- return;
- }
- super.eUnset(featureID);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public boolean eIsSet(int featureID) {
- switch (featureID) {
- case ReviewPackage.REVIEW__RESULT:
- return result != null;
- case ReviewPackage.REVIEW__SCOPE:
- return scope != null && !scope.isEmpty();
- }
- return super.eIsSet(featureID);
- }
-
-} //ReviewImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewPackageImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewPackageImpl.java
deleted file mode 100644
index 0b2e5332..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewPackageImpl.java
+++ /dev/null
@@ -1,413 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review.impl;
-
-import org.eclipse.compare.patch.IFilePatch2;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EDataType;
-import org.eclipse.emf.ecore.EEnum;
-import org.eclipse.emf.ecore.EPackage;
-import org.eclipse.emf.ecore.EReference;
-
-import org.eclipse.emf.ecore.impl.EPackageImpl;
-
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.Rating;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
-import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
-
-/**
- * <!-- begin-user-doc -->
- * An implementation of the model <b>Package</b>.
- * <!-- end-user-doc -->
- * @generated
- */
-public class ReviewPackageImpl extends EPackageImpl implements ReviewPackage {
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private EClass reviewEClass = null;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private EClass reviewResultEClass = null;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private EClass patchEClass = null;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private EClass scopeItemEClass = null;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private EEnum ratingEEnum = null;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private EDataType iFilePatch2EDataType = null;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private EDataType iProgressMonitorEDataType = null;
-
- /**
- * Creates an instance of the model <b>Package</b>, registered with
- * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
- * package URI value.
- * <p>Note: the correct way to create the package is via the static
- * factory method {@link #init init()}, which also performs
- * initialization of the package, or returns the registered package,
- * if one already exists.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see org.eclipse.emf.ecore.EPackage.Registry
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage#eNS_URI
- * @see #init()
- * @generated
- */
- private ReviewPackageImpl() {
- super(eNS_URI, ReviewFactory.eINSTANCE);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private static boolean isInited = false;
-
- /**
- * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
- *
- * <p>This method is used to initialize {@link ReviewPackage#eINSTANCE} when that field is accessed.
- * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #eNS_URI
- * @see #createPackageContents()
- * @see #initializePackageContents()
- * @generated
- */
- public static ReviewPackage init() {
- if (isInited) return (ReviewPackage)EPackage.Registry.INSTANCE.getEPackage(ReviewPackage.eNS_URI);
-
- // Obtain or create and register package
- ReviewPackageImpl theReviewPackage = (ReviewPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof ReviewPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new ReviewPackageImpl());
-
- isInited = true;
-
- // Create package meta-data objects
- theReviewPackage.createPackageContents();
-
- // Initialize created meta-data
- theReviewPackage.initializePackageContents();
-
- // Mark meta-data to indicate it can't be changed
- theReviewPackage.freeze();
-
-
- // Update the registry and return the package
- EPackage.Registry.INSTANCE.put(ReviewPackage.eNS_URI, theReviewPackage);
- return theReviewPackage;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EClass getReview() {
- return reviewEClass;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EReference getReview_Result() {
- return (EReference)reviewEClass.getEStructuralFeatures().get(0);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EReference getReview_Scope() {
- return (EReference)reviewEClass.getEStructuralFeatures().get(1);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EClass getReviewResult() {
- return reviewResultEClass;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EAttribute getReviewResult_Text() {
- return (EAttribute)reviewResultEClass.getEStructuralFeatures().get(0);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EAttribute getReviewResult_Rating() {
- return (EAttribute)reviewResultEClass.getEStructuralFeatures().get(1);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EAttribute getReviewResult_Reviewer() {
- return (EAttribute)reviewResultEClass.getEStructuralFeatures().get(2);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EClass getPatch() {
- return patchEClass;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EAttribute getPatch_Contents() {
- return (EAttribute)patchEClass.getEStructuralFeatures().get(0);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EAttribute getPatch_CreationDate() {
- return (EAttribute)patchEClass.getEStructuralFeatures().get(1);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EAttribute getPatch_FileName() {
- return (EAttribute)patchEClass.getEStructuralFeatures().get(2);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EClass getScopeItem() {
- return scopeItemEClass;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EAttribute getScopeItem_Author() {
- return (EAttribute)scopeItemEClass.getEStructuralFeatures().get(0);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EEnum getRating() {
- return ratingEEnum;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EDataType getIFilePatch2() {
- return iFilePatch2EDataType;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public EDataType getIProgressMonitor() {
- return iProgressMonitorEDataType;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public ReviewFactory getReviewFactory() {
- return (ReviewFactory)getEFactoryInstance();
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private boolean isCreated = false;
-
- /**
- * Creates the meta-model objects for the package. This method is
- * guarded to have no affect on any invocation but its first.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public void createPackageContents() {
- if (isCreated) return;
- isCreated = true;
-
- // Create classes and their features
- reviewEClass = createEClass(REVIEW);
- createEReference(reviewEClass, REVIEW__RESULT);
- createEReference(reviewEClass, REVIEW__SCOPE);
-
- reviewResultEClass = createEClass(REVIEW_RESULT);
- createEAttribute(reviewResultEClass, REVIEW_RESULT__TEXT);
- createEAttribute(reviewResultEClass, REVIEW_RESULT__RATING);
- createEAttribute(reviewResultEClass, REVIEW_RESULT__REVIEWER);
-
- patchEClass = createEClass(PATCH);
- createEAttribute(patchEClass, PATCH__CONTENTS);
- createEAttribute(patchEClass, PATCH__CREATION_DATE);
- createEAttribute(patchEClass, PATCH__FILE_NAME);
-
- scopeItemEClass = createEClass(SCOPE_ITEM);
- createEAttribute(scopeItemEClass, SCOPE_ITEM__AUTHOR);
-
- // Create enums
- ratingEEnum = createEEnum(RATING);
-
- // Create data types
- iFilePatch2EDataType = createEDataType(IFILE_PATCH2);
- iProgressMonitorEDataType = createEDataType(IPROGRESS_MONITOR);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- private boolean isInitialized = false;
-
- /**
- * Complete the initialization of the package and its meta-model. This
- * method is guarded to have no affect on any invocation but its first.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public void initializePackageContents() {
- if (isInitialized) return;
- isInitialized = true;
-
- // Initialize package
- setName(eNAME);
- setNsPrefix(eNS_PREFIX);
- setNsURI(eNS_URI);
-
- // Create type parameters
-
- // Set bounds for type parameters
-
- // Add supertypes to classes
- patchEClass.getESuperTypes().add(this.getScopeItem());
-
- // Initialize classes and features; add operations and parameters
- initEClass(reviewEClass, Review.class, "Review", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
- initEReference(getReview_Result(), this.getReviewResult(), null, "result", null, 0, 1, Review.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
- initEReference(getReview_Scope(), this.getScopeItem(), null, "scope", null, 0, -1, Review.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
-
- initEClass(reviewResultEClass, ReviewResult.class, "ReviewResult", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
- initEAttribute(getReviewResult_Text(), ecorePackage.getEString(), "text", null, 0, 1, ReviewResult.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
- initEAttribute(getReviewResult_Rating(), this.getRating(), "rating", null, 0, 1, ReviewResult.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
- initEAttribute(getReviewResult_Reviewer(), ecorePackage.getEString(), "reviewer", null, 0, 1, ReviewResult.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
-
- initEClass(patchEClass, Patch.class, "Patch", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
- initEAttribute(getPatch_Contents(), ecorePackage.getEString(), "contents", null, 0, 1, Patch.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
- initEAttribute(getPatch_CreationDate(), ecorePackage.getEDate(), "creationDate", null, 0, 1, Patch.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
- initEAttribute(getPatch_FileName(), ecorePackage.getEString(), "fileName", null, 0, 1, Patch.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
-
- addEOperation(patchEClass, this.getIFilePatch2(), "parse", 0, -1, IS_UNIQUE, IS_ORDERED);
-
- initEClass(scopeItemEClass, ScopeItem.class, "ScopeItem", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
- initEAttribute(getScopeItem_Author(), ecorePackage.getEString(), "author", null, 0, 1, ScopeItem.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
-
- // Initialize enums and add enum literals
- initEEnum(ratingEEnum, Rating.class, "Rating");
- addEEnumLiteral(ratingEEnum, Rating.NONE);
- addEEnumLiteral(ratingEEnum, Rating.PASSED);
- addEEnumLiteral(ratingEEnum, Rating.WARNING);
- addEEnumLiteral(ratingEEnum, Rating.FAILED);
-
- // Initialize data types
- initEDataType(iFilePatch2EDataType, IFilePatch2.class, "IFilePatch2", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);
- initEDataType(iProgressMonitorEDataType, IProgressMonitor.class, "IProgressMonitor", IS_SERIALIZABLE, !IS_GENERATED_INSTANCE_CLASS);
-
- // Create resource
- createResource(eNS_URI);
- }
-
-} //ReviewPackageImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java
deleted file mode 100644
index 1619866d..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ReviewResultImpl.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review.impl;
-
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.impl.ENotificationImpl;
-import org.eclipse.emf.ecore.impl.EObjectImpl;
-import org.eclipse.mylyn.reviews.core.model.review.Rating;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
-
-/**
- * <!-- begin-user-doc -->
- * An implementation of the model object '<em><b>Result</b></em>'.
- * <!-- end-user-doc -->
- * <p>
- * The following features are implemented:
- * <ul>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl#getText <em>Text</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl#getRating <em>Rating</em>}</li>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ReviewResultImpl#getReviewer <em>Reviewer</em>}</li>
- * </ul>
- * </p>
- *
- * @generated
- */
-public class ReviewResultImpl extends EObjectImpl implements ReviewResult {
- /**
- * The default value of the '{@link #getText() <em>Text</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getText()
- * @generated
- * @ordered
- */
- protected static final String TEXT_EDEFAULT = null;
- /**
- * The cached value of the '{@link #getText() <em>Text</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getText()
- * @generated
- * @ordered
- */
- protected String text = TEXT_EDEFAULT;
- /**
- * The default value of the '{@link #getRating() <em>Rating</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getRating()
- * @generated
- * @ordered
- */
- protected static final Rating RATING_EDEFAULT = Rating.NONE;
- /**
- * The cached value of the '{@link #getRating() <em>Rating</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getRating()
- * @generated
- * @ordered
- */
- protected Rating rating = RATING_EDEFAULT;
- /**
- * The default value of the '{@link #getReviewer() <em>Reviewer</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getReviewer()
- * @generated
- * @ordered
- */
- protected static final String REVIEWER_EDEFAULT = null;
- /**
- * The cached value of the '{@link #getReviewer() <em>Reviewer</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getReviewer()
- * @generated
- * @ordered
- */
- protected String reviewer = REVIEWER_EDEFAULT;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- protected ReviewResultImpl() {
- super();
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- protected EClass eStaticClass() {
- return ReviewPackage.Literals.REVIEW_RESULT;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public String getText() {
- return text;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public void setText(String newText) {
- String oldText = text;
- text = newText;
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__TEXT, oldText, text));
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public Rating getRating() {
- return rating;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public void setRating(Rating newRating) {
- Rating oldRating = rating;
- rating = newRating == null ? RATING_EDEFAULT : newRating;
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__RATING, oldRating, rating));
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public String getReviewer() {
- return reviewer;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public void setReviewer(String newReviewer) {
- String oldReviewer = reviewer;
- reviewer = newReviewer;
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.REVIEW_RESULT__REVIEWER, oldReviewer, reviewer));
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public Object eGet(int featureID, boolean resolve, boolean coreType) {
- switch (featureID) {
- case ReviewPackage.REVIEW_RESULT__TEXT:
- return getText();
- case ReviewPackage.REVIEW_RESULT__RATING:
- return getRating();
- case ReviewPackage.REVIEW_RESULT__REVIEWER:
- return getReviewer();
- }
- return super.eGet(featureID, resolve, coreType);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public void eSet(int featureID, Object newValue) {
- switch (featureID) {
- case ReviewPackage.REVIEW_RESULT__TEXT:
- setText((String)newValue);
- return;
- case ReviewPackage.REVIEW_RESULT__RATING:
- setRating((Rating)newValue);
- return;
- case ReviewPackage.REVIEW_RESULT__REVIEWER:
- setReviewer((String)newValue);
- return;
- }
- super.eSet(featureID, newValue);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public void eUnset(int featureID) {
- switch (featureID) {
- case ReviewPackage.REVIEW_RESULT__TEXT:
- setText(TEXT_EDEFAULT);
- return;
- case ReviewPackage.REVIEW_RESULT__RATING:
- setRating(RATING_EDEFAULT);
- return;
- case ReviewPackage.REVIEW_RESULT__REVIEWER:
- setReviewer(REVIEWER_EDEFAULT);
- return;
- }
- super.eUnset(featureID);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public boolean eIsSet(int featureID) {
- switch (featureID) {
- case ReviewPackage.REVIEW_RESULT__TEXT:
- return TEXT_EDEFAULT == null ? text != null : !TEXT_EDEFAULT.equals(text);
- case ReviewPackage.REVIEW_RESULT__RATING:
- return rating != RATING_EDEFAULT;
- case ReviewPackage.REVIEW_RESULT__REVIEWER:
- return REVIEWER_EDEFAULT == null ? reviewer != null : !REVIEWER_EDEFAULT.equals(reviewer);
- }
- return super.eIsSet(featureID);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public String toString() {
- if (eIsProxy()) return super.toString();
-
- StringBuffer result = new StringBuffer(super.toString());
- result.append(" (text: ");
- result.append(text);
- result.append(", rating: ");
- result.append(rating);
- result.append(", reviewer: ");
- result.append(reviewer);
- result.append(')');
- return result.toString();
- }
-
-} //ReviewResultImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java
deleted file mode 100644
index cad5f6f7..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/impl/ScopeItemImpl.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review.impl;
-
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.impl.ENotificationImpl;
-import org.eclipse.emf.ecore.impl.EObjectImpl;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
-
-/**
- * <!-- begin-user-doc -->
- * An implementation of the model object '<em><b>Scope Item</b></em>'.
- * <!-- end-user-doc -->
- * <p>
- * The following features are implemented:
- * <ul>
- * <li>{@link org.eclipse.mylyn.reviews.core.model.review.impl.ScopeItemImpl#getAuthor <em>Author</em>}</li>
- * </ul>
- * </p>
- *
- * @generated
- */
-public class ScopeItemImpl extends EObjectImpl implements ScopeItem {
- /**
- * The default value of the '{@link #getAuthor() <em>Author</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getAuthor()
- * @generated
- * @ordered
- */
- protected static final String AUTHOR_EDEFAULT = null;
- /**
- * The cached value of the '{@link #getAuthor() <em>Author</em>}' attribute.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @see #getAuthor()
- * @generated
- * @ordered
- */
- protected String author = AUTHOR_EDEFAULT;
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- protected ScopeItemImpl() {
- super();
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- protected EClass eStaticClass() {
- return ReviewPackage.Literals.SCOPE_ITEM;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public String getAuthor() {
- return author;
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- public void setAuthor(String newAuthor) {
- String oldAuthor = author;
- author = newAuthor;
- if (eNotificationRequired())
- eNotify(new ENotificationImpl(this, Notification.SET, ReviewPackage.SCOPE_ITEM__AUTHOR, oldAuthor, author));
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public Object eGet(int featureID, boolean resolve, boolean coreType) {
- switch (featureID) {
- case ReviewPackage.SCOPE_ITEM__AUTHOR:
- return getAuthor();
- }
- return super.eGet(featureID, resolve, coreType);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public void eSet(int featureID, Object newValue) {
- switch (featureID) {
- case ReviewPackage.SCOPE_ITEM__AUTHOR:
- setAuthor((String)newValue);
- return;
- }
- super.eSet(featureID, newValue);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public void eUnset(int featureID) {
- switch (featureID) {
- case ReviewPackage.SCOPE_ITEM__AUTHOR:
- setAuthor(AUTHOR_EDEFAULT);
- return;
- }
- super.eUnset(featureID);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public boolean eIsSet(int featureID) {
- switch (featureID) {
- case ReviewPackage.SCOPE_ITEM__AUTHOR:
- return AUTHOR_EDEFAULT == null ? author != null : !AUTHOR_EDEFAULT.equals(author);
- }
- return super.eIsSet(featureID);
- }
-
- /**
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @generated
- */
- @Override
- public String toString() {
- if (eIsProxy()) return super.toString();
-
- StringBuffer result = new StringBuffer(super.toString());
- result.append(" (author: ");
- result.append(author);
- result.append(')');
- return result.toString();
- }
-
-} //ScopeItemImpl
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java
deleted file mode 100644
index 73e096eb..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewAdapterFactory.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review.util;
-
-import org.eclipse.emf.common.notify.Adapter;
-import org.eclipse.emf.common.notify.Notifier;
-import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.mylyn.reviews.core.model.review.*;
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
-import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
-
-/**
- * <!-- begin-user-doc --> The <b>Adapter Factory</b> for the model. It provides
- * an adapter <code>createXXX</code> method for each class of the model. <!--
- * end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage
- * @generated
- */
-public class ReviewAdapterFactory extends AdapterFactoryImpl {
- /**
- * The cached model package.
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- protected static ReviewPackage modelPackage;
-
- /**
- * Creates an instance of the adapter factory.
- * <!-- begin-user-doc --> <!--
- * end-user-doc -->
- * @generated
- */
- public ReviewAdapterFactory() {
- if (modelPackage == null) {
- modelPackage = ReviewPackage.eINSTANCE;
- }
- }
-
- /**
- * Returns whether this factory is applicable for the type of the object.
- * <!-- begin-user-doc --> This implementation returns <code>true</code> if
- * the object is either the model's package or is an instance object of the
- * model. <!-- end-user-doc -->
- * @return whether this factory is applicable for the type of the object.
- * @generated
- */
- @Override
- public boolean isFactoryForType(Object object) {
- if (object == modelPackage) {
- return true;
- }
- if (object instanceof EObject) {
- return ((EObject)object).eClass().getEPackage() == modelPackage;
- }
- return false;
- }
-
- /**
- * The switch that delegates to the <code>createXXX</code> methods. <!--
- * begin-user-doc --> <!-- end-user-doc -->
- *
- * @generated
- */
- protected ReviewSwitch<Adapter> modelSwitch = new ReviewSwitch<Adapter>() {
- @Override
- public Adapter caseReview(Review object) {
- return createReviewAdapter();
- }
- @Override
- public Adapter caseReviewResult(ReviewResult object) {
- return createReviewResultAdapter();
- }
- @Override
- public Adapter casePatch(Patch object) {
- return createPatchAdapter();
- }
- @Override
- public Adapter caseScopeItem(ScopeItem object) {
- return createScopeItemAdapter();
- }
- @Override
- public Adapter defaultCase(EObject object) {
- return createEObjectAdapter();
- }
- };
-
- /**
- * Creates an adapter for the <code>target</code>.
- * <!-- begin-user-doc -->
- * <!-- end-user-doc -->
- * @param target the object to adapt.
- * @return the adapter for the <code>target</code>.
- * @generated
- */
- @Override
- public Adapter createAdapter(Notifier target) {
- return modelSwitch.doSwitch((EObject)target);
- }
-
- /**
- * Creates a new adapter for an object of class '
- * {@link org.eclipse.mylyn.reviews.core.model.review.Review
- * <em>Review</em>}'. <!-- begin-user-doc --> This default implementation
- * returns null so that we can easily ignore cases; it's useful to ignore a
- * case when inheritance will catch all the cases anyway. <!-- end-user-doc
- * -->
- *
- * @return the new adapter.
- * @see org.eclipse.mylyn.reviews.core.model.review.Review
- * @generated
- */
- public Adapter createReviewAdapter() {
- return null;
- }
-
- /**
- * Creates a new adapter for an object of class '
- * {@link org.eclipse.mylyn.reviews.core.model.review.ReviewResult
- * <em>Result</em>}'. <!-- begin-user-doc --> This default implementation
- * returns null so that we can easily ignore cases; it's useful to ignore a
- * case when inheritance will catch all the cases anyway. <!-- end-user-doc
- * -->
- *
- * @return the new adapter.
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewResult
- * @generated
- */
- public Adapter createReviewResultAdapter() {
- return null;
- }
-
- /**
- * Creates a new adapter for an object of class '{@link org.eclipse.mylyn.reviews.core.model.review.Patch <em>Patch</em>}'.
- * <!-- begin-user-doc --> This default implementation returns null so
- * that we can easily ignore cases; it's useful to ignore a case when
- * inheritance will catch all the cases anyway. <!-- end-user-doc -->
- * @return the new adapter.
- * @see org.eclipse.mylyn.reviews.core.model.review.Patch
- * @generated
- */
- public Adapter createPatchAdapter() {
- return null;
- }
-
- /**
- * Creates a new adapter for an object of class '{@link org.eclipse.mylyn.reviews.core.model.review.ScopeItem <em>Scope Item</em>}'.
- * <!-- begin-user-doc --> This default
- * implementation returns null so that we can easily ignore cases; it's
- * useful to ignore a case when inheritance will catch all the cases anyway.
- * <!-- end-user-doc -->
- * @return the new adapter.
- * @see org.eclipse.mylyn.reviews.core.model.review.ScopeItem
- * @generated
- */
- public Adapter createScopeItemAdapter() {
- return null;
- }
-
- /**
- * Creates a new adapter for the default case.
- * <!-- begin-user-doc --> This
- * default implementation returns null. <!-- end-user-doc -->
- * @return the new adapter.
- * @generated
- */
- public Adapter createEObjectAdapter() {
- return null;
- }
-
-} // ReviewAdapterFactory
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java b/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java
deleted file mode 100644
index 3ab3388d..00000000
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/model/review/util/ReviewSwitch.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/**
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- */
-package org.eclipse.mylyn.reviews.core.model.review.util;
-
-import java.util.List;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.mylyn.reviews.core.model.review.*;
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewPackage;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewResult;
-import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
-
-/**
- * <!-- begin-user-doc --> The <b>Switch</b> for the model's inheritance
- * hierarchy. It supports the call {@link #doSwitch(EObject) doSwitch(object)}
- * to invoke the <code>caseXXX</code> method for each class of the model,
- * starting with the actual class of the object and proceeding up the
- * inheritance hierarchy until a non-null result is returned, which is the
- * result of the switch. <!-- end-user-doc -->
- * @see org.eclipse.mylyn.reviews.core.model.review.ReviewPackage
- * @generated
- */
-public class ReviewSwitch<T> {
- /**
- * The cached model package
- * <!-- begin-user-doc --> <!-- end-user-doc -->
- * @generated
- */
- protected static ReviewPackage modelPackage;
-
- /**
- * Creates an instance of the switch.
- * <!-- begin-user-doc --> <!--
- * end-user-doc -->
- * @generated
- */
- public ReviewSwitch() {
- if (modelPackage == null) {
- modelPackage = ReviewPackage.eINSTANCE;
- }
- }
-
- /**
- * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
- * <!-- begin-user-doc --> <!--
- * end-user-doc -->
- * @return the first non-null result returned by a <code>caseXXX</code> call.
- * @generated
- */
- public T doSwitch(EObject theEObject) {
- return doSwitch(theEObject.eClass(), theEObject);
- }
-
- /**
- * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
- * <!-- begin-user-doc --> <!--
- * end-user-doc -->
- * @return the first non-null result returned by a <code>caseXXX</code> call.
- * @generated
- */
- protected T doSwitch(EClass theEClass, EObject theEObject) {
- if (theEClass.eContainer() == modelPackage) {
- return doSwitch(theEClass.getClassifierID(), theEObject);
- }
- else {
- List<EClass> eSuperTypes = theEClass.getESuperTypes();
- return
- eSuperTypes.isEmpty() ?
- defaultCase(theEObject) :
- doSwitch(eSuperTypes.get(0), theEObject);
- }
- }
-
- /**
- * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
- * <!-- begin-user-doc --> <!--
- * end-user-doc -->
- * @return the first non-null result returned by a <code>caseXXX</code> call.
- * @generated
- */
- protected T doSwitch(int classifierID, EObject theEObject) {
- switch (classifierID) {
- case ReviewPackage.REVIEW: {
- Review review = (Review)theEObject;
- T result = caseReview(review);
- if (result == null) result = defaultCase(theEObject);
- return result;
- }
- case ReviewPackage.REVIEW_RESULT: {
- ReviewResult reviewResult = (ReviewResult)theEObject;
- T result = caseReviewResult(reviewResult);
- if (result == null) result = defaultCase(theEObject);
- return result;
- }
- case ReviewPackage.PATCH: {
- Patch patch = (Patch)theEObject;
- T result = casePatch(patch);
- if (result == null) result = caseScopeItem(patch);
- if (result == null) result = defaultCase(theEObject);
- return result;
- }
- case ReviewPackage.SCOPE_ITEM: {
- ScopeItem scopeItem = (ScopeItem)theEObject;
- T result = caseScopeItem(scopeItem);
- if (result == null) result = defaultCase(theEObject);
- return result;
- }
- default: return defaultCase(theEObject);
- }
- }
-
- /**
- * Returns the result of interpreting the object as an instance of '<em>Review</em>'.
- * <!-- begin-user-doc --> This implementation returns
- * null; returning a non-null result will terminate the switch. <!--
- * end-user-doc -->
- * @param object the target of the switch.
- * @return the result of interpreting the object as an instance of '<em>Review</em>'.
- * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
- * @generated
- */
- public T caseReview(Review object) {
- return null;
- }
-
- /**
- * Returns the result of interpreting the object as an instance of '<em>Result</em>'.
- * <!-- begin-user-doc --> This implementation returns
- * null; returning a non-null result will terminate the switch. <!--
- * end-user-doc -->
- * @param object the target of the switch.
- * @return the result of interpreting the object as an instance of '<em>Result</em>'.
- * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
- * @generated
- */
- public T caseReviewResult(ReviewResult object) {
- return null;
- }
-
- /**
- * Returns the result of interpreting the object as an instance of '<em>Patch</em>'.
- * <!-- begin-user-doc --> This implementation returns
- * null; returning a non-null result will terminate the switch. <!--
- * end-user-doc -->
- * @param object the target of the switch.
- * @return the result of interpreting the object as an instance of '<em>Patch</em>'.
- * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
- * @generated
- */
- public T casePatch(Patch object) {
- return null;
- }
-
- /**
- * Returns the result of interpreting the object as an instance of '<em>Scope Item</em>'.
- * <!-- begin-user-doc --> This implementation returns
- * null; returning a non-null result will terminate the switch. <!--
- * end-user-doc -->
- * @param object the target of the switch.
- * @return the result of interpreting the object as an instance of '<em>Scope Item</em>'.
- * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
- * @generated
- */
- public T caseScopeItem(ScopeItem object) {
- return null;
- }
-
- /**
- * Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
- * <!-- begin-user-doc --> This implementation returns
- * null; returning a non-null result will terminate the switch, but this is
- * the last case anyway. <!-- end-user-doc -->
- * @param object the target of the switch.
- * @return the result of interpreting the object as an instance of '<em>EObject</em>'.
- * @see #doSwitch(org.eclipse.emf.ecore.EObject)
- * @generated
- */
- public T defaultCase(EObject object) {
- return null;
- }
-
-} // ReviewSwitch
diff --git a/tbr/org.eclipse.mylyn.reviews.core/.classpath b/tbr/org.eclipse.mylyn.reviews.tasks.core/.classpath
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.core/.classpath
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/.classpath
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/.project b/tbr/org.eclipse.mylyn.reviews.tasks.core/.project
similarity index 94%
rename from tbr/org.eclipse.mylyn.reviews.ui/.project
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/.project
index 8d039bc9..d83a9137 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/.project
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/.project
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
- <name>org.eclipse.mylyn.reviews.ui</name>
+ <name>org.eclipse.mylyn.reviews.tasks.core</name>
<comment></comment>
<projects>
</projects>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..b177a01b
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF
@@ -0,0 +1,17 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Mylyn Reviews Core (Incubation)
+Bundle-SymbolicName: org.eclipse.mylyn.reviews.tasks.core;singleton:=true
+Bundle-Version: 0.0.1.qualifier
+Require-Bundle: org.eclipse.core.runtime,
+ org.eclipse.emf.edit;bundle-version="2.5.0",
+ org.eclipse.team.core;bundle-version="3.5.0",
+ org.eclipse.core.resources;bundle-version="3.5.1",
+ org.eclipse.mylyn.tasks.core;bundle-version="3.3.0",
+ org.eclipse.compare;bundle-version="3.5.0",
+ org.eclipse.mylyn.reviews.tasks.dsl;bundle-version="0.0.1",
+ org.eclipse.xtext;bundle-version="1.0.1",
+ org.eclipse.swt;bundle-version="3.6.1"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.eclipse.mylyn.reviews.tasks.core,
+ org.eclipse.mylyn.reviews.tasks.core.internal;x-friends:="org.eclipse.mylyn.reviews.tasks.ui"
diff --git a/tbr/org.eclipse.mylyn.reviews.core/about.html b/tbr/org.eclipse.mylyn.reviews.tasks.core/about.html
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.core/about.html
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/about.html
diff --git a/tbr/org.eclipse.mylyn.reviews.core/build.properties b/tbr/org.eclipse.mylyn.reviews.tasks.core/build.properties
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.core/build.properties
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/build.properties
diff --git a/tbr/org.eclipse.mylyn.reviews.core/plugin.properties b/tbr/org.eclipse.mylyn.reviews.tasks.core/plugin.properties
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.core/plugin.properties
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/plugin.properties
diff --git a/tbr/org.eclipse.mylyn.reviews.core/plugin.xml b/tbr/org.eclipse.mylyn.reviews.tasks.core/plugin.xml
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.core/plugin.xml
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/plugin.xml
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/Attachment.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/Attachment.java
new file mode 100644
index 00000000..2965605e
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/Attachment.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+/**
+ *
+ * @author mattk
+ *
+ */
+public class Attachment {
+
+ private String fileName;
+ private String author;
+ private String date;
+ private String url;
+ private boolean isPatch;
+ private ITaskProperties task;
+
+ public Attachment(ITaskProperties task, String fileName, String author,
+ String date, boolean isPatch, String url) {
+ this.task = task;
+ this.fileName = fileName;
+ this.author = author;
+ this.date = date;
+ this.isPatch = isPatch;
+ this.url = url;
+ }
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public String getDate() {
+ return date;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public ITaskProperties getTask() {
+ return task;
+ }
+
+ public boolean isPatch() {
+ return isPatch;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/IPatchCreator.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewFile.java
similarity index 65%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/IPatchCreator.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewFile.java
index 390692ed..979d531d 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/IPatchCreator.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewFile.java
@@ -8,24 +8,19 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
+package org.eclipse.mylyn.reviews.tasks.core;
-import java.util.Date;
+import org.eclipse.compare.structuremergeviewer.ICompareInput;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-
-/*
- * @author Kilian Matt
+/**
+ * @author mattk
+ *
*/
-public interface IPatchCreator {
-
- public abstract Patch create() throws CoreException;
-
- public abstract String getFileName();
-
- public abstract String getAuthor();
+public interface IReviewFile {
- public abstract Date getCreationDate();
+ String getFileName();
+ boolean isNewFile();
+ boolean canReview();
+ ICompareInput getCompareInput();
}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewMapper.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewMapper.java
new file mode 100644
index 00000000..b1b5ff75
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewMapper.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+import java.util.List;
+
+import org.eclipse.core.runtime.CoreException;
+
+/**
+ *
+ * @author mattk
+ *
+ */
+public interface IReviewMapper {
+
+ void mapResultToTask(ReviewResult res, ITaskProperties taskProperties);
+
+ void mapScopeToTask(ReviewScope scope, ITaskProperties taskProperties);
+
+ List<ReviewResult> mapTaskToResults(ITaskProperties taskProperties);
+
+ ReviewScope mapTaskToScope(ITaskProperties properties) throws CoreException;
+
+ ReviewResult mapCurrentReviewResult(ITaskProperties taskProperties);
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewScopeItem.java
new file mode 100644
index 00000000..3b6dae06
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/IReviewScopeItem.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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+import java.util.List;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.NullProgressMonitor;
+/**
+ * @author mattk
+ *
+ */
+public interface IReviewScopeItem {
+
+ 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/ITaskProperties.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ITaskProperties.java
new file mode 100644
index 00000000..c8267549
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ITaskProperties.java
@@ -0,0 +1,51 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+import java.util.List;
+
+import org.eclipse.core.runtime.CoreException;
+
+/**
+ *
+ * @author mattk
+ *
+ */
+public interface ITaskProperties {
+
+ String getDescription();
+
+ String getAssignedTo();
+
+ List<TaskComment> getComments();
+
+ List<Attachment> getAttachments();
+
+ ITaskProperties loadFor(String taskId) throws CoreException;
+
+ String getTaskId();
+
+ String getNewCommentText();
+
+ void setNewCommentText(String comment);
+
+ void setDescription(String description);
+
+ void setSummary(String summary);
+
+ void setAssignedTo(String assignee);
+
+ String getRepositoryUrl();
+
+ String getReporter();
+
+}
+
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
new file mode 100644
index 00000000..13f92a7e
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/PatchScopeItem.java
@@ -0,0 +1,85 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.compare.patch.IFilePatch2;
+import org.eclipse.compare.patch.PatchParser;
+import org.eclipse.compare.patch.ReaderCreator;
+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.mylyn.reviews.tasks.core.internal.PatchReviewFile;
+import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewConstants;
+
+/**
+ *
+ * @author mattk
+ *
+ */
+public class PatchScopeItem implements IReviewScopeItem {
+
+ private Attachment attachment;
+
+ public PatchScopeItem(Attachment attachment) {
+ this.attachment = attachment;
+ }
+
+ public Attachment getAttachment() {
+ return attachment;
+ }
+
+ private ReaderCreator getPatch() {
+ return new ReaderCreator() {
+
+ @Override
+ public Reader createReader() throws CoreException {
+ try {
+ System.err.println(attachment.getUrl());
+ return new InputStreamReader(
+ new URL(attachment.getUrl()).openStream());
+ } catch (Exception e) {
+ throw new CoreException(new Status(IStatus.ERROR,
+ ReviewConstants.PLUGIN_ID, e.getMessage()));
+ }
+
+ }
+ };
+ }
+
+ @Override
+ public List<IReviewFile> getReviewFiles(
+ NullProgressMonitor nullProgressMonitor) throws CoreException {
+ IFilePatch2[] parsedPatch = PatchParser.parsePatch(getPatch());
+ List<IReviewFile> files = new ArrayList<IReviewFile>();
+ for (IFilePatch2 filePatch : parsedPatch) {
+ files.add(new PatchReviewFile(filePatch));
+ }
+ return files;
+ }
+
+ @Override
+ public String getDescription() {
+ 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.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSubmitHandler.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/Rating.java
similarity index 74%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSubmitHandler.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/Rating.java
index f037b64a..14ba4129 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSubmitHandler.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/Rating.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology
+ * 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
@@ -8,13 +8,19 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
+package org.eclipse.mylyn.reviews.tasks.core;
-/*
- * @author Kilian Matt
+/**
+ * @author mattk
+ *
*/
-public interface ReviewSubmitHandler {
-
- void doSubmit(ReviewTaskEditorInput editorInput);
-
+public enum Rating {
+ TODO,
+ PASSED,
+ WARNING,
+ FAIL;
+
+ public int getPriority() {
+ return this.ordinal();
+ }
}
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
new file mode 100644
index 00000000..05ec47fd
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ResourceScopeItem.java
@@ -0,0 +1,148 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.compare.IStreamContentAccessor;
+import org.eclipse.compare.ITypedElement;
+import org.eclipse.compare.structuremergeviewer.DiffNode;
+import org.eclipse.compare.structuremergeviewer.Differencer;
+import org.eclipse.compare.structuremergeviewer.ICompareInput;
+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.mylyn.reviews.tasks.core.internal.ReviewConstants;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * @author mattk
+ *
+ */
+public class ResourceScopeItem implements IReviewScopeItem {
+ private Attachment attachment;
+
+ public ResourceScopeItem(Attachment attachment) {
+ this.attachment = attachment;
+ }
+
+ public Attachment getAttachment() {
+ return attachment;
+ }
+
+ @Override
+ public List<IReviewFile> getReviewFiles(NullProgressMonitor monitor)
+ throws CoreException {
+
+ return Arrays.asList((IReviewFile) new ResourceReviewFile(attachment
+ .getFileName(), attachment.getUrl()));
+ }
+
+ private static class ResourceReviewFile implements IReviewFile {
+
+ private ICompareInput compareInput;
+ private String fileName;
+ private String url;
+
+ public ResourceReviewFile(String fileName, String url) {
+ this.fileName = fileName;
+ this.url = url;
+ }
+
+ public ICompareInput getCompareInput() {
+ if (compareInput == null) {
+ ICompareInput ci = new DiffNode(Differencer.CHANGE, null,
+ new CompareItem(fileName) {
+ @Override
+ public InputStream getContents()
+ throws CoreException {
+ return new ByteArrayInputStream(new byte[0]);
+ }
+ }, new CompareItem(fileName) {
+ @Override
+ public InputStream getContents()
+ throws CoreException {
+ try {
+ return new URL(url)
+ .openStream();
+ } catch (Exception e) {
+ throw new CoreException(new Status(
+ IStatus.ERROR,
+ ReviewConstants.PLUGIN_ID, e
+ .getMessage()));
+ }
+ }
+ });
+ compareInput = ci;
+ }
+ return compareInput;
+
+ }
+
+ @Override
+ public String getFileName() {
+ return fileName;
+ }
+
+ @Override
+ public boolean isNewFile() {
+ return true;
+ }
+
+ @Override
+ public boolean canReview() {
+ return true;
+
+ }
+
+ private static abstract class CompareItem implements IStreamContentAccessor,
+ ITypedElement {
+
+ private String filename;
+
+ public CompareItem(String filename) {
+ this.filename = filename;
+ }
+
+ public abstract InputStream getContents() throws CoreException;
+
+ public Image getImage() {
+ return null;
+ }
+
+ public String getName() {
+ return filename;
+ }
+
+ public String getType() {
+ return ITypedElement.TEXT_TYPE;
+ }
+ }
+
+ }
+
+ @Override
+ public String getDescription() {
+ 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/ReviewResult.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewResult.java
new file mode 100644
index 00000000..723bb8e8
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewResult.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.util.Date;
+
+/**
+ * @author mattk
+ *
+ */
+public class ReviewResult {
+ private String reviewer;
+ private Rating rating;
+ private String comment;
+ private Date date;
+ private final PropertyChangeSupport changeSupport = new PropertyChangeSupport(
+ this);
+
+ public void addPropertyChangeListener(String propertyName,
+ PropertyChangeListener listener) {
+ changeSupport.addPropertyChangeListener(propertyName, listener);
+ }
+
+ public void removePropertyChangeListener(String propertyName,
+ PropertyChangeListener listener) {
+ changeSupport.removePropertyChangeListener(propertyName, listener);
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ Date old = this.date;
+ this.date = date;
+ changeSupport.firePropertyChange("date", old, date);
+ }
+
+ public String getReviewer() {
+ return reviewer;
+ }
+
+ public void setReviewer(String reviewer) {
+ String old = this.reviewer;
+ this.reviewer = reviewer;
+ changeSupport.firePropertyChange("reviewer", old, reviewer);
+ }
+
+ public Rating getRating() {
+ return rating;
+ }
+
+ public void setRating(Rating rating) {
+ Rating old = this.rating;
+ this.rating = rating;
+ changeSupport.firePropertyChange("rating", old, rating);
+ }
+
+ public String getComment() {
+ return comment;
+ }
+
+ public void setComment(String comment) {
+ String old = this.comment;
+ this.comment = comment;
+ changeSupport.firePropertyChange("comment", old, comment);
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScope.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScope.java
new file mode 100644
index 00000000..7cc85ee3
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewScope.java
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author mattk
+ *
+ */
+public class ReviewScope {
+ private List<IReviewScopeItem> items = new ArrayList<IReviewScopeItem>();
+ private String creator;
+
+ public List<IReviewScopeItem> getItems() {
+ return Collections.unmodifiableList( items );
+ }
+ public void addScope(IReviewScopeItem item) {
+ this.items.add(item);
+ }
+ public String getCreator() {
+ return creator;
+ }
+ public void setCreator(String creator) {
+ this.creator=creator;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/TaskComment.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/TaskComment.java
new file mode 100644
index 00000000..b58b5fcd
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/TaskComment.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core;
+
+import java.util.Date;
+
+/**
+ *
+ * @author mattk
+ *
+ */
+public class TaskComment {
+ private String author;
+ private String text;
+ private Date date;
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public void setText(String text) {
+ this.text = text;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/AbstractTreeNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/AbstractTreeNode.java
new file mode 100644
index 00000000..3d467515
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/AbstractTreeNode.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core.internal;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+
+/**
+ * @author mattk
+ *
+ */
+public abstract class AbstractTreeNode implements ITreeNode {
+ private ITreeNode parent;
+ private List<ITreeNode> children=new ArrayList<ITreeNode>();
+ private ITaskProperties task;
+
+ protected AbstractTreeNode(ITaskProperties task) {
+ this.task=task;
+ }
+
+ @Override
+ public List<ITreeNode> getChildren() {
+ return Collections.unmodifiableList(children);
+ }
+
+ @Override
+ public ITreeNode getParent() {
+ return parent;
+ }
+
+ public void addChildren(ITreeNode child) {
+ this.children.add(child);
+ child.setParent(this);
+ }
+
+ @Override
+ public void setParent(ITreeNode parent) {
+ this.parent = parent;
+ }
+
+ @Override
+ public String getTaskId() {
+ return task!=null? task.getTaskId():null;
+ }
+
+ @Override
+ public ITaskProperties getTask() {
+ return task;
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ITreeNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ITreeNode.java
new file mode 100644
index 00000000..b653b810
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ITreeNode.java
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core.internal;
+
+import java.util.List;
+
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.reviews.tasks.core.Rating;
+
+/**
+ * @author mattk
+ *
+ */
+public interface ITreeNode {
+ List<ITreeNode> getChildren();
+
+ ITreeNode getParent();
+
+ void setParent(ITreeNode parent);
+
+ String getDescription();
+
+ Rating getResult();
+
+ String getTaskId();
+
+ ITaskProperties getTask();
+
+ String getPerson() ;
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CompareItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchCompareItem.java
similarity index 87%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CompareItem.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchCompareItem.java
index 9c50c24c..8a9be0eb 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CompareItem.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchCompareItem.java
@@ -8,7 +8,8 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
+
+package org.eclipse.mylyn.reviews.tasks.core.internal;
import java.io.InputStream;
@@ -18,11 +19,10 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
-// TODO move to core?
-/*
+/**
* @author Kilian Matt
*/
-public class CompareItem implements IStreamContentAccessor, ITypedElement {
+public class PatchCompareItem implements IStreamContentAccessor, ITypedElement {
public enum Kind {
ORIGINAL, PATCHED
};
@@ -31,7 +31,7 @@ public enum Kind {
private Kind kind;
private String filename;
- public CompareItem(IFilePatchResult result, Kind kind, String filename) {
+ public PatchCompareItem(IFilePatchResult result, Kind kind, String filename) {
this.result = result;
this.kind = kind;
this.filename = filename;
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewDiffModel.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchReviewFile.java
similarity index 82%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewDiffModel.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchReviewFile.java
index 7626eeb5..6f12ea48 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewDiffModel.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/PatchReviewFile.java
@@ -8,7 +8,7 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
+package org.eclipse.mylyn.reviews.tasks.core.internal;
import java.io.CharArrayReader;
import java.io.Reader;
@@ -25,42 +25,31 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.mylyn.reviews.core.ITargetPathStrategy;
-import org.eclipse.mylyn.reviews.core.ReviewsUtil;
-
+import org.eclipse.mylyn.reviews.tasks.core.IReviewFile;
+import org.eclipse.mylyn.reviews.tasks.core.patch.ITargetPathStrategy;
/**
- * @author Kilian Matt
+ * @author mattk
+ *
*/
-public class ReviewDiffModel {
+public class PatchReviewFile implements IReviewFile {
+ private ICompareInput compareInput;
private IFilePatch2 patch;
+ private IFilePatchResult compareEditorInput;
private PatchConfiguration configuration;
- private ICompareInput compareInput;
- private IFilePatchResult compareEditorInput = null;
-
- public ReviewDiffModel(IFilePatch2 currentPatch,
- PatchConfiguration configuration) {
- patch = currentPatch;
- this.configuration = configuration;
- }
-
- @Override
- public String toString() {
- return getFileName();
- }
- public String getFileName() {
- String string = patch.getTargetPath(configuration).lastSegment();
- return string;
+ public PatchReviewFile(IFilePatch2 filePatch) {
+ this.patch = filePatch;
+ configuration = new PatchConfiguration();
}
public ICompareInput getCompareInput() {
if (compareInput == null) {
IFilePatchResult patchResult = getCompareEditorInput();
ICompareInput ci = new DiffNode(Differencer.CHANGE, null,
- new CompareItem(patchResult, CompareItem.Kind.ORIGINAL,
- toString()), new CompareItem(patchResult,
- CompareItem.Kind.PATCHED, toString()));
+ new PatchCompareItem(patchResult, PatchCompareItem.Kind.ORIGINAL,
+ toString()), new PatchCompareItem(patchResult,
+ PatchCompareItem.Kind.PATCHED, toString()));
compareInput = ci;
}
return compareInput;
@@ -113,6 +102,22 @@ private boolean patchAddsFile() {
return true;
}
+ @Override
+ public String getFileName() {
+ return patch.getTargetPath(configuration).lastSegment();
+ }
+
+ @Override
+ public boolean isNewFile() {
+ return patchAddsFile();
+ }
+
+ @Override
+ public boolean canReview() {
+ return sourceFileExists() || patchAddsFile();
+
+ }
+
public boolean sourceFileExists() {
IPath targetPath = patch.getTargetPath(configuration);
@@ -125,12 +130,5 @@ public boolean sourceFileExists() {
}
return false;
}
- public boolean canReview() {
- return sourceFileExists() || patchAddsFile();
- }
-
- public boolean isNewFile() {
- return patchAddsFile();
- }
}
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewConstants.java
similarity index 79%
rename from tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewConstants.java
index 704be905..0a0aeca2 100644
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewConstants.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewConstants.java
@@ -8,18 +8,19 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.core;
+package org.eclipse.mylyn.reviews.tasks.core.internal;
/**
* @author Kilian Matt
*/
public class ReviewConstants {
- public static final String REVIEW_DATA_CONTAINER = "review-data.zip";
-
- public static final String REVIEW_DATA_FILE = "reviews-data.xml";
-
public static final String ATTR_CACHED_REVIEW = "review";
public static final String ATTR_REVIEW_FLAG = "isReview";
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.mylyn.reviews.core"; //$NON-NLS-1$
+
+ public static final String REVIEW_MARKER = "[review]";
}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewResultNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewResultNode.java
new file mode 100644
index 00000000..dcc1da41
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewResultNode.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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core.internal;
+
+import org.eclipse.mylyn.reviews.tasks.core.Rating;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewResult;
+/**
+ * @author mattk
+ *
+ */
+public class ReviewResultNode extends AbstractTreeNode {
+
+ private ReviewResult result;
+
+ public ReviewResultNode(ReviewResult result) {
+ super(null);
+ this.result = result;
+ }
+
+ public String getDescription() {
+ return result.getComment();
+ }
+
+ @Override
+ public Rating getResult() {
+ return result.getRating();
+ }
+
+ @Override
+ public String getPerson() {
+ return result.getReviewer();
+ }
+
+
+}
\ No newline at end of file
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
new file mode 100644
index 00000000..504c2c51
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core.internal;
+
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.reviews.tasks.core.Rating;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewResult;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewScope;
+import org.eclipse.mylyn.reviews.tasks.core.IReviewScopeItem;
+/**
+ *
+ * @author mattk
+ *
+ */
+public class ReviewScopeNode extends AbstractTreeNode {
+
+ private ReviewScope scope;
+ private String description;
+ private List<ReviewResult> results;
+
+ public ReviewScopeNode(ITaskProperties task, ReviewScope scope, List<ReviewResult> results) {
+ super(task);
+ this.scope = scope;
+ this.results = results;
+ for (ReviewResult result : results) {
+ addChildren(new ReviewResultNode(result));
+ }
+ }
+
+ public String getDescription() {
+ if (description == null) {
+ description = convertScopeToDescription();
+ }
+ return description;
+ }
+ private static class Counter {
+ int counter;
+ IReviewScopeItem item;
+ public Counter(IReviewScopeItem item) {
+ this.item=item;
+ }
+ }
+ private String convertScopeToDescription() {
+ StringBuilder sb = new StringBuilder();
+ Map<String, Counter> counts = new TreeMap<String, Counter>();
+ for (IReviewScopeItem item : scope.getItems()) {
+ String key = item.getType(1);
+ if (!counts.containsKey(key)) {
+ counts.put(key, new Counter(item));
+ }
+ counts.get(key).counter++;
+ }
+ boolean isFirstElement = true;
+ for (String type : counts.keySet()) {
+ if (isFirstElement) {
+ isFirstElement = false;
+ } else {
+ sb.append(", ");
+ }
+
+ int count = counts.get(type).counter;
+ sb.append(count);
+ sb.append(" ");
+ sb.append(counts.get(type).item.getType(count));
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public Rating getResult() {
+ Rating rating = null;
+ for (ReviewResult res : results) {
+ if (rating == null
+ || res.getRating().getPriority() > rating.getPriority()) {
+ rating = res.getRating();
+ }
+ }
+ return rating;
+ }
+
+ @Override
+ public String getPerson() {
+ // TODO
+ return scope.getCreator();
+ }
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java
new file mode 100644
index 00000000..65975a64
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java
@@ -0,0 +1,255 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core.internal;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.mylyn.reviews.tasks.core.Attachment;
+import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper;
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.reviews.tasks.core.PatchScopeItem;
+import org.eclipse.mylyn.reviews.tasks.core.Rating;
+import org.eclipse.mylyn.reviews.tasks.core.ResourceScopeItem;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewScope;
+import org.eclipse.mylyn.reviews.tasks.core.IReviewScopeItem;
+import org.eclipse.mylyn.reviews.tasks.core.TaskComment;
+import org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr.ReviewDslParser;
+import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.AttachmentSource;
+import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.PatchDef;
+import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ResourceDef;
+import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ResultEnum;
+import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewDslFactory;
+import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult;
+import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.Source;
+import org.eclipse.xtext.parser.IParseResult;
+import org.eclipse.xtext.parsetree.reconstr.Serializer;
+/**
+ * @author mattk
+ *
+ */
+public class ReviewTaskMapper implements IReviewMapper {
+ private ReviewDslParser parser;
+ private Serializer serializer;
+
+ public ReviewTaskMapper(ReviewDslParser parser, Serializer serializer) {
+ this.parser = parser;
+ this.serializer = serializer;
+ }
+
+ private org.eclipse.mylyn.reviews.tasks.core.ReviewResult mapResult(
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult parsed,
+ TaskComment comment) {
+ if (parsed == null)
+ return null;
+
+ org.eclipse.mylyn.reviews.tasks.core.ReviewResult result = new org.eclipse.mylyn.reviews.tasks.core.ReviewResult();
+ result.setReviewer(comment.getAuthor());
+ result.setDate(comment.getDate());
+ result.setRating(mapRating(parsed.getResult()));
+ result.setComment(comment.getText());
+ return result;
+ }
+
+ private Rating mapRating(ResultEnum result) {
+ switch (result) {
+ case PASSED:
+ return Rating.PASSED;
+ case FAILED:
+ return Rating.FAIL;
+ case WARNING:
+ return Rating.WARNING;
+ case TODO:
+ return Rating.TODO;
+ }
+ throw new IllegalArgumentException();
+ }
+
+ @Override
+ public ReviewScope mapTaskToScope(ITaskProperties properties)
+ throws CoreException {
+ Assert.isNotNull(properties);
+ IParseResult parsed = parser.doParse(properties.getDescription());
+
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope = (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope) parsed
+ .getRootASTElement();
+ return mapReviewScope(properties, scope);
+ }
+
+ private ReviewScope mapReviewScope(ITaskProperties properties,
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope)
+ throws CoreException {
+ if (scope == null)
+ return null;
+
+ ReviewScope mappedScope = new ReviewScope();
+ mappedScope.setCreator(properties.getReporter());
+ for (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScopeItem s : scope
+ .getScope()) {
+ if (s instanceof PatchDef) {
+ PatchScopeItem item = mapPatchDef(properties, mappedScope, (PatchDef) s);
+ mappedScope.addScope(item);
+ } else if (s instanceof ResourceDef) {
+ ResourceDef res = (ResourceDef) s;
+ ResourceScopeItem item = mapResourceDef(properties, res);
+ mappedScope.addScope(item);
+ }
+ }
+ return mappedScope;
+ }
+
+ private ResourceScopeItem mapResourceDef(ITaskProperties properties,
+ ResourceDef res) throws CoreException {
+ Source source = res.getSource();
+ Attachment att = null;
+ if (source instanceof AttachmentSource) {
+ att = parseAttachmenSource(properties, source);
+ }
+ return new ResourceScopeItem(att);
+ }
+
+ private PatchScopeItem mapPatchDef(ITaskProperties properties,
+ ReviewScope mappedScope, PatchDef patch) throws CoreException {
+ Source source = patch.getSource();
+ Attachment att = null;
+ if (source instanceof AttachmentSource) {
+ att = parseAttachmenSource(properties, source);
+ }
+ return new PatchScopeItem(att);
+ }
+
+ private Attachment parseAttachmenSource(ITaskProperties properties,
+ Source source) throws CoreException {
+ AttachmentSource attachment = (AttachmentSource) source;
+
+ Attachment att = ReviewsUtil.findAttachment(attachment.getFilename(),
+ attachment.getAuthor(), attachment.getCreatedDate(),
+ properties.loadFor(attachment.getTaskId()));
+ return att;
+ }
+
+ @Override
+ public void mapScopeToTask(ReviewScope scope, ITaskProperties taskProperties) {
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope2 = mapScope(scope);
+
+ taskProperties.setDescription(serializer.serialize(scope2));
+ }
+
+ private org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope mapScope(
+ ReviewScope scope) {
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope2 = ReviewDslFactory.eINSTANCE
+ .createReviewScope();
+ for (IReviewScopeItem item : scope.getItems()) {
+ scope2.getScope().add(mapScopeItem(item));
+ }
+ return scope2;
+ }
+
+ private org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScopeItem mapScopeItem(
+ IReviewScopeItem item) {
+ if (item instanceof PatchScopeItem) {
+ PatchScopeItem patchItem = (PatchScopeItem) item;
+ PatchDef patch = ReviewDslFactory.eINSTANCE.createPatchDef();
+ Attachment attachment = patchItem.getAttachment();
+ AttachmentSource source = mapAttachment(attachment);
+ patch.setSource(source);
+
+ return patch;
+ } else if (item instanceof ResourceScopeItem) {
+ ResourceScopeItem resourceItem = (ResourceScopeItem) item;
+ ResourceDef resource = ReviewDslFactory.eINSTANCE
+ .createResourceDef();
+ Attachment attachment = resourceItem.getAttachment();
+ AttachmentSource source = mapAttachment(attachment);
+ resource.setSource(source);
+ return resource;
+ }
+ return null;
+ }
+
+ private AttachmentSource mapAttachment(Attachment attachment) {
+ AttachmentSource source = ReviewDslFactory.eINSTANCE
+ .createAttachmentSource();
+ source.setAuthor(attachment.getAuthor());
+ source.setCreatedDate(attachment.getDate());
+ source.setFilename(attachment.getFileName());
+ source.setTaskId(attachment.getTask().getTaskId());
+ return source;
+ }
+
+ @Override
+ public void mapResultToTask(
+ org.eclipse.mylyn.reviews.tasks.core.ReviewResult res,
+ ITaskProperties taskProperties) {
+ ReviewResult result = ReviewDslFactory.eINSTANCE.createReviewResult();
+ ResultEnum rating = ResultEnum.WARNING;
+ switch (res.getRating()) {
+ case FAIL:
+ rating = ResultEnum.FAILED;
+ break;
+ case PASSED:
+ rating = ResultEnum.PASSED;
+ break;
+ case TODO:
+ rating = ResultEnum.TODO;
+ break;
+ case WARNING:
+ rating = ResultEnum.WARNING;
+ break;
+ }
+ result.setResult(rating);
+ result.setComment(res.getComment());
+
+ String resultAsText = serializer.serialize(result);
+ System.err.println(resultAsText);
+ taskProperties.setNewCommentText(resultAsText);
+ }
+
+ @Override
+ public org.eclipse.mylyn.reviews.tasks.core.ReviewResult mapCurrentReviewResult(
+ ITaskProperties taskProperties) {
+ Assert.isNotNull(taskProperties);
+ if (taskProperties.getNewCommentText() == null)
+ return null;
+ IParseResult parsed = parser
+ .doParse(taskProperties.getNewCommentText());
+
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult res = (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult) parsed
+ .getRootASTElement();
+ org.eclipse.mylyn.reviews.tasks.core.ReviewResult result = new org.eclipse.mylyn.reviews.tasks.core.ReviewResult();
+ if (res == null)
+ return null;
+ result.setComment(res.getComment());
+ result.setRating(mapRating(res.getResult()));
+ // FIXME author is current
+ // result.setReviewer()
+ // result.setDate()
+ return result;
+ }
+
+ @Override
+ public List<org.eclipse.mylyn.reviews.tasks.core.ReviewResult> mapTaskToResults(
+ ITaskProperties taskProperties) {
+ List<org.eclipse.mylyn.reviews.tasks.core.ReviewResult> results = new ArrayList<org.eclipse.mylyn.reviews.tasks.core.ReviewResult>();
+ for (TaskComment comment : taskProperties.getComments()) {
+ IParseResult parsed = parser.doParse(comment.getText());
+ if (parsed.getRootASTElement() != null) {
+ results.add(mapResult(
+ (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult) parsed
+ .getRootASTElement(), comment));
+ }
+ }
+ return results;
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewsUtil.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewsUtil.java
new file mode 100644
index 00000000..5907e378
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewsUtil.java
@@ -0,0 +1,104 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core.internal;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.mylyn.reviews.tasks.core.Attachment;
+import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper;
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewResult;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewScope;
+import org.eclipse.mylyn.reviews.tasks.core.patch.GitPatchPathFindingStrategy;
+import org.eclipse.mylyn.reviews.tasks.core.patch.ITargetPathStrategy;
+import org.eclipse.mylyn.reviews.tasks.core.patch.SimplePathFindingStrategy;
+import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslStandaloneSetup;
+import org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr.ReviewDslParser;
+import org.eclipse.mylyn.tasks.core.ITask;
+import org.eclipse.mylyn.tasks.core.ITaskContainer;
+import org.eclipse.mylyn.tasks.core.data.ITaskDataManager;
+import org.eclipse.xtext.parsetree.reconstr.Serializer;
+
+import com.google.inject.Injector;
+
+/**
+ * @author Kilian Matt
+ */
+public class ReviewsUtil {
+ public static ITreeNode getReviewSubTasksFor(ITask task,
+ ITaskDataManager taskDataManager, IReviewMapper mapper,
+ IProgressMonitor monitor) throws CoreException {
+
+ ITaskProperties taskProperties = TaskProperties.fromTaskData(
+ taskDataManager, taskDataManager.getTaskData(task));
+ if (ReviewsUtil.isMarkedAsReview(task)) {
+
+ ReviewScope scope = mapper.mapTaskToScope(taskProperties);
+ List<ReviewResult> results = mapper
+ .mapTaskToResults(taskProperties);
+ return new ReviewScopeNode(taskProperties, scope, results);
+ } else {
+ TaskNode current = new TaskNode(taskProperties);
+ if (task instanceof ITaskContainer) {
+ ITaskContainer taskContainer = (ITaskContainer) task;
+ for (ITask subTask : taskContainer.getChildren()) {
+ current.addChildren(getReviewSubTasksFor(subTask,
+ taskDataManager, mapper, monitor));
+ }
+ }
+ return current;
+ }
+ }
+
+ private static List<ITargetPathStrategy> strategies;
+ static {
+ strategies = new ArrayList<ITargetPathStrategy>();
+ strategies.add(new SimplePathFindingStrategy());
+ strategies.add(new GitPatchPathFindingStrategy());
+ }
+
+ public static List<? extends ITargetPathStrategy> getPathFindingStrategies() {
+ return strategies;
+ }
+
+ public static boolean isMarkedAsReview(ITask task) {
+ return task.getSummary().startsWith(ReviewConstants.REVIEW_MARKER);
+ }
+
+ public static boolean hasReviewMarker(ITask task) {
+ return task.getAttribute(ReviewConstants.ATTR_REVIEW_FLAG) != null;
+ }
+
+ public static Attachment findAttachment(String filename, String author,
+ String createdDate, ITaskProperties task) {
+ for (Attachment att : task.getAttachments()) {
+ if (filename.equals(att.getFileName())) {
+ return att;
+ }
+
+ }
+ return null;
+ }
+
+ public static ReviewTaskMapper createMapper() {
+ Injector createInjectorAndDoEMFRegistration = new ReviewDslStandaloneSetup()
+ .createInjectorAndDoEMFRegistration();
+ ReviewDslParser parser = createInjectorAndDoEMFRegistration
+ .getInstance(ReviewDslParser.class);
+ Serializer serializer = createInjectorAndDoEMFRegistration
+ .getInstance(Serializer.class);
+ return new ReviewTaskMapper(parser, serializer);
+ }
+
+}
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
new file mode 100644
index 00000000..bc582f6e
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskNode.java
@@ -0,0 +1,81 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core.internal;
+
+import org.eclipse.mylyn.reviews.tasks.core.Attachment;
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.reviews.tasks.core.Rating;
+/**
+ *
+ * @author mattk
+ *
+ */
+public class TaskNode extends AbstractTreeNode {
+
+ public TaskNode(ITaskProperties task) {
+ super(task);
+ }
+
+ @Override
+ public String getDescription() {
+ int patchCount=0;
+ int otherCount=0;
+ for(Attachment att : getTask().getAttachments()) {
+ if(att.isPatch()) {
+ patchCount++;
+ } else {
+ otherCount++;
+ }
+ }
+ StringBuilder sb = new StringBuilder();
+ if(patchCount >0) {
+ sb.append(patchCount);
+ sb.append(" patch");
+ if(patchCount>1) {
+ sb.append("es");
+ }
+ }
+ if(patchCount>0&& otherCount>0) {
+ sb.append(", ");
+ }
+ if(otherCount>0) {
+ sb.append(otherCount);
+ sb.append(" other attachment");
+ if(otherCount>1) {
+ sb.append("s");
+ }
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public Rating getResult() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getPerson() {
+ //TODO
+ return "FIXME";
+ }
+ public boolean hasReviewSubTasks() {
+ for (ITreeNode node :getChildren()) {
+ if(node instanceof ReviewScopeNode)
+ return true;
+ else if (node instanceof TaskNode)
+ if(((TaskNode)node).hasReviewSubTasks())
+ return true;
+ }
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskProperties.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskProperties.java
new file mode 100644
index 00000000..d93259e3
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/TaskProperties.java
@@ -0,0 +1,181 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.core.internal;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import org.eclipse.core.runtime.Assert;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.mylyn.reviews.tasks.core.Attachment;
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.reviews.tasks.core.TaskComment;
+import org.eclipse.mylyn.tasks.core.TaskRepository;
+import org.eclipse.mylyn.tasks.core.data.ITaskDataManager;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
+/**
+ *
+ * @author mattk
+ *
+ */
+public class TaskProperties implements ITaskProperties {
+ private ITaskDataManager manager;
+ private TaskData taskData;
+
+ public TaskProperties(ITaskDataManager manager, TaskData taskData) {
+ Assert.isNotNull(manager);
+ Assert.isNotNull(taskData);
+ this.taskData = taskData;
+ this.manager = manager;
+ }
+
+ @Override
+ public String getDescription() {
+ return taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION)
+ .getValue();
+ }
+
+ @Override
+ public String getAssignedTo() {
+ return taskData.getRoot()
+ .getMappedAttribute(TaskAttribute.USER_ASSIGNED).getValue();
+ }
+
+ @Override
+ public List<Attachment> getAttachments() {
+ List<TaskAttribute> attachments = taskData.getAttributeMapper()
+ .getAttributesByType(taskData, TaskAttribute.TYPE_ATTACHMENT);
+ ArrayList<Attachment> list = new ArrayList<Attachment>();
+ for (TaskAttribute att : attachments) {
+ list.add(new Attachment(
+ this,
+ attributeValue(att, TaskAttribute.ATTACHMENT_FILENAME),
+ attributeValue(att, TaskAttribute.ATTACHMENT_AUTHOR),
+ attributeValue(att, TaskAttribute.ATTACHMENT_DATE),
+ taskData.getAttributeMapper()
+ .getBooleanValue(
+ att.getMappedAttribute(TaskAttribute.ATTACHMENT_IS_PATCH)),
+ attributeValue(att, TaskAttribute.ATTACHMENT_URL)));
+ }
+ return list;
+ }
+
+ private String attributeValue(TaskAttribute parent, String attribute) {
+ return parent.getMappedAttribute(attribute).getValue();
+ }
+
+ @Override
+ public List<TaskComment> getComments() {
+ List<TaskComment> comments = new ArrayList<TaskComment>();
+ for (TaskAttribute attr : taskData.getRoot().getAttributes().values()) {
+ if (attr.getId().startsWith(TaskAttribute.PREFIX_COMMENT)) {
+
+ TaskComment comment = new TaskComment();
+ comment.setAuthor(attr.getMappedAttribute(
+ TaskAttribute.COMMENT_AUTHOR).getValue());
+ comment.setText(attr.getMappedAttribute(
+ TaskAttribute.COMMENT_TEXT).getValue());
+ try {
+ comment.setDate(parseDate(attr.getMappedAttribute(
+ TaskAttribute.COMMENT_DATE).getValue()));
+ } catch (ParseException ex) {
+ ex.printStackTrace();
+ }
+ comments.add(comment);
+ }
+ }
+ return comments;
+ }
+
+ @Override
+ public String getNewCommentText() {
+ TaskAttribute attribute = this.taskData.getRoot().getMappedAttribute(
+ TaskAttribute.COMMENT_NEW);
+ if (attribute == null)
+ return null;
+
+ return attribute.getValue();
+ }
+
+ @Override
+ public void setNewCommentText(String value) {
+ TaskAttribute attribute = this.taskData.getRoot().getMappedAttribute(
+ TaskAttribute.COMMENT_NEW);
+ if (attribute == null) {
+ attribute = this.taskData.getRoot().createMappedAttribute(
+ TaskAttribute.COMMENT_NEW);
+ }
+ attribute.setValue(value);
+ }
+
+ private Date parseDate(String dateString) throws ParseException {
+ return new SimpleDateFormat("yyyy-mm-dd hh:MM").parse(dateString);
+ }
+
+ public static ITaskProperties fromTaskData(ITaskDataManager manager,
+ TaskData taskData) {
+ return new TaskProperties(manager, taskData);
+ }
+
+ @Override
+ public ITaskProperties loadFor(String taskId) throws CoreException {
+ TaskData td = manager.getTaskData(
+ new TaskRepository(taskData.getConnectorKind(), taskData
+ .getRepositoryUrl()), taskId);
+ return new TaskProperties(manager, td);
+ }
+
+ @Override
+ public String getTaskId() {
+ return taskData.getTaskId();
+ }
+
+ @Override
+ public void setDescription(String description) {
+ setValue(TaskAttribute.DESCRIPTION, description);
+ }
+
+ private void setValue(String mappedAttributeName, String value) {
+ TaskAttribute attribute = taskData.getRoot().getMappedAttribute(
+ mappedAttributeName);
+ if (attribute == null) {
+ attribute = taskData.getRoot().createMappedAttribute(
+ mappedAttributeName);
+ }
+ attribute.setValue(value);
+ }
+
+ @Override
+ public void setSummary(String summary) {
+ taskData.getRoot().getMappedAttribute(TaskAttribute.SUMMARY)
+ .setValue(summary);
+ }
+
+ @Override
+ public void setAssignedTo(String assignee) {
+ taskData.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED)
+ .setValue(assignee);
+ }
+
+ @Override
+ public String getRepositoryUrl() {
+ return taskData.getRepositoryUrl();
+ }
+
+ @Override
+ public String getReporter() {
+ return attributeValue(taskData.getRoot(),TaskAttribute.USER_REPORTER);
+ }
+}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/GitPatchPathFindingStrategy.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/GitPatchPathFindingStrategy.java
similarity index 96%
rename from tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/GitPatchPathFindingStrategy.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/GitPatchPathFindingStrategy.java
index 4875e3ea..e40d2694 100644
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/GitPatchPathFindingStrategy.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/GitPatchPathFindingStrategy.java
@@ -8,7 +8,7 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.core;
+package org.eclipse.mylyn.reviews.tasks.core.patch;
import java.io.InputStreamReader;
import java.io.Reader;
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ITargetPathStrategy.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/ITargetPathStrategy.java
similarity index 94%
rename from tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ITargetPathStrategy.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/ITargetPathStrategy.java
index 78f355cc..d64d4f72 100644
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ITargetPathStrategy.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/ITargetPathStrategy.java
@@ -8,7 +8,7 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.core;
+package org.eclipse.mylyn.reviews.tasks.core.patch;
import org.eclipse.compare.patch.ReaderCreator;
import org.eclipse.core.runtime.IPath;
diff --git a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/SimplePathFindingStrategy.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/SimplePathFindingStrategy.java
similarity index 96%
rename from tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/SimplePathFindingStrategy.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/SimplePathFindingStrategy.java
index db3b871e..57400ad4 100644
--- a/tbr/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/SimplePathFindingStrategy.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/patch/SimplePathFindingStrategy.java
@@ -8,7 +8,7 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.core;
+package org.eclipse.mylyn.reviews.tasks.core.patch;
import java.io.InputStreamReader;
import java.io.Reader;
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.classpath b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.classpath
new file mode 100644
index 00000000..7e8449de
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.classpath
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="src-gen"/>
+ <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="output" path="bin"/>
+</classpath>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.project b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.project
new file mode 100644
index 00000000..27776feb
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.project
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.mylyn.reviews.tasks.dsl</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>
+ <buildCommand>
+ <name>org.eclipse.xtext.ui.shared.xtextBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.xtext.ui.shared.xtextNature</nature>
+ </natures>
+</projectDescription>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..acec93ef
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF
@@ -0,0 +1,31 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: org.eclipse.mylyn.reviews.tasks.dsl
+Bundle-Vendor: Mylyn Reviews Project
+Bundle-Version: 0.0.1.qualifier
+Bundle-SymbolicName: org.eclipse.mylyn.reviews.tasks.dsl;singleton:=true
+Bundle-ActivationPolicy: lazy
+Require-Bundle: org.eclipse.xtext,
+ org.eclipse.xtext.generator;resolution:=optional,
+ org.apache.commons.logging;resolution:=optional,
+ org.eclipse.emf.codegen.ecore;resolution:=optional,
+ org.eclipse.emf.mwe.utils;resolution:=optional,
+ org.eclipse.emf.mwe2.launch;resolution:=optional,
+ com.ibm.icu;resolution:=optional,
+ org.eclipse.xtext.xtend;resolution:=optional,
+ org.eclipse.xtext.util,
+ org.eclipse.emf.ecore,
+ org.eclipse.emf.common,
+ org.antlr.runtime
+Import-Package: org.apache.log4j
+Bundle-RequiredExecutionEnvironment: J2SE-1.5
+Export-Package: org.eclipse.mylyn.reviews.tasks.dsl,
+ org.eclipse.mylyn.reviews.tasks.dsl.parseTreeConstruction,
+ org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr,
+ org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr.internal,
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl,
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.impl,
+ org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.util,
+ org.eclipse.mylyn.reviews.tasks.dsl.services,
+ org.eclipse.mylyn.reviews.tasks.dsl.validation
+
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/build.properties b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/build.properties
new file mode 100644
index 00000000..e10dcceb
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/build.properties
@@ -0,0 +1,5 @@
+source.. = src/,\
+ src-gen/
+bin.includes = META-INF/,\
+ .,\
+ plugin.xml
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml
new file mode 100644
index 00000000..8881d7bf
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+
+<plugin>
+
+ <extension point="org.eclipse.emf.ecore.generated_package">
+ <package
+ uri = "http://www.eclipse.org/mylyn/reviews/tasks/dsl/ReviewDsl"
+ class = "org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewDslPackage"
+ genModel = "org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.genmodel" />
+
+ </extension>
+
+
+
+
+
+</plugin>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml_gen b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml_gen
new file mode 100644
index 00000000..8881d7bf
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml_gen
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.0"?>
+
+<plugin>
+
+ <extension point="org.eclipse.emf.ecore.generated_package">
+ <package
+ uri = "http://www.eclipse.org/mylyn/reviews/tasks/dsl/ReviewDsl"
+ class = "org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewDslPackage"
+ genModel = "org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.genmodel" />
+
+ </extension>
+
+
+
+
+
+</plugin>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/GenerateReviewDsl.mwe2 b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/GenerateReviewDsl.mwe2
new file mode 100644
index 00000000..06d08ac7
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/GenerateReviewDsl.mwe2
@@ -0,0 +1,100 @@
+module org.eclipse.mylyn.reviews.tasks.dsl.ReviewDsl
+
+import org.eclipse.emf.mwe.utils.*
+import org.eclipse.xtext.generator.*
+import org.eclipse.xtext.ui.generator.*
+
+var grammarURI = "classpath:/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext"
+var file.extensions = "review-dsl"
+var projectName = "org.eclipse.mylyn.reviews.tasks.dsl"
+var runtimeProject = "../${projectName}"
+
+Workflow {
+ bean = StandaloneSetup {
+ platformUri = "${runtimeProject}/.."
+ }
+
+ component = DirectoryCleaner {
+ directory = "${runtimeProject}/src-gen"
+ }
+
+ component = DirectoryCleaner {
+ directory = "${runtimeProject}.ui/src-gen"
+ }
+
+ component = Generator {
+ pathRtProject = runtimeProject
+ pathUiProject = "${runtimeProject}.ui"
+ projectNameRt = projectName
+ projectNameUi = "${projectName}.ui"
+ language = {
+ uri = grammarURI
+ fileExtensions = file.extensions
+
+ // Java API to access grammar elements (required by several other fragments)
+ fragment = grammarAccess.GrammarAccessFragment {}
+
+ // generates Java API for the generated EPackages
+ fragment = ecore.EcoreGeneratorFragment {
+ // referencedGenModels = "uri to genmodel, uri to next genmodel"
+ }
+
+ // the serialization component
+ fragment = parseTreeConstructor.ParseTreeConstructorFragment {}
+
+ // a custom ResourceFactory for use with EMF
+ fragment = resourceFactory.ResourceFactoryFragment {
+ fileExtensions = file.extensions
+ }
+
+ // The antlr parser generator fragment.
+ fragment = parser.antlr.XtextAntlrGeneratorFragment {
+ // options = {
+ // backtrack = true
+ // }
+ }
+
+ // java-based API for validation
+ fragment = validation.JavaValidatorFragment {
+ composedCheck = "org.eclipse.xtext.validation.ImportUriValidator"
+ composedCheck = "org.eclipse.xtext.validation.NamesAreUniqueValidator"
+ // registerForImportedPackages = true
+ }
+
+ // scoping and exporting API
+ // fragment = scoping.ImportURIScopingFragment {}
+ // fragment = exporting.SimpleNamesFragment {}
+
+ // scoping and exporting API
+ fragment = scoping.ImportNamespacesScopingFragment {}
+ fragment = exporting.QualifiedNamesFragment {}
+ fragment = builder.BuilderIntegrationFragment {}
+
+ // formatter API
+ fragment = formatting.FormatterFragment {}
+
+ // labeling API
+ fragment = labeling.LabelProviderFragment {}
+
+ // outline API
+ fragment = outline.TransformerFragment {}
+ fragment = outline.OutlineNodeAdapterFactoryFragment {}
+ fragment = outline.QuickOutlineFragment {}
+
+ // quickfix API
+ fragment = quickfix.QuickfixProviderFragment {}
+
+ // content assist API
+ fragment = contentAssist.JavaBasedContentAssistFragment {}
+
+ // generates a more lightweight Antlr parser and lexer tailored for content assist
+ fragment = parser.antlr.XtextAntlrUiGeneratorFragment {}
+
+ // project wizard (optional)
+ // fragment = projectWizard.SimpleProjectWizardFragment {
+ // generatorProjectName = "${projectName}.generator"
+ // modelFileExtension = file.extensions
+ // }
+ }
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext
new file mode 100644
index 00000000..1a3e41c6
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext
@@ -0,0 +1,50 @@
+grammar org.eclipse.mylyn.reviews.tasks.dsl.ReviewDsl with org.eclipse.xtext.common.Terminals
+
+generate reviewDsl "http://www.eclipse.org/mylyn/reviews/tasks/dsl/ReviewDsl"
+
+Model:
+ ReviewResult | ReviewScope;
+
+ReviewResult:
+ "Review result:" result=ResultEnum
+ ("Comment:" comment=STRING )? (filecomments+=FileComment)* ;
+
+enum ResultEnum:
+ passed="PASSED" | failed="FAILED"
+ | todo="TODO" | warning="WARNING";
+
+FileComment:
+ "File" path=STRING ":" comment=STRING?
+ linecomments+=LineComment*;
+
+LineComment:
+ "Line " start=INT ("-" end=INT)? ":" comment=STRING;
+
+ReviewScope:
+ "Review scope:"
+ (
+ scope+=ReviewScopeItem
+ )+;
+
+//ChangesetDef:
+// ("Changeset" revision=INT " from " repoType=ID url=STRING );
+ReviewScopeItem:
+ ResourceDef|PatchDef;
+ResourceDef:
+ ("Resource" source=Source );
+
+PatchDef:
+ ("Patch" source=Source );
+
+Source:
+ AttachmentSource;
+
+AttachmentSource:
+ "from Attachment" filename=STRING
+ "by" author=STRING
+ "on" createdDate=STRING
+ "of task" taskId=TASK_ID;
+
+
+terminal TASK_ID : ('a'..'z'|'A'..'Z'|'_'|'-'|'0'..'9')*;
+
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslRuntimeModule.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslRuntimeModule.java
new file mode 100644
index 00000000..7bf5ed9f
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslRuntimeModule.java
@@ -0,0 +1,12 @@
+/*
+ * generated by Xtext
+ */
+package org.eclipse.mylyn.reviews.tasks.dsl;
+
+
+/**
+ * Use this class to register components to be used at runtime / without the Equinox extension registry.
+ */
+public class ReviewDslRuntimeModule extends org.eclipse.mylyn.reviews.tasks.dsl.AbstractReviewDslRuntimeModule {
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslStandaloneSetup.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslStandaloneSetup.java
new file mode 100644
index 00000000..e5caf580
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslStandaloneSetup.java
@@ -0,0 +1,16 @@
+
+package org.eclipse.mylyn.reviews.tasks.dsl;
+
+import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslStandaloneSetupGenerated;
+
+/**
+ * Initialization support for running Xtext languages
+ * without equinox extension registry
+ */
+public class ReviewDslStandaloneSetup extends ReviewDslStandaloneSetupGenerated{
+
+ public static void doSetup() {
+ new ReviewDslStandaloneSetup().createInjectorAndDoEMFRegistration();
+ }
+}
+
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java
new file mode 100644
index 00000000..81a99589
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java
@@ -0,0 +1,32 @@
+/*
+ * generated by Xtext
+ */
+package org.eclipse.mylyn.reviews.tasks.dsl.formatting;
+
+import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewDslPackage;
+import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter;
+import org.eclipse.xtext.formatting.impl.FormattingConfig;
+
+/**
+ * This class contains custom formatting description.
+ *
+ * see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#formatting
+ * on how and when to use it
+ *
+ * Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an example
+ */
+public class ReviewDslFormatter extends AbstractDeclarativeFormatter {
+
+ @Override
+ protected void configureFormatting(FormattingConfig c) {
+ c.setLinewrap(1).after(ReviewDslPackage.eINSTANCE.getReviewScope());
+ c.setIndentationIncrement().before(ReviewDslPackage.eINSTANCE.getReviewScopeItem());
+ c.setIndentationDecrement().after(ReviewDslPackage.eINSTANCE.getReviewScopeItem());
+ c.setLinewrap(1).after(ReviewDslPackage.eINSTANCE.getReviewScopeItem());
+
+ // c.setLinewrap(1, 1, 2).before(ReviewDslPackage.eINSTANCE.getFileComment());
+// c.setLinewrap(1, 1, 2).before(ReviewDslPackage.eINSTANCE.getLineComment());
+// c.setLinewrap(1, 1, 2).before(ReviewDslPackage.eINSTANCE.getResourceDef());
+// c.setLinewrap(1, 1, 2).before(ReviewDslPackage.eINSTANCE.getPatchDef());
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/scoping/ReviewDslScopeProvider.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/scoping/ReviewDslScopeProvider.java
new file mode 100644
index 00000000..b763d9b4
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/scoping/ReviewDslScopeProvider.java
@@ -0,0 +1,17 @@
+/*
+ * generated by Xtext
+ */
+package org.eclipse.mylyn.reviews.tasks.dsl.scoping;
+
+import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider;
+
+/**
+ * This class contains custom scoping description.
+ *
+ * see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#scoping
+ * on how and when to use it
+ *
+ */
+public class ReviewDslScopeProvider extends AbstractDeclarativeScopeProvider {
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/validation/ReviewDslJavaValidator.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/validation/ReviewDslJavaValidator.java
new file mode 100644
index 00000000..1ebad0a8
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/validation/ReviewDslJavaValidator.java
@@ -0,0 +1,13 @@
+package org.eclipse.mylyn.reviews.tasks.dsl.validation;
+
+
+public class ReviewDslJavaValidator extends AbstractReviewDslJavaValidator {
+
+// @Check
+// public void checkGreetingStartsWithCapital(Greeting greeting) {
+// if (!Character.isUpperCase(greeting.getName().charAt(0))) {
+// warning("Name should start with a capital", MyDslPackage.GREETING__NAME);
+// }
+// }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/.classpath b/tbr/org.eclipse.mylyn.reviews.tasks.ui/.classpath
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/.classpath
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/.classpath
diff --git a/tbr/org.eclipse.mylyn.reviews.core/.project b/tbr/org.eclipse.mylyn.reviews.tasks.ui/.project
similarity index 94%
rename from tbr/org.eclipse.mylyn.reviews.core/.project
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/.project
index 7b0cd529..643061eb 100644
--- a/tbr/org.eclipse.mylyn.reviews.core/.project
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/.project
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
- <name>org.eclipse.mylyn.reviews.core</name>
+ <name>org.eclipse.mylyn.reviews.tasks.ui</name>
<comment></comment>
<projects>
</projects>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF
new file mode 100644
index 00000000..3d08a164
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF
@@ -0,0 +1,18 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Mylyn Reviews UI (Incubation)
+Bundle-SymbolicName: org.eclipse.mylyn.reviews.tasks.ui;singleton:=true
+Bundle-Version: 0.0.1
+Bundle-Activator: org.eclipse.mylyn.reviews.tasks.ui.ReviewsUiPlugin
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ org.eclipse.mylyn.tasks.ui;bundle-version="3.4.0",
+ org.eclipse.ui.forms;bundle-version="3.4.1",
+ org.eclipse.mylyn.tasks.core;bundle-version="3.3.0",
+ org.eclipse.compare;bundle-version="3.5.0",
+ org.eclipse.core.resources;bundle-version="3.6.0",
+ org.eclipse.mylyn.reviews.tasks.core;bundle-version="0.0.1"
+Bundle-ActivationPolicy: lazy
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: org.eclipse.mylyn.reviews.tasks.ui,
+ org.eclipse.mylyn.reviews.tasks.ui.editors
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/about.html b/tbr/org.eclipse.mylyn.reviews.tasks.ui/about.html
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/about.html
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/about.html
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/about_files/CreativeCommons-Attribution2.5-Legalcode.html b/tbr/org.eclipse.mylyn.reviews.tasks.ui/about_files/CreativeCommons-Attribution2.5-Legalcode.html
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/about_files/CreativeCommons-Attribution2.5-Legalcode.html
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/about_files/CreativeCommons-Attribution2.5-Legalcode.html
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/build.properties b/tbr/org.eclipse.mylyn.reviews.tasks.ui/build.properties
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/build.properties
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/build.properties
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/addition.gif b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/addition.gif
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/addition.gif
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/addition.gif
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/filter_ps.gif b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/filter_ps.gif
new file mode 100644
index 00000000..a4c9e60e
Binary files /dev/null and b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/filter_ps.gif differ
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/maximize.png b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/maximize.png
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/maximize.png
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/maximize.png
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/obstructed.gif b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/obstructed.gif
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/obstructed.gif
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/obstructed.gif
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/review_failed.png b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/review_failed.png
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/review_failed.png
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/review_failed.png
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/review_none.png b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/review_none.png
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/review_none.png
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/review_none.png
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/review_passed.png b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/review_passed.png
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/review_passed.png
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/review_passed.png
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/review_warning.png b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/review_warning.png
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/review_warning.png
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/review_warning.png
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews16.gif b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/reviews16.gif
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/reviews16.gif
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/reviews16.gif
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews24.gif b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/reviews24.gif
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/reviews24.gif
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/reviews24.gif
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/icons/reviews32.gif b/tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/reviews32.gif
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/icons/reviews32.gif
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/icons/reviews32.gif
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/plugin.xml b/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml
similarity index 54%
rename from tbr/org.eclipse.mylyn.reviews.ui/plugin.xml
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml
index 61482a16..12faedae 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/plugin.xml
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml
@@ -11,15 +11,6 @@
-->
<plugin>
- <extension
- point="org.eclipse.ui.editors">
- <editor
- class="org.eclipse.mylyn.reviews.ui.editors.ReviewEditor"
- icon="icons/reviews32.gif"
- id="org.eclipse.mylyn.reviews.ui.editors.ReviewEditor"
- name="Mylyn Reviews Editor">
- </editor>
- </extension>
<extension
point="org.eclipse.ui.popupMenus">
<objectContribution
@@ -27,24 +18,20 @@
id="org.eclipse.mylyn.reviews.ui.objectContribution1"
objectClass="org.eclipse.mylyn.tasks.core.ITaskAttachment">
<action
- class="org.eclipse.mylyn.reviews.ui.CreateReviewAction"
+ class="org.eclipse.mylyn.reviews.tasks.ui.CreateReviewActionFromAttachment"
enablesFor="*"
- id="org.eclipse.mylyn.reviews.ui.create_review_from_attachment"
+ id="org.eclipse.mylyn.reviews.tasks.ui.create_review_from_attachment"
label="Create Review from Attachment"
tooltip="Create a new review from this attachment">
</action>
</objectContribution>
</extension>
<extension
- point="org.eclipse.mylyn.tasks.ui.taskEditorPageContribution">
- <partAdvisor
- class="org.eclipse.mylyn.reviews.ui.editors.ReviewTaskEditorPartAdvisor"
- id="org.eclipse.mylyn.reviews.ui.reviewPart">
- </partAdvisor>
- <partAdvisor
- class="org.eclipse.mylyn.reviews.ui.editors.ReviewSummaryPartConfigurer"
- id="org.eclipse.mylyn.reviews.ui.reviewSummaryPart">
- </partAdvisor>
+ point="org.eclipse.mylyn.tasks.ui.editors">
+ <pageFactory
+ class="org.eclipse.mylyn.reviews.tasks.ui.editors.ReviewTaskEditorPageFactory"
+ id="org.eclipse.mylyn.reviews.ui.pageFactory2">
+ </pageFactory>
</extension>
</plugin>
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java
new file mode 100644
index 00000000..0b5a77ff
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java
@@ -0,0 +1,131 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.ui;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
+import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
+import org.eclipse.mylyn.reviews.tasks.core.Attachment;
+import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper;
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.reviews.tasks.core.PatchScopeItem;
+import org.eclipse.mylyn.reviews.tasks.core.ResourceScopeItem;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewScope;
+import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewsUtil;
+import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties;
+import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
+import org.eclipse.mylyn.tasks.core.ITaskAttachment;
+import org.eclipse.mylyn.tasks.core.TaskRepository;
+import org.eclipse.mylyn.tasks.core.data.ITaskDataManager;
+import org.eclipse.mylyn.tasks.core.data.TaskData;
+import org.eclipse.mylyn.tasks.core.data.TaskMapper;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+import org.eclipse.ui.IActionDelegate;
+
+public class CreateReviewActionFromAttachment extends Action implements
+ IActionDelegate {
+
+ private List<ITaskAttachment> selection2;
+
+ public void run(IAction action) {
+ try {
+ // FIXME move common creation to a subclass
+ ITaskAttachment taskAttachment = selection2.get(0);
+
+ TaskRepository taskRepository = taskAttachment.getTaskRepository();
+ ITaskDataManager manager = TasksUi.getTaskDataManager();
+ TaskData parentTaskData = manager.getTaskData(taskAttachment
+ .getTask());
+ ITaskProperties parentTask= TaskProperties.fromTaskData(manager, parentTaskData);
+
+ TaskMapper initializationData = new TaskMapper(parentTaskData);
+ IReviewMapper taskMapper = ReviewsUiPlugin.getMapper();
+
+ TaskData taskData = TasksUiInternal.createTaskData(taskRepository,
+ initializationData, null, new NullProgressMonitor());
+ AbstractRepositoryConnector connector = TasksUiPlugin
+ .getConnector(taskRepository.getConnectorKind());
+
+ connector.getTaskDataHandler().initializeSubTaskData(
+ taskRepository, taskData, parentTaskData,
+ new NullProgressMonitor());
+
+ ITaskProperties taskProperties = TaskProperties.fromTaskData(
+ manager, taskData);
+ taskProperties.setSummary("[review] " + parentTask.getDescription());
+
+ String reviewer = taskRepository.getUserName();
+ taskProperties.setAssignedTo(reviewer);
+
+ initTaskProperties(taskMapper, taskProperties,parentTask);
+
+ TasksUiInternal.createAndOpenNewTask(taskData);
+ } catch (CoreException e) {
+ throw new RuntimeException(e);
+ }
+
+ }
+
+ private void initTaskProperties(IReviewMapper taskMapper,
+ ITaskProperties taskProperties,ITaskProperties parentTask) {
+ ReviewScope scope = new ReviewScope();
+ for (ITaskAttachment taskAttachment : selection2) {
+ // FIXME date from task attachment
+ Attachment attachment = ReviewsUtil
+ .findAttachment(taskAttachment.getFileName(),
+ taskAttachment.getAuthor().getPersonId(),
+ taskAttachment.getCreationDate().toString(),
+ parentTask);
+ if (attachment.isPatch()) {
+ scope.addScope(new PatchScopeItem(attachment));
+ } else {
+ scope.addScope(new ResourceScopeItem(attachment));
+ }
+ }
+ taskMapper.mapScopeToTask(scope, taskProperties);
+ }
+
+ public void selectionChanged(IAction action, ISelection selection) {
+ action.setEnabled(true);
+ if (selection instanceof IStructuredSelection) {
+ if (selection.isEmpty()) {
+ action.setEnabled(false);
+ return;
+ }
+ IStructuredSelection structuredSelection = (IStructuredSelection) selection;
+ selection2 = new ArrayList<ITaskAttachment>();
+ @SuppressWarnings("unchecked")
+ Iterator<ITaskAttachment> iterator = structuredSelection.iterator();
+ TaskRepository taskRepository = null;
+ while (iterator.hasNext()) {
+ ITaskAttachment attachment = iterator.next();
+ if (taskRepository == null) {
+ taskRepository = attachment.getTaskRepository();
+ } else if (!taskRepository.equals(attachment
+ .getTaskRepository())) {
+ action.setEnabled(false);
+ }
+
+ selection2.add(attachment);
+ }
+ }
+ }
+
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Images.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Images.java
similarity index 95%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Images.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Images.java
index f6cae175..f5c4c8f5 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Images.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Images.java
@@ -8,7 +8,7 @@
* Contributors:
* Christoph Mayerhofer (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
+package org.eclipse.mylyn.reviews.tasks.ui;
import java.net.URL;
@@ -53,6 +53,8 @@ public class Images {
"obstructed.gif"); //$NON-NLS-1$
public static final ImageDescriptor MAXIMIZE = create(ICONS_PATH,
"maximize.png"); //$NON-NLS-1$
+ public static final ImageDescriptor FILTER = create(ICONS_PATH,
+ "filter_ps.gif"); //$NON-NLS-1$
protected static ImageDescriptor create(String prefix, String name) {
return ImageDescriptor.createFromURL(makeIconURL(prefix, name));
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Messages.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Messages.java
similarity index 93%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Messages.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Messages.java
index 56a075c8..eaf36f61 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/Messages.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Messages.java
@@ -8,7 +8,7 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
+package org.eclipse.mylyn.reviews.tasks.ui;
import org.eclipse.osgi.util.NLS;
@@ -16,7 +16,7 @@
* @author Kilian Matt
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.ui.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.tasks.ui.messages"; //$NON-NLS-1$
public static String CreateTask_Success;
public static String CreateTask_Title;
public static String CreateTask_UploadingAttachment;
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewUiUtils.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewUiUtils.java
new file mode 100644
index 00000000..bbc4276d
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewUiUtils.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.ui;
+
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
+/**
+ *
+ * @author mattk
+ *
+ */
+public class ReviewUiUtils {
+ public static void openTaskInMylyn(ITaskProperties task) {
+ TasksUiUtil.openTask(task.getRepositoryUrl(), task.getTaskId(), null);
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewsUiPlugin.java
similarity index 66%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewsUiPlugin.java
index 64343541..8651c34c 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewsUiPlugin.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewsUiPlugin.java
@@ -8,13 +8,11 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
+package org.eclipse.mylyn.reviews.tasks.ui;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.mylyn.internal.tasks.ui.ITasksUiPreferenceConstants;
-import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
-import org.eclipse.mylyn.reviews.core.ReviewDataManager;
-import org.eclipse.mylyn.reviews.core.ReviewDataStore;
+import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper;
+import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewTaskMapper;
+import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewsUtil;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
@@ -31,7 +29,7 @@ public class ReviewsUiPlugin extends AbstractUIPlugin {
// The shared instance
private static ReviewsUiPlugin plugin;
- private static ReviewDataManager reviewDataManager;
+ private static ReviewTaskMapper mapper;
/**
* The constructor
@@ -50,17 +48,6 @@ public ReviewsUiPlugin() {
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
-
- String DIRECTORY_METADATA = ".metadata"; //$NON-NLS-1$
-
- String NAME_DATA_DIR = ".mylyn"; //$NON-NLS-1$
- String storeDir = ResourcesPlugin.getWorkspace().getRoot()
- .getLocation().toString()
- + '/' + DIRECTORY_METADATA + '/' + NAME_DATA_DIR;
- ReviewDataStore store = new ReviewDataStore(storeDir);
- reviewDataManager = new ReviewDataManager(store,
- TasksUiPlugin.getTaskDataManager(),
- TasksUiPlugin.getRepositoryModel());
}
/*
@@ -85,8 +72,11 @@ public static ReviewsUiPlugin getDefault() {
return plugin;
}
- public static ReviewDataManager getDataManager() {
- return reviewDataManager;
+ public static IReviewMapper getMapper() {
+ if (mapper == null) {
+ mapper=ReviewsUtil.createMapper();
+ }
+ return mapper;
}
}
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/AbstractReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/AbstractReviewTaskEditorPart.java
new file mode 100644
index 00000000..baa06c5f
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/AbstractReviewTaskEditorPart.java
@@ -0,0 +1,30 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.ui.editors;
+
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
+
+public abstract class AbstractReviewTaskEditorPart extends AbstractTaskEditorPart{
+
+ private ReviewTaskEditorPage reviewPage;
+public AbstractReviewTaskEditorPart() {
+super();
+}
+ @Override
+ public void initialize(AbstractTaskEditorPage taskEditorPage) {
+ super.initialize(taskEditorPage);
+ reviewPage = (ReviewTaskEditorPage)taskEditorPage;
+ }
+ protected ReviewTaskEditorPage getReviewPage() {
+ return reviewPage;
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/Messages.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/Messages.java
similarity index 96%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/Messages.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/Messages.java
index 288a7ee0..16b59e14 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/Messages.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/Messages.java
@@ -8,7 +8,7 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
+package org.eclipse.mylyn.reviews.tasks.ui.editors;
import org.eclipse.osgi.util.NLS;
@@ -16,7 +16,7 @@
* @author Kilian Matt
*/
public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.ui.editors.messages"; //$NON-NLS-1$
+ private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.tasks.ui.editors.messages"; //$NON-NLS-1$
public static String CreateReviewTaskEditorPageFactory_Reviews;
public static String CreateReviewTaskEditorPart_Patches;
public static String CreateReviewTaskEditorPart_Create_Review;
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java
new file mode 100644
index 00000000..475a9279
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java
@@ -0,0 +1,254 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.ui.editors;
+
+import java.util.Collection;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.ToolBarManager;
+import org.eclipse.jface.viewers.DoubleClickEvent;
+import org.eclipse.jface.viewers.IDoubleClickListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.TreeViewerColumn;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties;
+import org.eclipse.mylyn.reviews.tasks.core.internal.ITreeNode;
+import org.eclipse.mylyn.reviews.tasks.core.internal.TaskNode;
+import org.eclipse.mylyn.reviews.tasks.ui.Images;
+import org.eclipse.mylyn.reviews.tasks.ui.ReviewUiUtils;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+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.Tree;
+import org.eclipse.ui.forms.widgets.ExpandableComposite;
+import org.eclipse.ui.forms.widgets.FormToolkit;
+import org.eclipse.ui.forms.widgets.Section;
+
+/*
+ * @author Kilian Matt
+ */
+public class ReviewSummaryTaskEditorPart extends AbstractReviewTaskEditorPart {
+
+ public static final String ID_PART_REVIEWSUMMARY = "org.eclipse.mylyn.reviews.ui.editors.parts.reviewsummary"; //$NON-NLS-1$
+ private TreeViewer reviewResults;
+ private ScopeViewerFilter scopeViewerFilter = new ScopeViewerFilter();
+
+ public ReviewSummaryTaskEditorPart() {
+ setPartName(Messages.ReviewSummaryTaskEditorPart_Partname);
+ }
+
+ @Override
+ public void createControl(final Composite parent, FormToolkit toolkit) {
+ Section summarySection = createSection(parent, toolkit,
+ ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
+ | ExpandableComposite.EXPANDED);
+ summarySection.setLayout(new FillLayout(SWT.HORIZONTAL));
+ summarySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
+ true));
+ Composite reviewResultsComposite = toolkit
+ .createComposite(summarySection);
+ toolkit.paintBordersFor(reviewResultsComposite);
+ reviewResultsComposite.setLayout(new GridLayout(1, false));
+
+ reviewResults = createResultsViewer(reviewResultsComposite, toolkit);
+ reviewResults.getControl().setLayoutData(
+ new GridData(SWT.FILL, SWT.FILL, true, true));
+
+ try {
+ ITreeNode rootNode = getReviewPage().getReviewResults(
+ new NullProgressMonitor());
+ reviewResults.setInput(new Object[] { rootNode });
+ reviewResults.expandAll();
+ } catch (CoreException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ summarySection.setText("Review Summary ");
+ summarySection.setClient(reviewResultsComposite);
+ setSection(toolkit, summarySection);
+ }
+
+ private TreeViewerColumn createColumn(TreeViewer tree, String columnTitle) {
+ TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT);
+ column.getColumn().setText(columnTitle);
+ column.getColumn().setWidth(100);
+ column.getColumn().setResizable(true);
+ return column;
+ }
+
+ private TreeViewer createResultsViewer(Composite reviewResultsComposite,
+ FormToolkit toolkit) {
+ Tree tree = new Tree(reviewResultsComposite, SWT.SINGLE
+ | SWT.FULL_SELECTION);
+ tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
+ tree.setLinesVisible(true);
+ tree.setHeaderVisible(true);
+ for (int i = 0; i < tree.getColumnCount(); i++) {
+ tree.getColumn(i).pack();
+ }
+ tree.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
+
+ TreeViewer reviewResults = new TreeViewer(tree);
+ createColumn(reviewResults, "Task");
+ createColumn(reviewResults,
+ Messages.ReviewSummaryTaskEditorPart_Header_Result);
+ createColumn(reviewResults, "Description");
+ createColumn(reviewResults, "Who");
+
+ reviewResults.setContentProvider(new ReviewResultContentProvider());
+
+ reviewResults.setLabelProvider(new TableLabelProvider() {
+ private static final int COLUMN_TASK_ID = 0;
+ private static final int COLUMN_RESULT = 1;
+ private static final int COLUMN_DESCRIPTION = 2;
+ private static final int COLUMN_WHO = 3;
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ if (columnIndex == COLUMN_RESULT) {
+ ITreeNode node = (ITreeNode) element;
+ if (node.getResult() == null)
+ return null;
+ switch (node.getResult()) {
+ case FAIL:
+ return Images.REVIEW_RESULT_FAILED.createImage();
+ case WARNING:
+ return Images.REVIEW_RESULT_WARNING.createImage();
+ case PASSED:
+ return Images.REVIEW_RESULT_PASSED.createImage();
+ case TODO:
+ return Images.REVIEW_RESULT_NONE.createImage();
+
+ }
+ }
+ return null;
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+
+ ITreeNode node = (ITreeNode) element;
+ switch (columnIndex) {
+ case COLUMN_TASK_ID:
+ return node.getTaskId();
+ case COLUMN_RESULT:
+ return node.getResult() != null ? node.getResult().name()
+ : "";
+ case COLUMN_DESCRIPTION:
+ return node.getDescription();
+ case COLUMN_WHO:
+ return node.getPerson();
+ default:
+ return null;
+ }
+ }
+
+ });
+ reviewResults.addDoubleClickListener(new IDoubleClickListener() {
+
+ public void doubleClick(DoubleClickEvent event) {
+ if (!event.getSelection().isEmpty()) {
+ ITaskProperties task = ((ITreeNode) ((IStructuredSelection) event
+ .getSelection()).getFirstElement()).getTask();
+ ReviewUiUtils.openTaskInMylyn(task);
+ }
+ }
+ });
+ return reviewResults;
+ }
+
+ private final class ScopeViewerFilter extends ViewerFilter {
+ @Override
+ public boolean select(Viewer viewer, Object parentElement,
+ Object element) {
+ if (element instanceof TaskNode) {
+ return ((TaskNode) element).hasReviewSubTasks();
+ }
+ return true;
+ }
+ }
+
+ private static class ReviewResultContentProvider implements
+ ITreeContentProvider {
+
+ @Override
+ public Object[] getChildren(Object parentElement) {
+ return ((ITreeNode) parentElement).getChildren().toArray();
+ }
+
+ @Override
+ public Object getParent(Object element) {
+ return ((ITreeNode) element).getParent();
+ }
+
+ @Override
+ public boolean hasChildren(Object element) {
+ return !((ITreeNode) element).getChildren().isEmpty();
+ }
+
+ @Override
+ public void dispose() {
+ // nothing to do
+
+ }
+
+ @Override
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ // nothing to do
+ }
+
+ @Override
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof Object[]) {
+ return (Object[]) inputElement;
+ } else if (inputElement instanceof Collection<?>) {
+ return ((Collection<?>) inputElement).toArray();
+ }
+ return new Object[0];
+ }
+ }
+
+ @Override
+ protected void fillToolBar(ToolBarManager manager) {
+ Action toggleFiltering = new Action("Filter", SWT.TOGGLE) { //$NON-NLS-1$
+ @Override
+ public void run() {
+ enableFiltering(!isFiltering());
+ }
+ };
+ toggleFiltering.setImageDescriptor(Images.FILTER);
+ toggleFiltering.setToolTipText("Toogle Filtering");
+ toggleFiltering.setChecked(true);
+ enableFiltering(true);
+ manager.add(toggleFiltering);
+ super.fillToolBar(manager);
+ }
+
+ private boolean isFiltering() {
+ return reviewResults.getFilters() != null
+ && reviewResults.getFilters().length > 0;
+ }
+
+ private void enableFiltering(boolean enable) {
+ if (enable) {
+
+ reviewResults.setFilters(new ViewerFilter[] { scopeViewerFilter });
+ } else {
+ reviewResults.setFilters(new ViewerFilter[0]);
+ }
+ }
+}
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
new file mode 100644
index 00000000..657ed0a5
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java
@@ -0,0 +1,129 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.ui.editors;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.mylyn.internal.tasks.ui.editors.ToolBarButtonContribution;
+import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewScope;
+import org.eclipse.mylyn.reviews.tasks.core.internal.ITreeNode;
+import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewsUtil;
+import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties;
+import org.eclipse.mylyn.reviews.tasks.ui.ReviewsUiPlugin;
+import org.eclipse.mylyn.tasks.core.sync.SubmitJobEvent;
+import org.eclipse.mylyn.tasks.ui.TasksUi;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
+import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
+import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
+import org.eclipse.mylyn.tasks.ui.editors.TaskEditorPartDescriptor;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+
+/*
+ * @author Kilian Matt
+ */
+public class ReviewTaskEditorPage extends AbstractTaskEditorPage {
+ private ReviewScope scope;
+
+ public ReviewTaskEditorPage(TaskEditor editor) {
+ super(editor, getConnectorId(editor));
+ }
+
+ private static String getConnectorId(TaskEditor editor) {
+ return ((TaskEditorInput) editor.getEditorInput()).getTaskRepository()
+ .getConnectorKind();
+ }
+
+ @Override
+ public boolean needsSubmitButton() {
+ return true;
+ }
+
+ @Override
+ public void doSubmit() {
+ super.doSubmit();
+ }
+
+ @Override
+ protected void handleTaskSubmitted(SubmitJobEvent event) {
+ super.handleTaskSubmitted(event);
+ }
+
+ @Override
+ protected Set<TaskEditorPartDescriptor> createPartDescriptors() {
+ Set<TaskEditorPartDescriptor> taskDescriptors = new HashSet<TaskEditorPartDescriptor>();
+ taskDescriptors.add(new TaskEditorPartDescriptor(
+ ReviewTaskEditorPart.ID_PART_REVIEW) {
+ @Override
+ public AbstractTaskEditorPart createPart() {
+ return new ReviewTaskEditorPart();
+ }
+ });
+ taskDescriptors.add(new TaskEditorPartDescriptor(ReviewSummaryTaskEditorPart.ID_PART_REVIEWSUMMARY) {
+
+ @Override
+ public AbstractTaskEditorPart createPart() {
+ return new ReviewSummaryTaskEditorPart();
+ }
+ });
+
+ return taskDescriptors;
+ }
+
+ @Override
+ public void fillToolBar(IToolBarManager toolBarManager) {
+ ToolBarButtonContribution submitButtonContribution = new ToolBarButtonContribution(
+ "org.eclipse.mylyn.reviews.tasks.toolbars.submit") {
+
+ @Override
+ protected Control createButton(Composite parent) {
+ Button submitButton = new Button(parent, SWT.FLAT);
+ submitButton.setText("submit review"); //$NON-NLS-1$
+ submitButton.setBackground(null);
+ submitButton.addListener(SWT.Selection, new Listener() {
+ public void handleEvent(Event e) {
+ doSubmit();
+ }
+ });
+ return submitButton;
+ }
+ };
+ submitButtonContribution.marginLeft = 10;
+ toolBarManager.add(submitButtonContribution);
+ }
+
+ public ReviewScope getReviewScope() throws CoreException {
+ if (scope == null) {
+ IReviewMapper mapper = ReviewsUiPlugin.getMapper();
+ scope = mapper.mapTaskToScope(TaskProperties.fromTaskData(
+ TasksUi.getTaskDataManager(), getModel().getTaskData()));
+
+ }
+ return scope;
+ }
+
+ /* 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/ReviewTaskEditorPageFactory.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPageFactory.java
new file mode 100644
index 00000000..5e8f6fa3
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPageFactory.java
@@ -0,0 +1,56 @@
+/*******************************************************************************
+ * 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:
+ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.reviews.tasks.ui.editors;
+
+import org.eclipse.mylyn.reviews.tasks.ui.Images;
+import org.eclipse.mylyn.reviews.tasks.ui.Messages;
+import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory;
+import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
+import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.forms.editor.IFormPage;
+
+/*
+ * @author Kilian Matt
+ */
+public class ReviewTaskEditorPageFactory extends AbstractTaskEditorPageFactory {
+
+ @Override
+ public boolean canCreatePageFor(TaskEditorInput input) {
+ // TODO restrict reviews to non-new and non-local tasks
+ return true;
+ }
+
+ @Override
+ public IFormPage createPage(TaskEditor parentEditor) {
+ return new ReviewTaskEditorPage(parentEditor);
+ }
+
+ @Override
+ public Image getPageImage() {
+ return Images.SMALL_ICON.createImage();
+ }
+
+ @Override
+ public String getPageText() {
+ return Messages.ReviewTaskEditorPageFactory_PageTitle;
+ }
+
+ @Override
+ public int getPriority() {
+ return PRIORITY_ADDITIONS;
+ }
+
+ @Override
+ public String[] getConflictingIds(TaskEditorInput input) {
+ return new String[0];
+ }
+}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java
similarity index 58%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java
index d0279cfa..327e148d 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java
@@ -8,47 +8,48 @@
* Contributors:
* Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
+package org.eclipse.mylyn.reviews.tasks.ui.editors;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
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.patch.IFilePatch2;
-import org.eclipse.compare.patch.PatchConfiguration;
+import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.ISafeRunnable;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.SafeRunner;
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;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.mylyn.reviews.core.ReviewData;
-import org.eclipse.mylyn.reviews.core.ReviewsUtil;
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.Rating;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
-import org.eclipse.mylyn.reviews.ui.Images;
-import org.eclipse.mylyn.reviews.ui.ReviewDiffModel;
-import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
-import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
+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;
+import org.eclipse.mylyn.reviews.tasks.core.Rating;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewResult;
+import org.eclipse.mylyn.reviews.tasks.core.ReviewScope;
+import org.eclipse.mylyn.reviews.tasks.core.IReviewScopeItem;
+import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties;
+import org.eclipse.mylyn.reviews.tasks.ui.Images;
+import org.eclipse.mylyn.reviews.tasks.ui.ReviewsUiPlugin;
+import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.ui.TasksUi;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
@@ -59,6 +60,7 @@
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.Text;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
@@ -69,10 +71,13 @@
/*
* @author Kilian Matt
*/
-public class ReviewTaskEditorPart extends AbstractTaskEditorPart {
+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 ");
@@ -81,103 +86,85 @@ 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);
+ createColumn(fileList, "Group", 100);
+ createColumn(fileList, "Filename", 100);
+ fileList.getTree().setLinesVisible(true);
+ fileList.getTree().setHeaderVisible(true);
- TableLayout tableLayout = new TableLayout();
- tableLayout.addColumnData(new ColumnWeightData(100, true));
- fileList.getTable().setLayout(tableLayout);
-
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) {
- if (element instanceof ReviewDiffModel) {
- ReviewDiffModel diffModel = ((ReviewDiffModel) element);
-
- return diffModel.getFileName();
+ public String getColumnText(Object node, int columnIndex) {
+ Object element = ((TreeNode) node).getValue();
+ switch (columnIndex) {
+ case COLUMN_GROUP:
+ if (element instanceof IReviewScopeItem) {
+ return ((IReviewScopeItem) element).getDescription();
+ }
+ break;
+ case COLUMN_FILE:
+ if (element instanceof IReviewFile) {
+ 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 ReviewDiffModel) {
- ReviewDiffModel diffModel = ((ReviewDiffModel) element);
- if (diffModel.isNewFile()) {
+ 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();
}
- if (!diffModel.canReview()) {
+ 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(new IStructuredContentProvider() {
-
- public void inputChanged(Viewer viewer, Object oldInput,
- Object newInput) {
- }
-
- public void dispose() {
- }
-
- public Object[] getElements(Object inputElement) {
- // parse the patch and create our model for the table
- Patch patch = (Patch) inputElement;
- List<IFilePatch2> patches = patch.parse();
- ReviewDiffModel[] model = new ReviewDiffModel[patches.size()];
- int index = 0;
- for (IFilePatch2 currentPatch : patches) {
- final PatchConfiguration configuration = new PatchConfiguration();
- currentPatch.getTargetPath(configuration);
- model[index++] = new ReviewDiffModel(currentPatch,
- configuration);
-
- }
- return model;
- }
- });
+ 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 ReviewDiffModel) {
- final ReviewDiffModel diffModel = ((ReviewDiffModel) sel
- .getFirstElement());
- if (diffModel.canReview()) {
+ 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);
configuration.setRightEditable(false);
@@ -200,7 +187,7 @@ protected Object prepareInput(
IProgressMonitor monitor)
throws InvocationTargetException,
InterruptedException {
- return diffModel.getCompareInput();
+ return file.getCompareInput();
}
}, true);
}
@@ -208,7 +195,6 @@ protected Object prepareInput(
}
}
});
- setInput();
createResultFields(composite, toolkit);
@@ -227,23 +213,64 @@ protected Object prepareInput(
setSection(toolkit, section);
- }
+ SafeRunner.run(new ISafeRunnable() {
- private void createResultFields(Composite composite, FormToolkit toolkit) {
+ @Override
+ public void run() throws Exception {
+
+ ReviewScope reviewScope = getReviewScope();
+ if (reviewScope == null) {
+ section.setExpanded(false);
+ return;
+ }
+ List<IReviewScopeItem> files = reviewScope.getItems();
+
+ final TreeNode[] rootNodes = new TreeNode[files.size()];
+ int index = 0;
+ for (IReviewScopeItem 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(rootNodes);
+ if(rootNodes.length==0) {
+ section.setExpanded(false);
+ }
+ }
+ });
- final Review review;
- final ReviewData rd = ReviewsUiPlugin.getDataManager().getReviewData(
- getModel().getTask());
- if (rd != null) {
- review = rd.getReview();
- } else {
- review = parseFromAttachments();
- if (review != null) {
- ReviewsUiPlugin.getDataManager().storeTask(
- getModel().getTask(), review);
}
- }
+ @Override
+ public void handleException(Throwable exception) {
+ exception.printStackTrace();
+ }
+
+ });
+ }
+
+ 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);
resultComposite.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true,
@@ -257,24 +284,22 @@ private void createResultFields(Composite composite, FormToolkit toolkit) {
ratingsCombo.setData(FormToolkit.KEY_DRAW_BORDER,
FormToolkit.TREE_BORDER);
toolkit.adapt(ratingsCombo, false, false);
-
- final ComboViewer ratingList = new ComboViewer(ratingsCombo);
-
+ ratingList = new ComboViewer(ratingsCombo);
ratingList.setContentProvider(ArrayContentProvider.getInstance());
ratingList.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
// TODO externalize string
- return ((Rating) element).getName();
+ return ((Rating) element).name();
}
@Override
public Image getImage(Object element) {
Rating rating = ((Rating) element);
switch (rating) {
- case FAILED:
+ case FAIL:
return Images.REVIEW_RESULT_FAILED.createImage();
- case NONE:
+ case TODO:
return Images.REVIEW_RESULT_NONE.createImage();
case PASSED:
return Images.REVIEW_RESULT_PASSED.createImage();
@@ -284,33 +309,30 @@ public Image getImage(Object element) {
return super.getImage(element);
}
});
- ratingList.setInput(Rating.VALUES);
+ ratingList.setInput(Rating.values());
ratingList.getControl().setLayoutData(
new GridData(SWT.LEFT, SWT.TOP, false, false));
toolkit.createLabel(resultComposite, "Rating comment:").setForeground(
toolkit.getColors().getColor(IFormColors.TITLE));
- final Text commentText = toolkit.createText(resultComposite, "", SWT.MULTI);
-
+ final Text commentText = toolkit.createText(resultComposite, "",
+ SWT.MULTI);
+
GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false);
gd.heightHint = 100;
commentText.setLayoutData(gd);
+ final ReviewResult result = getCurrentResultOrNew();
- if (review.getResult() != null) {
- Rating rating = review.getResult().getRating();
- ratingList.setSelection(new StructuredSelection(rating));
- String comment = review.getResult().getText();
- commentText.setText(comment != null ? comment : "");
- }
+ // FIXME selection for rating
+ if (result.getRating() != null)
+ ratingList.getCCombo().select(result.getRating().ordinal());
+ if (result.getComment() != null)
+ commentText.setText(result.getComment());
commentText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
- if (review.getResult() == null) {
- review.setResult(ReviewFactory.eINSTANCE
- .createReviewResult());
- }
- review.getResult().setText(commentText.getText());
- rd.setDirty();
+ result.setComment(commentText.getText());
+
}
});
ratingList.addSelectionChangedListener(new ISelectionChangedListener() {
@@ -318,44 +340,62 @@ public void modifyText(ModifyEvent e) {
public void selectionChanged(SelectionChangedEvent event) {
Rating rating = (Rating) ((IStructuredSelection) event
.getSelection()).getFirstElement();
- if (review.getResult() == null) {
- review.setResult(ReviewFactory.eINSTANCE
- .createReviewResult());
- }
- review.getResult().setRating(rating);
- rd.setDirty();
+
+ result.setRating(rating);
}
});
+ registerEditOperations(result);
+ }
+ private ReviewResult getCurrentResultOrNew() {
+ ReviewResult result = getCurrentResult();
+ if (result == null) {
+ result = new ReviewResult();
+ }
+ return result;
}
- private Review parseFromAttachments() {
- try {
- final TaskDataModel model = getModel();
- List<Review> reviews = ReviewsUtil.getReviewAttachmentFromTask(
- TasksUi.getTaskDataManager(), TasksUi.getRepositoryModel(),
- model.getTask());
+ void registerEditOperations(ReviewResult result) {
+ final IReviewMapper mapper = ReviewsUiPlugin.getMapper();
+ PropertyChangeListener listener = new PropertyChangeListener() {
- if (reviews.size() > 0) {
- return reviews.get(0);
+ @Override
+ public void propertyChange(PropertyChangeEvent arg0) {
+ ReviewResult result = (ReviewResult) arg0.getSource();
+
+ mapper.mapResultToTask(result, getTaskProperties());
+ // FIXME
+ getModel().attributeChanged(
+ getModel().getTaskData().getRoot()
+ .getMappedAttribute(TaskAttribute.COMMENT_NEW));
}
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
+ };
+ result.addPropertyChangeListener("comment", listener);
+ result.addPropertyChangeListener("rating", listener);
+ }
+
+ private ITaskProperties getTaskProperties() {
+ if (taskProperties == null) {
+ taskProperties = TaskProperties.fromTaskData(
+ TasksUi.getTaskDataManager(), getTaskData());
+
+ }
+ return taskProperties;
}
/**
* Retrieves the review from the review data manager and fills the left
* table with the files.
+ *
+ * @return
*/
- private void setInput() {
- ReviewData rd = ReviewsUiPlugin.getDataManager().getReviewData(
- getModel().getTask());
- if (rd != null) {
- fileList.setInput((rd.getReview().getScope().get(0)));
- }
+ private ReviewResult getCurrentResult() {
+ ITaskProperties taskProperties = getTaskProperties();
+
+ final IReviewMapper mapper = ReviewsUiPlugin.getMapper();
+ ReviewResult res = mapper.mapCurrentReviewResult(taskProperties);
+ return res;
}
private static class MissingFile extends CompositeImageDescriptor {
@@ -415,6 +455,10 @@ private ImageData getBaseImageData() {
}
+ private ReviewScope getReviewScope() throws CoreException {
+ return getReviewPage().getReviewScope();
+ }
+
@Override
protected void fillToolBar(ToolBarManager manager) {
// Depends on 288171
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/TableLabelProvider.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TableLabelProvider.java
similarity index 95%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/TableLabelProvider.java
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TableLabelProvider.java
index 22d00865..7289bf28 100644
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/TableLabelProvider.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TableLabelProvider.java
@@ -8,7 +8,7 @@
* Contributors:
* Christoph Mayerhofer (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
*******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
+package org.eclipse.mylyn.reviews.tasks.ui.editors;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/messages.properties
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/messages.properties
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/messages.properties b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/messages.properties
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/messages.properties
rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/messages.properties
diff --git a/tbr/org.eclipse.mylyn.reviews/.project b/tbr/org.eclipse.mylyn.reviews.tasks/.project
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews/.project
rename to tbr/org.eclipse.mylyn.reviews.tasks/.project
diff --git a/tbr/org.eclipse.mylyn.reviews/build.properties b/tbr/org.eclipse.mylyn.reviews.tasks/build.properties
similarity index 100%
rename from tbr/org.eclipse.mylyn.reviews/build.properties
rename to tbr/org.eclipse.mylyn.reviews.tasks/build.properties
diff --git a/tbr/org.eclipse.mylyn.reviews/feature.xml b/tbr/org.eclipse.mylyn.reviews.tasks/feature.xml
similarity index 97%
rename from tbr/org.eclipse.mylyn.reviews/feature.xml
rename to tbr/org.eclipse.mylyn.reviews.tasks/feature.xml
index 1bcecf9a..e83cd07c 100644
--- a/tbr/org.eclipse.mylyn.reviews/feature.xml
+++ b/tbr/org.eclipse.mylyn.reviews.tasks/feature.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<feature
- id="org.eclipse.mylyn.reviews"
- label="Mylyn Reviews (Incubation)"
+ id="org.eclipse.mylyn.reviews.tasks"
+ label="Mylyn Reviews TBR (Incubation)"
version="0.0.1"
provider-name="Mylyn Reviews Team">
@@ -68,14 +68,14 @@ Java and all Java-based trademarks are trademarks of Oracle Corporation in the U
</license>
<plugin
- id="org.eclipse.mylyn.reviews.core"
+ id="org.eclipse.mylyn.reviews.tasks.core"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
<plugin
- id="org.eclipse.mylyn.reviews.ui"
+ id="org.eclipse.mylyn.reviews.tasks.ui"
download-size="0"
install-size="0"
version="0.0.0"
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
deleted file mode 100644
index cf178a13..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,20 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Mylyn Reviews UI (Incubation)
-Bundle-SymbolicName: org.eclipse.mylyn.reviews.ui;singleton:=true
-Bundle-Version: 0.0.1
-Bundle-Activator: org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.mylyn.tasks.ui;bundle-version="3.5.0",
- org.eclipse.ui.forms;bundle-version="3.4.1",
- org.eclipse.mylyn.tasks.core;bundle-version="3.3.0",
- org.eclipse.compare;bundle-version="3.5.0",
- org.eclipse.mylyn.reviews.core;bundle-version="0.0.1",
- org.eclipse.emf.ecore.change;bundle-version="2.5.0",
- org.eclipse.mylyn.bugzilla.ui;bundle-version="3.4.0",
- org.eclipse.core.resources;bundle-version="3.6.0"
-Bundle-ActivationPolicy: lazy
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Export-Package: org.eclipse.mylyn.reviews.ui,
- org.eclipse.mylyn.reviews.ui.editors
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java
deleted file mode 100644
index 242ceda5..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java
+++ /dev/null
@@ -1,98 +0,0 @@
-package org.eclipse.mylyn.reviews.ui;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
-import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
-import org.eclipse.mylyn.reviews.core.ReviewConstants;
-import org.eclipse.mylyn.reviews.core.ReviewsUtil;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
-import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
-import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
-import org.eclipse.mylyn.tasks.core.ITask;
-import org.eclipse.mylyn.tasks.core.ITaskAttachment;
-import org.eclipse.mylyn.tasks.core.TaskRepository;
-import org.eclipse.mylyn.tasks.core.data.ITaskDataWorkingCopy;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.core.data.TaskData;
-import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
-import org.eclipse.mylyn.tasks.core.data.TaskMapper;
-import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
-import org.eclipse.ui.IActionDelegate;
-
-public class CreateReviewAction extends Action implements IActionDelegate {
-
- private ITaskAttachment attachment;
-
- public void run(IAction action) {
- if (attachment != null) {
- try {
- ITaskDataWorkingCopy taskDataState = TasksUiPlugin
- .getTaskDataManager().getWorkingCopy(
- attachment.getTask());
- TaskDataModel model = new TaskDataModel(
- attachment.getTaskRepository(), attachment.getTask(),
- taskDataState);
-
- performFinish(model, new PatchCreator(attachment.getTaskAttribute()).create());
- } catch (CoreException e) {
- throw new RuntimeException(e);
- }
- }
-
- }
-
- public void selectionChanged(IAction action, ISelection selection) {
- action.setEnabled(false);
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structuredSelection = (IStructuredSelection) selection;
- if (structuredSelection.size() == 1) {
- attachment = (ITaskAttachment) structuredSelection
- .getFirstElement();
- if (attachment.isPatch()) {
- action.setEnabled(true);
- }
- }
- }
- }
-
-
- public boolean performFinish(TaskDataModel model,ScopeItem scope) {
- String reviewer=model.getTaskRepository().getUserName();
- try {
- Review review = ReviewFactory.eINSTANCE.createReview();
- review.getScope().add(scope);
- TaskRepository taskRepository=model.getTaskRepository();
- ITask newTask = TasksUiUtil.createOutgoingNewTask(taskRepository.getConnectorKind(), taskRepository.getRepositoryUrl());
-
- ReviewsUtil.markAsReview(newTask);
- TaskMapper initializationData=new TaskMapper(model.getTaskData());
- TaskData taskData = TasksUiInternal.createTaskData(taskRepository, initializationData, null,
- new NullProgressMonitor());
- AbstractRepositoryConnector connector=TasksUiPlugin.getConnector(taskRepository.getConnectorKind());
- connector.getTaskDataHandler().initializeSubTaskData(
- taskRepository, taskData, model.getTaskData(),
- new NullProgressMonitor());
-
-
- taskData.getRoot().getMappedAttribute(TaskAttribute.SUMMARY).setValue("Review of " + model.getTask().getSummary());
- taskData.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED).setValue(reviewer);
- taskData.getRoot().getMappedAttribute(TaskAttribute.DESCRIPTION).setValue("Review of " + model.getTask().getSummary() );
-
- ReviewsUiPlugin.getDataManager().storeOutgoingTask(newTask, review);
-
-
- TasksUiInternal.createAndOpenNewTask(newTask, taskData);
- } catch (CoreException e1) {
- throw new RuntimeException(e1);
- }
-
- return true;
- }
-
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateTask.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateTask.java
deleted file mode 100644
index fda72779..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateTask.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
-
-import java.io.ByteArrayOutputStream;
-import java.util.TreeSet;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.emf.common.util.URI;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
-import org.eclipse.mylyn.internal.tasks.ui.editors.TaskMigrator;
-import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
-import org.eclipse.mylyn.reviews.core.ReviewConstants;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
-import org.eclipse.mylyn.tasks.core.ITask;
-import org.eclipse.mylyn.tasks.core.TaskRepository;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper;
-import org.eclipse.mylyn.tasks.core.data.TaskData;
-import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
-import org.eclipse.mylyn.tasks.core.sync.SubmitJob;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
-import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
-
-/*
- * @author Kilian Matt
- */
-public class CreateTask extends Job {
-
- private TaskDataModel model;
- private Review review;
- private TaskRepository taskRepository;
- private AbstractRepositoryConnector connector;
- private String reviewer;
-
- public CreateTask(TaskDataModel model, Review review, String reviewer) {
- super(Messages.CreateTask_Title);
- this.model = model;
- this.review = review;
-
- this.taskRepository = model.getTaskRepository();
-
- this.connector = TasksUi.getRepositoryConnector(taskRepository
- .getConnectorKind());
- this.reviewer = reviewer;
- }
-
- @Override
- protected IStatus run(final IProgressMonitor monitor) {
- try {
-
- final ITask newLocalTask = TasksUiUtil.createOutgoingNewTask(
- taskRepository.getConnectorKind(),
- taskRepository.getRepositoryUrl());
-
- TaskAttributeMapper mapper = connector.getTaskDataHandler()
- .getAttributeMapper(taskRepository);
-
- final TaskData data = new TaskData(mapper,
- taskRepository.getConnectorKind(),
- taskRepository.getRepositoryUrl(), ""); //$NON-NLS-1$
-
- connector.getTaskDataHandler().initializeSubTaskData(
- taskRepository, data, model.getTaskData(),
- new NullProgressMonitor());
-
- if (reviewer != null && reviewer.isEmpty()) {
- createAttribute(data,TaskAttribute.USER_ASSIGNED,reviewer);
- }
-
- createAttribute(data,TaskAttribute.SUMMARY,
- "Review of " + model.getTask().getTaskKey() + " " + model.getTask().getSummary()); //$NON-NLS-1$ //$NON-NLS-2$
-
- createAttribute(data,TaskAttribute.COMPONENT,
- model.getTaskData()
- .getRoot()
- .getMappedAttribute(TaskAttribute.COMPONENT)
- .getValue());
- createAttribute(data,TaskAttribute.STATUS, "NEW"); //$NON-NLS-1$
- createAttribute(data,TaskAttribute.VERSION,
- model.getTaskData().getRoot()
- .getMappedAttribute(TaskAttribute.VERSION)
- .getValue());
- createAttribute(data,TaskAttribute.PRODUCT,
- model.getTaskData().getRoot()
- .getMappedAttribute(TaskAttribute.PRODUCT)
- .getValue());
-
- final byte[] attachmentBytes = createAttachment(model, review);
-
- final SubmitJob submitJob = TasksUiInternal.getJobFactory()
- .createSubmitTaskJob(connector, taskRepository,
- newLocalTask, data, new TreeSet<TaskAttribute>());
- submitJob.schedule();
- submitJob.join();
-
- if (submitJob.getStatus() == null) {
- ITask newRepoTask = submitJob.getTask();
-
- TaskMigrator migrator = new TaskMigrator(newLocalTask);
- migrator.setDelete(true);
- migrator.execute(newRepoTask);
-
- TaskAttribute attachmentAttribute = data.getAttributeMapper()
- .createTaskAttachment(data);
- try {
- ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
- attachmentBytes);
-
- monitor.subTask(Messages.CreateTask_UploadingAttachment);
- connector.getTaskAttachmentHandler().postContent(
- taskRepository, newRepoTask, attachment,
- "review result", //$NON-NLS-1$
- attachmentAttribute, monitor);
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- return new ReviewStatus(Messages.CreateTask_Success,
- newRepoTask);
- }
- return new Status(IStatus.WARNING, ReviewsUiPlugin.PLUGIN_ID, "");
- } catch (Exception e) {
- return new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID,
- e.getMessage());
- }
- }
- private TaskAttribute createAttribute( TaskData taskData, String mappedAttributeName, String value) {
- TaskAttribute attribute = taskData.getRoot().createMappedAttribute(mappedAttributeName);
- attribute.setValue(value);
- return attribute;
- }
-
- private byte[] createAttachment(TaskDataModel model, Review review) {
- try {
- ResourceSet resourceSet = new ResourceSetImpl();
-
- Resource resource = resourceSet.createResource(URI
- .createFileURI("")); //$NON-NLS-1$
-
- resource.getContents().add(review);
- resource.getContents().add(review.getScope().get(0));
- if(review.getResult()!=null)
- resource.getContents().add(review.getResult());
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- ZipOutputStream outputStream = new ZipOutputStream(
- byteArrayOutputStream);
- outputStream.putNextEntry(new ZipEntry(
- ReviewConstants.REVIEW_DATA_FILE));
- resource.save(outputStream, null);
- outputStream.closeEntry();
- outputStream.close();
- return byteArrayOutputStream.toByteArray();
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
-
- }
-
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/PatchCreator.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/PatchCreator.java
deleted file mode 100644
index 5fc79751..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/PatchCreator.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URL;
-import java.util.Date;
-import java.util.logging.Logger;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.mylyn.internal.tasks.core.RepositoryModel;
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
-import org.eclipse.mylyn.tasks.core.ITaskAttachment;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
-
-/**
- * @author Kilian Matt
- */
-public class PatchCreator implements IPatchCreator {
-
- private static final Logger log = Logger.getAnonymousLogger();
- private TaskAttribute attribute;
-
- public PatchCreator(TaskAttribute attribute) {
- this.attribute = attribute;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.mylyn.reviews.ui.IPatchCreator#create()
- */
- public Patch create() throws CoreException {
- try {
- ITaskAttachment taskAttachment = getTaskAttachment();
- URL url = new URL(attribute.getMappedAttribute(
- TaskAttribute.ATTACHMENT_URL).getValue());
- Patch patch = ReviewFactory.eINSTANCE.createPatch();
- patch.setAuthor(taskAttachment.getAuthor().getName());
- patch.setCreationDate(taskAttachment.getCreationDate());
- patch.setContents(readContents(url));
- patch.setFileName(taskAttachment.getFileName());
- return patch;
- } catch (Exception e) {
- e.printStackTrace();
- log.warning(e.toString());
- throw new CoreException(new Status(IStatus.ERROR,
- ReviewsUiPlugin.PLUGIN_ID,
- Messages.PatchCreator_ReaderCreationFailed, e));
- }
- }
-
- private ITaskAttachment taskAttachment;
-
- private ITaskAttachment getTaskAttachment() {
- if (taskAttachment == null) {
- // TODO move RepositoryModel.createTaskAttachment to interface?
- taskAttachment = ((RepositoryModel) TasksUi.getRepositoryModel())
- .createTaskAttachment(attribute);
- // new TaskAttachment(repository, task, attribute);
- // attributeMapper.updateTaskAttachment(taskAttachment, attribute);
- }
- return taskAttachment;
- }
-
- private String readContents(URL url) throws IOException {
- InputStream stream = null;
- try {
- stream = url.openStream();
- InputStreamReader reader = new InputStreamReader(stream);
- char[] buffer = new char[256];
- int readChars = 0;
- StringBuilder sb = new StringBuilder();
- while ((readChars = reader.read(buffer)) > 0) {
- sb.append(buffer, 0, readChars);
- }
- return sb.toString();
- } finally {
- if (stream != null)
- try {
- stream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- }
-
- @Override
- public String toString() {
- return attribute.getMappedAttribute(TaskAttribute.ATTACHMENT_FILENAME)
- .getValue();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.mylyn.reviews.ui.IPatchCreator#getFileName()
- */
- public String getFileName() {
- return getTaskAttachment().getFileName();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.mylyn.reviews.ui.IPatchCreator#getAuthor()
- */
- public String getAuthor() {
- return getTaskAttachment().getAuthor().getName();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.mylyn.reviews.ui.IPatchCreator#getCreationDate()
- */
- public Date getCreationDate() {
- return getTaskAttachment().getCreationDate();
- }
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewCommentTaskAttachmentSource.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewCommentTaskAttachmentSource.java
deleted file mode 100644
index d3fdbe0f..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewCommentTaskAttachmentSource.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.mylyn.reviews.core.ReviewConstants;
-import org.eclipse.mylyn.tasks.core.data.AbstractTaskAttachmentSource;
-
-/*
- * @author Kilian Matt
- */
-public class ReviewCommentTaskAttachmentSource extends
- AbstractTaskAttachmentSource {
-
- private byte[] source;
-
- public ReviewCommentTaskAttachmentSource(byte[] source) {
- this.source = source;
- }
-
- @Override
- public InputStream createInputStream(IProgressMonitor monitor)
- throws CoreException {
- return new ByteArrayInputStream(source);
- }
-
- @Override
- public String getContentType() {
- return "application/octet-stream"; //$NON-NLS-1$
- }
-
- @Override
- public String getDescription() {
- return Messages.ReviewCommentTaskAttachmentSource_Description;
- }
-
- @Override
- public long getLength() {
- return source.length;
- }
-
- @Override
- public String getName() {
- return ReviewConstants.REVIEW_DATA_CONTAINER;
- }
-
- @Override
- public boolean isLocal() {
- return true;
- }
-
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewStatus.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewStatus.java
deleted file mode 100644
index e2f5c433..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/ReviewStatus.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.eclipse.mylyn.reviews.ui;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.mylyn.tasks.core.ITask;
-
-public class ReviewStatus extends Status {
- private ITask task;
-
- public ReviewStatus(String message, ITask task) {
- super(IStatus.OK, ReviewsUiPlugin.PLUGIN_ID, message);
- this.task = task;
- }
-
- public ITask getTask() {
- return task;
- }
-
-}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/NewReviewTaskEditorInput.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/NewReviewTaskEditorInput.java
deleted file mode 100644
index 9356bf7c..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/NewReviewTaskEditorInput.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
-
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
-import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
-
-/*
- * @author Kilian Matt
- */
-public class NewReviewTaskEditorInput extends ReviewTaskEditorInput {
-
- private TaskDataModel model;
-
- public NewReviewTaskEditorInput(TaskDataModel model, Patch patch) {
- super(ReviewFactory.eINSTANCE.createReview());
- this.model = model;
- getReview().getScope().add(patch);
- }
-
- @Override
- public String getName() {
- return Messages.NewReviewTaskEditorInput_ReviewPrefix + model.getTask().getTaskKey() + " " //$NON-NLS-2$
- + model.getTask().toString();
- }
-
- public TaskDataModel getModel() {
- return model;
- }
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryPartConfigurer.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryPartConfigurer.java
deleted file mode 100644
index bd1127c1..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryPartConfigurer.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package org.eclipse.mylyn.reviews.ui.editors;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.mylyn.internal.tasks.core.RepositoryModel;
-import org.eclipse.mylyn.tasks.core.IRepositoryModel;
-import org.eclipse.mylyn.tasks.core.ITask;
-import org.eclipse.mylyn.tasks.core.ITaskAttachment;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.core.data.TaskData;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
-import org.eclipse.mylyn.tasks.ui.editors.ITaskEditorPartDescriptorAdvisor;
-import org.eclipse.mylyn.tasks.ui.editors.TaskEditorPartDescriptor;
-
-public class ReviewSummaryPartConfigurer implements
- ITaskEditorPartDescriptorAdvisor {
-
- public boolean canCustomize(ITask task) {
- try {
-
- // TODO change to detecting review sub tasks!
-
- TaskData taskData = TasksUi.getTaskDataManager().getTaskData(task);
- IRepositoryModel repositoryModel = TasksUi.getRepositoryModel();
- if (taskData != null) {
- List<TaskAttribute> attributesByType = taskData
- .getAttributeMapper().getAttributesByType(taskData,
- TaskAttribute.TYPE_ATTACHMENT);
- for (TaskAttribute attribute : attributesByType) {
- // TODO move RepositoryModel.createTaskAttachment to
- // interface?
- ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel)
- .createTaskAttachment(attribute);
- if (taskAttachment.isPatch())
- return true;
-
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- return false;
- }
-
- public Set<String> getBlockingIds(ITask task) {
- return Collections.emptySet();
- }
-
- public Set<String> getBlockingPaths(ITask task) {
- return Collections.emptySet();
- }
-
- public Set<TaskEditorPartDescriptor> getPartContributions(ITask task) {
- Set<TaskEditorPartDescriptor> descriptors = new HashSet<TaskEditorPartDescriptor>();
- descriptors.add(new TaskEditorPartDescriptor(
- ReviewSummaryTaskEditorPart.ID_PART_REVIEWSUMMARY) {
-
- @Override
- public AbstractTaskEditorPart createPart() {
- return new ReviewSummaryTaskEditorPart();
- }
- });
- return descriptors;
- }
-
- public void afterSubmit(ITask task) {
- }
-
- public void prepareSubmit(ITask task) {
- }
-
- public void taskMigration(ITask oldTask, ITask newTask) {
- }
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java
deleted file mode 100644
index 48900dd4..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.mylyn.reviews.core.ReviewSubTask;
-import org.eclipse.mylyn.reviews.core.ReviewsUtil;
-import org.eclipse.mylyn.reviews.core.model.review.Rating;
-import org.eclipse.mylyn.reviews.ui.Images;
-import org.eclipse.mylyn.tasks.core.ITask;
-import org.eclipse.mylyn.tasks.core.ITaskContainer;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
-import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-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.Table;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-/*
- * @author Kilian Matt
- */
-public class ReviewSummaryTaskEditorPart extends AbstractTaskEditorPart {
-
- public static final String ID_PART_REVIEWSUMMARY = "org.eclipse.mylyn.reviews.ui.editors.parts.reviewsummary"; //$NON-NLS-1$
- private Section summarySection;
-
- public ReviewSummaryTaskEditorPart() {
- setPartName(Messages.ReviewSummaryTaskEditorPart_Partname);
- }
-
- @Override
- public void createControl(final Composite parent, FormToolkit toolkit) {
- summarySection = createSection(parent, toolkit,
- ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE
- | ExpandableComposite.EXPANDED);
- summarySection.setLayout(new FillLayout(SWT.HORIZONTAL));
- summarySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
- true));
- // summarySection.setText(Messages.ReviewSummaryTaskEditorPart_Partname);
- Composite reviewResultsComposite = toolkit
- .createComposite(summarySection);
- toolkit.paintBordersFor(reviewResultsComposite);
- reviewResultsComposite.setLayout(new GridLayout(1, false));
-
- TableViewer reviewResults = createResultsTableViewer(
- reviewResultsComposite, toolkit);
- reviewResults.getControl().setLayoutData(
- new GridData(SWT.FILL, SWT.FILL, true, true));
-
- summarySection.setClient(reviewResultsComposite);
- }
-
- private TableViewerColumn createColumn(TableViewer parent,
- String columnTitle) {
- TableViewerColumn column = new TableViewerColumn(parent, SWT.LEFT);
- column.getColumn().setText(columnTitle);
- column.getColumn().setWidth(100);
- column.getColumn().setResizable(true);
- return column;
- }
-
- private TableViewer createResultsTableViewer(
- Composite reviewResultsComposite, FormToolkit toolkit) {
- Table table = toolkit.createTable(reviewResultsComposite, SWT.SINGLE
- | SWT.FULL_SELECTION);
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
- table.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER);
-
- TableViewer reviewResults = new TableViewer(table);
- createColumn(reviewResults,
- Messages.ReviewSummaryTaskEditorPart_Header_ReviewId);
- createColumn(reviewResults,
- Messages.ReviewSummaryTaskEditorPart_Header_Scope);
- createColumn(reviewResults,
- Messages.ReviewSummaryTaskEditorPart_Header_Author);
- createColumn(reviewResults,
- Messages.ReviewSummaryTaskEditorPart_Header_Reviewer);
- createColumn(reviewResults,
- Messages.ReviewSummaryTaskEditorPart_Header_Result);
-
- createColumn(reviewResults,
- Messages.ReviewSummaryTaskEditorPart_Header_Comment);
-
- reviewResults.setContentProvider(new IStructuredContentProvider() {
-
- public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
- }
-
- public void dispose() {
- }
-
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof ITaskContainer) {
- ITaskContainer taskContainer = (ITaskContainer) inputElement;
- List<ReviewSubTask> reviewSubTasks = ReviewsUtil
- .getReviewSubTasksFor(taskContainer,
- TasksUi.getTaskDataManager(),
- TasksUi.getRepositoryModel(),
- new NullProgressMonitor());
- int passedCount = 0;
- int warningCount = 0;
- int failedCount = 0;
- int noResultCount = 0;
- for (ReviewSubTask subtask : reviewSubTasks) {
- switch (subtask.getResult()) {
- case PASSED:
- passedCount++;
- break;
- case WARNING:
- warningCount++;
- break;
- case FAILED:
- failedCount++;
- break;
- case NONE:
- noResultCount++;
- break;
-
- }
- }
-
- summarySection.setText(String
- .format("Review Summary (PASSED: %s / WARNING: %s / FAILED: %s / ?: %s)",
- passedCount, warningCount, failedCount,
- noResultCount));
- return reviewSubTasks
- .toArray(new ReviewSubTask[reviewSubTasks.size()]);
- }
- return null;
- }
- });
-
- reviewResults.setLabelProvider(new TableLabelProvider() {
- private static final int COLUMN_ID = 0;
- private static final int COLUMN_PATCHFILE = 1;
- private static final int COLUMN_AUTHOR = 2;
- private static final int COLUMN_REVIEWER = 3;
- private static final int COLUMN_RESULT = 4;
- private static final int COLUMN_COMMENT = 5;
-
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == COLUMN_RESULT) {
- ReviewSubTask subtask = (ReviewSubTask) element;
- switch (subtask.getResult()) {
- case FAILED:
- return Images.REVIEW_RESULT_FAILED.createImage();
- case WARNING:
- return Images.REVIEW_RESULT_WARNING.createImage();
- case PASSED:
- return Images.REVIEW_RESULT_PASSED.createImage();
- case NONE:
- return Images.REVIEW_RESULT_NONE.createImage();
-
- }
- }
- return null;
- }
-
- public String getColumnText(Object element, int columnIndex) {
-
- ReviewSubTask subtask = (ReviewSubTask) element;
- switch (columnIndex) {
- case COLUMN_ID:
- return subtask.getTask().getTaskId();
- case COLUMN_PATCHFILE:
- return subtask.getPatchDescription();
- case COLUMN_AUTHOR:
- return subtask.getAuthor();
- case COLUMN_REVIEWER:
- return subtask.getReviewer();
- case COLUMN_RESULT:
- return subtask.getResult().getName();
- case COLUMN_COMMENT:
- return subtask.getComment();
- default:
- return null;
- }
- }
-
- });
- reviewResults.setInput(getModel().getTask());
- reviewResults.addDoubleClickListener(new IDoubleClickListener() {
-
- public void doubleClick(DoubleClickEvent event) {
- if (!event.getSelection().isEmpty()) {
- ITask task = ((ReviewSubTask) ((IStructuredSelection) event
- .getSelection()).getFirstElement()).getTask();
- TasksUiUtil.openTask(task);
- }
- }
- });
- return reviewResults;
- }
-
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorInput.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorInput.java
deleted file mode 100644
index c9020428..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorInput.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.compare.patch.IFilePatch2;
-import org.eclipse.compare.patch.PatchConfiguration;
-import org.eclipse.compare.patch.PatchParser;
-import org.eclipse.compare.patch.ReaderCreator;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.mylyn.reviews.core.model.review.Patch;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.ui.Images;
-import org.eclipse.mylyn.reviews.ui.ReviewDiffModel;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IPersistableElement;
-
-/*
- * @author Kilian Matt
- */
-public class ReviewTaskEditorInput implements IEditorInput {
-
- private Review review;
-
- public ReviewTaskEditorInput(Review review) {
- this.review = review;
- }
-
- public Review getReview() {
- return review;
- }
-
- public boolean exists() {
- return false;
- }
-
- public ImageDescriptor getImageDescriptor() {
- return Images.SMALL_ICON;
- }
-
- public String getName() {
- // TODO
- return Messages.ReviewTaskEditorInput_New_Review;//"Review of" + model.getTask().getTaskKey() + " " +
- // model.getTask().toString();
- }
-
- public IPersistableElement getPersistable() {
- return null;
- }
-
- public String getToolTipText() {
- return Messages.NewReviewTaskEditorInput_Tooltip;
- }
-
- @SuppressWarnings("rawtypes")
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- public List<ReviewDiffModel> getScope() {
- try {
-
- IFilePatch2[] patches = PatchParser.parsePatch(new ReaderCreator() {
-
- @Override
- public Reader createReader() throws CoreException {
- return new InputStreamReader(new ByteArrayInputStream(
- ((Patch) review.getScope().get(0)).getContents()
- .getBytes()));
- }
- });
- List<ReviewDiffModel> model = new ArrayList<ReviewDiffModel>();
- for (int i = 0; i < patches.length; i++) {
- final PatchConfiguration configuration = new PatchConfiguration();
-
- final IFilePatch2 currentPatch = patches[i];
- model.add(new ReviewDiffModel(currentPatch, configuration));
- }
- return model;
- } catch (Exception ex) {
- ex.printStackTrace();
- throw new RuntimeException(ex);
- }
- }
-
-}
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
deleted file mode 100644
index 2e4b4ddb..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
+++ /dev/null
@@ -1,160 +0,0 @@
-package org.eclipse.mylyn.reviews.ui.editors;
-
-import java.io.ByteArrayOutputStream;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.emf.common.util.URI;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
-import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
-import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
-import org.eclipse.mylyn.reviews.core.ReviewConstants;
-import org.eclipse.mylyn.reviews.core.ReviewData;
-import org.eclipse.mylyn.reviews.core.ReviewDataManager;
-import org.eclipse.mylyn.reviews.core.ReviewsUtil;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.ui.ReviewCommentTaskAttachmentSource;
-import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
-import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
-import org.eclipse.mylyn.tasks.core.IRepositoryModel;
-import org.eclipse.mylyn.tasks.core.ITask;
-import org.eclipse.mylyn.tasks.core.TaskRepository;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.core.data.TaskData;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage;
-import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
-import org.eclipse.mylyn.tasks.ui.editors.ITaskEditorPartDescriptorAdvisor;
-import org.eclipse.mylyn.tasks.ui.editors.TaskEditorPartDescriptor;
-
-public class ReviewTaskEditorPartAdvisor implements
- ITaskEditorPartDescriptorAdvisor {
-
- public boolean canCustomize(ITask task) {
- if (!ReviewsUtil.hasReviewMarker(task)) {
- try {
- IRepositoryModel repositoryModel = TasksUi.getRepositoryModel();
- TaskData taskData = TasksUiPlugin.getTaskDataManager()
- .getTaskData(task);
- if (ReviewsUtil.getReviewAttachments(repositoryModel, taskData)
- .size() > 0) {
- ReviewsUtil.markAsReview(task);
- }
- } catch (CoreException e) {
- // FIXME
- e.printStackTrace();
- }
- }
-
- boolean isReview = ReviewsUtil.isMarkedAsReview(task);
- return isReview;
- }
-
- public Set<String> getBlockingIds(ITask task) {
- return Collections.emptySet();
- }
-
- public Set<String> getBlockingPaths(ITask task) {
- Set<String> blockedPaths = new HashSet<String>();
- blockedPaths.add(AbstractTaskEditorPage.PATH_ATTRIBUTES);
- blockedPaths.add(AbstractTaskEditorPage.PATH_ATTACHMENTS);
- blockedPaths.add(AbstractTaskEditorPage.PATH_PLANNING);
-
- return blockedPaths;
- }
-
- public Set<TaskEditorPartDescriptor> getPartContributions(ITask task) {
- Set<TaskEditorPartDescriptor> parts = new HashSet<TaskEditorPartDescriptor>();
- parts.add(new TaskEditorPartDescriptor(
- ReviewTaskEditorPart.ID_PART_REVIEW) {
-
- @Override
- public AbstractTaskEditorPart createPart() {
- return new ReviewTaskEditorPart();
- }
- }.setPath(AbstractTaskEditorPage.PATH_ATTRIBUTES));
- return parts;
- }
-
- public void taskMigration(ITask oldTask, ITask newTask) {
- ReviewDataManager dataManager = ReviewsUiPlugin.getDataManager();
- Review review = dataManager.getReviewData(oldTask).getReview();
- dataManager.storeOutgoingTask(newTask, review);
- ReviewsUtil.markAsReview(newTask);
- }
-
- public void afterSubmit(ITask task) {
- try {
- ReviewData reviewData = ReviewsUiPlugin.getDataManager()
- .getReviewData(task);
- Review review = reviewData.getReview();
-
- if (reviewData.isOutgoing() || reviewData.isDirty()) {
- reviewData.setDirty(false);
- TaskRepository taskRepository = TasksUiPlugin
- .getRepositoryManager().getRepository(
- task.getRepositoryUrl());
- TaskData taskData = TasksUiPlugin.getTaskDataManager()
- .getTaskData(task);
- // todo get which attachments have to be submitted
- TaskAttribute attachmentAttribute = taskData
- .getAttributeMapper().createTaskAttachment(taskData);
- byte[] attachmentBytes = createAttachment(review);
-
- ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
- attachmentBytes);
-
- AbstractRepositoryConnector connector = TasksUi
- .getRepositoryConnector(taskRepository
- .getConnectorKind());
- connector.getTaskAttachmentHandler().postContent(
- taskRepository, task, attachment, "review result", //$NON-NLS-1$
- attachmentAttribute, new NullProgressMonitor());
-
- TasksUiInternal.closeTaskEditorInAllPages(task, false);
- TasksUiInternal.synchronizeTask(connector, task, false, null);
- TasksUiInternal.openTaskInBackground(task, true);
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
- public void prepareSubmit(ITask task) {
- }
-
- private byte[] createAttachment(Review review) {
- try {
- ResourceSet resourceSet = new ResourceSetImpl();
-
- Resource resource = resourceSet.createResource(URI
- .createFileURI("")); //$NON-NLS-1$
-
- resource.getContents().add(review);
- resource.getContents().add(review.getScope().get(0));
- if (review.getResult() != null)
- resource.getContents().add(review.getResult());
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- ZipOutputStream outputStream = new ZipOutputStream(
- byteArrayOutputStream);
- outputStream.putNextEntry(new ZipEntry(
- ReviewConstants.REVIEW_DATA_FILE));
- resource.save(outputStream, null);
- outputStream.closeEntry();
- outputStream.close();
- return byteArrayOutputStream.toByteArray();
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
-
- }
-
-}
\ No newline at end of file
diff --git a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/UpdateReviewTask.java b/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/UpdateReviewTask.java
deleted file mode 100644
index f51af485..00000000
--- a/tbr/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/UpdateReviewTask.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*******************************************************************************
- * 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:
- * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation
- *******************************************************************************/
-package org.eclipse.mylyn.reviews.ui.editors;
-
-import java.io.ByteArrayOutputStream;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-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.emf.common.util.URI;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
-import org.eclipse.mylyn.reviews.core.ReviewConstants;
-import org.eclipse.mylyn.reviews.core.model.review.Review;
-import org.eclipse.mylyn.reviews.ui.editors.Messages;
-import org.eclipse.mylyn.reviews.ui.ReviewCommentTaskAttachmentSource;
-import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin;
-import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
-import org.eclipse.mylyn.tasks.core.TaskRepository;
-import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
-import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
-import org.eclipse.mylyn.tasks.ui.TasksUi;
-
-/*
- * @author Kilian Matt
- */
-public class UpdateReviewTask extends Job {
-
-
-
- private TaskDataModel model;
- private Review review;
- private TaskRepository taskRepository;
- private AbstractRepositoryConnector connector;
-
- public UpdateReviewTask(TaskDataModel model, Review review) {
- super(Messages.UpdateReviewTask_Title);
- this.model = model;
- this.review = review;
-
- this.taskRepository = model.getTaskRepository();
-
- this.connector = TasksUi.getRepositoryConnector(taskRepository
- .getConnectorKind());
- }
-
- @Override
- protected IStatus run(final IProgressMonitor monitor) {
- try {
-
-
- final byte[] attachmentBytes = createAttachment(model, review);
-
- TaskAttribute attachmentAttribute = model.getTaskData().getAttributeMapper()
- .createTaskAttachment( model.getTaskData());
- try {
- ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
- attachmentBytes);
-
- monitor.subTask(org.eclipse.mylyn.reviews.ui.Messages.CreateTask_UploadingAttachment);
- connector.getTaskAttachmentHandler().postContent(
- taskRepository, model.getTask(), attachment,
- "review result", //$NON-NLS-1$
- attachmentAttribute, monitor);
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
-
- return new Status(IStatus.OK, ReviewsUiPlugin.PLUGIN_ID,
- org.eclipse.mylyn.reviews.ui.Messages.CreateTask_Success);
- } catch (Exception e) {
- return new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, e
- .getMessage());
- }
- }
-
- private byte[] createAttachment(TaskDataModel model, Review review) {
- try {
- ResourceSet resourceSet = new ResourceSetImpl();
-
- Resource resource = resourceSet.createResource(URI
- .createFileURI("")); //$NON-NLS-1$
-
- resource.getContents().add(review);
- resource.getContents().add(review.getScope().get(0));
- resource.getContents().add(review.getResult());
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- ZipOutputStream outputStream = new ZipOutputStream(
- byteArrayOutputStream);
- outputStream.putNextEntry(new ZipEntry(
- ReviewConstants.REVIEW_DATA_FILE));
- resource.save(outputStream, null);
- outputStream.closeEntry();
- outputStream.close();
- return byteArrayOutputStream.toByteArray();
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
-
- }
-
-}
|
643ae0c985d01e4b5deb9d28a1381de8179926af
|
hbase
|
HBASE-2781 ZKW.createUnassignedRegion doesn't- make sure existing znode is in the right state (Karthik- Ranganathan via JD)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@963910 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index ec4341f65428..44e345bba702 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -432,6 +432,8 @@ Release 0.21.0 - Unreleased
HBASE-2797 Another NPE in ReadWriteConsistencyControl
HBASE-2831 Fix '$bin' path duplication in setup scripts
(Nicolas Spiegelberg via Stack)
+ HBASE-2781 ZKW.createUnassignedRegion doesn't make sure existing znode is
+ in the right state (Karthik Ranganathan via JD)
IMPROVEMENTS
HBASE-1760 Cleanup TODOs in HTable
diff --git a/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java b/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java
index b4ba5ab15c03..979739e3a076 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java
@@ -993,8 +993,9 @@ public void setUnassigned(HRegionInfo info, boolean force) {
// should never happen
LOG.error("Error creating event data for " + HBaseEventType.M2ZK_REGION_OFFLINE, e);
}
- zkWrapper.createUnassignedRegion(info.getEncodedName(), data);
- LOG.debug("Created UNASSIGNED zNode " + info.getRegionNameAsString() + " in state " + HBaseEventType.M2ZK_REGION_OFFLINE);
+ zkWrapper.createOrUpdateUnassignedRegion(info.getEncodedName(), data);
+ LOG.debug("Created/updated UNASSIGNED zNode " + info.getRegionNameAsString() +
+ " in state " + HBaseEventType.M2ZK_REGION_OFFLINE);
s = new RegionState(info, RegionState.State.UNASSIGNED);
regionsInTransition.put(info.getRegionNameAsString(), s);
}
diff --git a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java
index 74b0446fa30f..f292b253c62e 100644
--- a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java
+++ b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java
@@ -1073,6 +1073,14 @@ public boolean writeZNode(String znodeName, byte[] data, int version, boolean wa
}
}
+ /**
+ * Given a region name and some data, this method creates a new the region
+ * znode data under the UNASSGINED znode with the data passed in. This method
+ * will not update data for existing znodes.
+ *
+ * @param regionName - encoded name of the region
+ * @param data - new serialized data to update the region znode
+ */
public void createUnassignedRegion(String regionName, byte[] data) {
String znode = getZNode(getRegionInTransitionZNode(), regionName);
if(LOG.isDebugEnabled()) {
@@ -1109,6 +1117,66 @@ public void createUnassignedRegion(String regionName, byte[] data) {
}
}
+ /**
+ * Given a region name and some data, this method updates the region znode
+ * data under the UNASSGINED znode with the latest data. This method will
+ * update the znode data only if it already exists.
+ *
+ * @param regionName - encoded name of the region
+ * @param data - new serialized data to update the region znode
+ */
+ public void updateUnassignedRegion(String regionName, byte[] data) {
+ String znode = getZNode(getRegionInTransitionZNode(), regionName);
+ // this is an update - make sure the node already exists
+ if(!exists(znode, true)) {
+ LOG.error("Cannot update " + znode + " - node does not exist" );
+ return;
+ }
+
+ if(LOG.isDebugEnabled()) {
+ // Check existing state for logging purposes.
+ Stat stat = new Stat();
+ byte[] oldData = null;
+ try {
+ oldData = readZNode(znode, stat);
+ } catch (IOException e) {
+ LOG.error("Error reading data for " + znode);
+ }
+ if(oldData == null) {
+ LOG.debug("While updating UNASSIGNED region " + regionName + " - node exists with no data" );
+ }
+ else {
+ LOG.debug("While updating UNASSIGNED region " + regionName + " exists, state = " + (HBaseEventType.fromByte(oldData[0])));
+ }
+ }
+ synchronized(unassignedZNodesWatched) {
+ unassignedZNodesWatched.add(znode);
+ try {
+ writeZNode(znode, data, -1, true);
+ } catch (IOException e) {
+ LOG.error("Error writing data for " + znode + ", could not update state to " + (HBaseEventType.fromByte(data[0])));
+ }
+ }
+ }
+
+ /**
+ * This method will create a new region in transition entry in ZK with the
+ * speficied data if none exists. If one already exists, it will update the
+ * data with whatever is passed in.
+ *
+ * @param regionName - encoded name of the region
+ * @param data - serialized data for the region znode
+ */
+ public void createOrUpdateUnassignedRegion(String regionName, byte[] data) {
+ String znode = getZNode(getRegionInTransitionZNode(), regionName);
+ if(exists(znode, true)) {
+ updateUnassignedRegion(regionName, data);
+ }
+ else {
+ createUnassignedRegion(regionName, data);
+ }
+ }
+
public void deleteUnassignedRegion(String regionName) {
String znode = getZNode(getRegionInTransitionZNode(), regionName);
try {
|
7ed444678012a695278f54ab86ca4a5dd73537c7
|
intellij-community
|
one more test that fails; some more code moved- to common framework--
|
p
|
https://github.com/JetBrains/intellij-community
|
diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnDeleteTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnDeleteTest.java
new file mode 100644
index 0000000000000..809bb1bc917da
--- /dev/null
+++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnDeleteTest.java
@@ -0,0 +1,27 @@
+package org.jetbrains.idea.svn;
+
+import com.intellij.openapi.vcs.VcsConfiguration;
+import com.intellij.openapi.vfs.VirtualFile;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * @author yole
+ */
+public class SvnDeleteTest extends SvnTestCase {
+ // IDEADEV-16066
+ @Test
+ @Ignore
+ public void testDeletePackage() throws Exception {
+ enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
+ enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE);
+ VirtualFile dir = createDirInCommand(myWorkingCopyDir, "child");
+ createFileInCommand(dir, "a.txt", "content");
+
+ verify(runSvn("status"), "A child", "A child\\a.txt");
+ checkin();
+
+ deleteFileInCommand(dir);
+ verify(runSvn("status"), "D child", "D child\\a.txt");
+ }
+}
\ No newline at end of file
diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java
index 450ad487f63f1..dea7e4f5bfe66 100644
--- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java
+++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnRenameTest.java
@@ -2,10 +2,8 @@
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vfs.VirtualFile;
-import org.junit.Test;
import org.junit.Ignore;
-
-import java.io.IOException;
+import org.junit.Test;
/**
* @author yole
@@ -21,10 +19,6 @@ public void testSimpleRename() throws Exception {
verify(runSvn("status"), "A + b.txt", "D a.txt");
}
- private void checkin() throws IOException {
- verify(runSvn("ci", "-m", "test"));
- }
-
// IDEADEV-18844
@Test
@Ignore
diff --git a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java
index 7b3ec28c8f834..e70a8e54534e8 100644
--- a/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java
+++ b/plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestCase.java
@@ -68,4 +68,8 @@ protected RunResult runSvn(String... commandLine) throws IOException {
protected void enableSilentOperation(final VcsConfiguration.StandardConfirmation op) {
enableSilentOperation(SvnVcs.VCS_NAME, op);
}
+
+ protected void checkin() throws IOException {
+ verify(runSvn("ci", "-m", "test"));
+ }
}
|
cadd12fe44f37ce5c40652a800820eca8b09cfb7
|
intellij-community
|
Memory leak fixed. Area instances connected to- project and module haven't been disposed at their disposal.--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/source/com/intellij/openapi/module/impl/ModuleImpl.java b/source/com/intellij/openapi/module/impl/ModuleImpl.java
index fabdb8a958812..ca57298d19b29 100644
--- a/source/com/intellij/openapi/module/impl/ModuleImpl.java
+++ b/source/com/intellij/openapi/module/impl/ModuleImpl.java
@@ -1,28 +1,30 @@
package com.intellij.openapi.module.impl;
-import com.intellij.application.options.PathMacros;
import com.intellij.application.options.ExpandMacroToPathMap;
import com.intellij.application.options.PathMacroMap;
+import com.intellij.application.options.PathMacros;
import com.intellij.application.options.ReplacePathToMacroMap;
import com.intellij.ide.plugins.PluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
-import com.intellij.openapi.application.ex.ApplicationEx;
-import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.application.ex.DecodeDefaultsUtil;
import com.intellij.openapi.components.BaseComponent;
import com.intellij.openapi.components.impl.ComponentManagerImpl;
import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.module.*;
+import com.intellij.openapi.extensions.Extensions;
+import com.intellij.openapi.module.Module;
+import com.intellij.openapi.module.ModuleComponent;
+import com.intellij.openapi.module.ModuleType;
+import com.intellij.openapi.module.ModuleTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.impl.BaseFileConfigurable;
import com.intellij.openapi.project.impl.ProjectImpl;
-import com.intellij.openapi.util.*;
+import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.util.InvalidDataException;
+import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
-import com.intellij.openapi.extensions.AreaInstance;
-import com.intellij.openapi.extensions.Extensions;
import com.intellij.pom.PomModel;
import com.intellij.pom.PomModule;
import com.intellij.pom.core.impl.PomModuleImpl;
@@ -180,6 +182,7 @@ public void dispose() {
disposeComponents();
myIsDisposed = true;
VirtualFileManager.getInstance().removeVirtualFileListener(myVirtualFileListener);
+ Extensions.disposeArea(this);
}
public VirtualFile[] getConfigurationFiles() {
diff --git a/source/com/intellij/openapi/project/impl/ProjectImpl.java b/source/com/intellij/openapi/project/impl/ProjectImpl.java
index dc4d9ac6bfd55..f1ab1313458dc 100644
--- a/source/com/intellij/openapi/project/impl/ProjectImpl.java
+++ b/source/com/intellij/openapi/project/impl/ProjectImpl.java
@@ -8,14 +8,14 @@
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.ex.ApplicationEx;
-import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.application.ex.DecodeDefaultsUtil;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.components.BaseComponent;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.components.impl.ComponentManagerImpl;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.extensions.AreaInstance;
+import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.impl.ModuleImpl;
@@ -35,8 +35,6 @@
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
-import com.intellij.openapi.extensions.Extensions;
-import com.intellij.openapi.extensions.AreaInstance;
import com.intellij.pom.PomModel;
import com.intellij.util.ArrayUtil;
import org.jdom.Document;
@@ -484,6 +482,7 @@ public void dispose() {
}
disposeComponents();
+ Extensions.disposeArea(this);
myDisposed = true;
}
|
84db103b6f7e6dcca997a34175a4891f1fa18d51
|
tapiji
|
Prototypes marker update approach.
Gets the markers current position information from the abstract marker annotation model.
|
a
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF
index 719731b9..0be86f28 100644
--- a/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF
+++ b/org.eclipselabs.tapiji.tools.core.ui/META-INF/MANIFEST.MF
@@ -30,4 +30,5 @@ Export-Package: org.eclipselabs.tapiji.tools.core.ui,
org.eclipselabs.tapiji.tools.core.ui.widgets.listener,
org.eclipselabs.tapiji.tools.core.ui.widgets.provider,
org.eclipselabs.tapiji.tools.core.ui.widgets.sorter
-Import-Package: org.eclipse.core.filebuffers
+Import-Package: org.eclipse.core.filebuffers,
+ org.eclipse.ui.texteditor
diff --git a/org.eclipselabs.tapiji.tools.core.ui/plugin.xml b/org.eclipselabs.tapiji.tools.core.ui/plugin.xml
index 88b66b2c..4919cc30 100644
--- a/org.eclipselabs.tapiji.tools.core.ui/plugin.xml
+++ b/org.eclipselabs.tapiji.tools.core.ui/plugin.xml
@@ -112,5 +112,5 @@
name="Builder Settings">
</page>
</extension>
-
+
</plugin>
diff --git a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java
index 190778c8..ecbcf5d3 100644
--- a/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java
+++ b/org.eclipselabs.tapiji.tools.core/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java
@@ -8,26 +8,30 @@
import org.eclipselabs.tapiji.tools.core.extensions.I18nAuditor;
import org.eclipselabs.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
+public class ViolationResolutionGenerator implements
+ IMarkerResolutionGenerator2 {
-public class ViolationResolutionGenerator implements IMarkerResolutionGenerator2 {
+ @Override
+ public boolean hasResolutions(IMarker marker) {
+ return true;
+ }
- @Override
- public boolean hasResolutions(IMarker marker) {
- return true;
- }
+ @Override
+ public IMarkerResolution[] getResolutions(IMarker marker) {
+ String contextId = marker.getAttribute("context", "");
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
- String contextId = marker.getAttribute("context", "");
-
- // find resolution generator for the given context
- try {
- I18nAuditor auditor = StringLiteralAuditor.getI18nAuditorByContext(contextId);
- List<IMarkerResolution> resolutions = auditor.getMarkerResolutions(marker);
- return resolutions.toArray(new IMarkerResolution[resolutions.size()]);
- } catch (NoSuchResourceAuditorException e) {}
-
- return new IMarkerResolution[0];
+ // find resolution generator for the given context
+ try {
+ I18nAuditor auditor = StringLiteralAuditor
+ .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.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF
index dfa9644b..77d8cc50 100644
--- a/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF
+++ b/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF
@@ -15,12 +15,15 @@ Import-Package: org.eclipse.core.filebuffers,
org.eclipse.jface.dialogs,
org.eclipse.jface.text,
org.eclipse.jface.text.contentassist,
+ org.eclipse.jface.text.source,
org.eclipse.jface.wizard,
org.eclipse.swt.graphics,
org.eclipse.swt.widgets,
org.eclipse.text.edits,
org.eclipse.ui,
+ org.eclipse.ui.part,
org.eclipse.ui.progress,
+ org.eclipse.ui.texteditor,
org.eclipse.ui.wizards,
org.eclipselabs.tapiji.translator.rbe.babel.bundle,
org.eclipselabs.tapiji.translator.rbe.ui.wizards
diff --git a/org.eclipselabs.tapiji.tools.java/src/auditor/JavaResourceAuditor.java b/org.eclipselabs.tapiji.tools.java/src/auditor/JavaResourceAuditor.java
index b80c1f7a..2c386b8d 100644
--- a/org.eclipselabs.tapiji.tools.java/src/auditor/JavaResourceAuditor.java
+++ b/org.eclipselabs.tapiji.tools.java/src/auditor/JavaResourceAuditor.java
@@ -1,9 +1,11 @@
package auditor;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import java.util.Set;
+import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
@@ -12,8 +14,13 @@
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.CompilationUnit;
+import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.SharedASTProvider;
+import org.eclipse.jface.text.Position;
+import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.IMarkerResolution;
+import org.eclipse.ui.part.FileEditorInput;
+import org.eclipse.ui.texteditor.SimpleMarkerAnnotation;
import org.eclipselabs.tapiji.tools.core.builder.quickfix.CreateResourceBundle;
import org.eclipselabs.tapiji.tools.core.builder.quickfix.IncludeResource;
import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor;
@@ -30,126 +37,166 @@
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>();
-
- public String[] getFileEndings () {
- return new String [] {"java"};
+ 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) {
+ IJavaElement javaElement = JavaCore.create(resource);
+ if (javaElement == null)
+ return;
+
+ if (!(javaElement instanceof ICompilationUnit))
+ return;
+
+ ICompilationUnit icu = (ICompilationUnit) javaElement;
+ ResourceAuditVisitor csav = new ResourceAuditVisitor(resource
+ .getProject().getFile(resource.getProjectRelativePath()),
+ ResourceBundleManager.getManager(resource.getProject()));
+
+ // get the type of the currently loaded resource
+ ITypeRoot typeRoot = icu;
+
+ if (typeRoot == null)
+ return;
+
+ // 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);
+ if (cu == null) {
+ System.out.println("Cannot audit resource: "
+ + resource.getFullPath());
+ return;
}
-
- public void audit(IResource resource) {
- IJavaElement javaElement = JavaCore.create(resource);
- if (javaElement == null)
- return;
-
- if (!(javaElement instanceof ICompilationUnit))
- return;
-
- ICompilationUnit icu = (ICompilationUnit) javaElement;
- ResourceAuditVisitor csav = new ResourceAuditVisitor(
- resource.getProject().getFile(resource.getProjectRelativePath()),
- ResourceBundleManager.getManager(resource.getProject())
- );
-
- // get the type of the currently loaded resource
- ITypeRoot typeRoot = icu;
-
- if (typeRoot == null)
- return;
-
- // 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);
- 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";
+ }
+
+ private Position findProblemPosition(IAnnotationModel model, IMarker marker) {
+ Iterator iter = model.getAnnotationIterator();
+ while (iter.hasNext()) {
+ Object curr = iter.next();
+ if (curr instanceof SimpleMarkerAnnotation) {
+ SimpleMarkerAnnotation annot = (SimpleMarkerAnnotation) curr;
+ if (marker.equals(annot.getMarker())) {
+ return model.getPosition(annot);
}
- 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);
+ return null;
+ }
+
+ @Override
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
+ List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
+ int cause = marker.getAttribute("cause", -1);
+
+ FileEditorInput input = new FileEditorInput(
+ (IFile) marker.getResource());
+
+ IAnnotationModel model = JavaUI.getDocumentProvider()
+ .getAnnotationModel(input);
+
+ // TODO: check if the marker annotation model was generated
+ System.out.println(findProblemPosition(model, marker).getLength());
+
+ switch (marker.getAttribute("cause", -1)) {
+ case IMarkerConstants.CAUSE_CONSTANT_LITERAL:
+ resolutions.add(new ExportToResourceBundleResolution());
+ resolutions.add(new ExcludeResourceFromInternationalization());
+ 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, manager,
+ 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)));
}
- @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 ExportToResourceBundleResolution());
- resolutions.add(new ExcludeResourceFromInternationalization());
- 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, manager, 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;
- }
+ return resolutions;
+ }
}
diff --git a/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF
index 9b5b7ce3..9022be10 100644
--- a/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF
+++ b/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF
@@ -23,6 +23,7 @@ Import-Package: org.eclipse.core.filebuffers,
org.eclipse.swt.graphics,
org.eclipse.swt.widgets,
org.eclipse.ui,
+ org.eclipse.ui.part,
org.eclipse.ui.wizards,
org.eclipse.wst.validation.internal.core,
org.eclipse.wst.validation.internal.provisional.core,
diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
index b60d946c..fef0b2bd 100644
--- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
+++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java
@@ -19,88 +19,94 @@
public class ExportToResourceBundleResolution implements IMarkerResolution2 {
- public ExportToResourceBundleResolution () {
- }
-
- @Override
- public String getDescription() {
- return "Export constant string literal to a resource bundle.";
- }
+ public ExportToResourceBundleResolution() {
+ }
- @Override
- public Image getImage() {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public String getDescription() {
+ return "Export constant string literal to a resource bundle.";
+ }
- @Override
- public String getLabel() {
- return "Export to 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();
- @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(),
- ResourceBundleManager.getManager(resource.getProject()),
- "",
- (startPos < document.getLength() && endPos > 1) ? document.get(startPos, endPos) : "",
- "",
- "");
- 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();
- }
- }
-
+ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(
+ Display.getDefault().getActiveShell(),
+ ResourceBundleManager.getManager(resource.getProject()),
+ "",
+ (startPos < document.getLength() && endPos > 1) ? document
+ .get(startPos, endPos) : "", "", "");
+ 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();
+ }
}
+ }
+
}
|
9ac8731539e821afca215b685203ef82115e36f5
|
orientdb
|
Working to fix corrupted data in sockets--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java
index ef8646b8b48..8d060267d50 100644
--- a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java
+++ b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java
@@ -21,6 +21,7 @@
import java.util.concurrent.locks.ReentrantLock;
import com.orientechnologies.common.concur.OTimeoutException;
+import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
@@ -32,7 +33,7 @@
*
*/
public class OChannelBinaryAsynch extends OChannelBinary {
- private final ReentrantLock lockRead = new ReentrantLock();
+ private final ReentrantLock lockRead = new ReentrantLock(true);
private final ReentrantLock lockWrite = new ReentrantLock();
private boolean channelRead = false;
private byte currentStatus;
@@ -105,7 +106,8 @@ else if (!lockRead.tryLock(iTimeout, TimeUnit.MILLISECONDS))
maxUnreadResponses);
// CALL THE SUPER-METHOD TO AVOID LOCKING AGAIN
- super.clearInput();
+ //super.clearInput();
+ throw new OIOException("Timeout on reading response");
}
lockRead.unlock();
@@ -116,14 +118,14 @@ else if (!lockRead.tryLock(iTimeout, TimeUnit.MILLISECONDS))
synchronized (this) {
try {
if (debug)
- OLogManager.instance().debug(this, "Session %d is going to sleep...", currentSessionId);
+ OLogManager.instance().debug(this, "Session %d is going to sleep...", iRequesterId);
wait(1000);
final long now = System.currentTimeMillis();
if (debug)
OLogManager.instance().debug(this, "Waked up: slept %dms, checking again from %s for session %d", (now - start),
- socket.getLocalAddress(), currentSessionId);
+ socket.getLocalAddress(), iRequesterId);
if (now - start >= 1000)
unreadResponse++;
|
c74a3211ef6bc1dcd10326613b09e426e50839cc
|
couchbase$couchbase-java-client
|
JCBC-575: Add support for a RawJsonDocument.
Motivation
----------
This changeset adds the capabilities to pass in a raw (already encoded)
JSON document, largely driven by the fact that users may already have their
JSON stack set up and just want to pass in the data. We do not want to get
in the way.
Modifications
-------------
Adds the raw JSON document which justs takes the string, expects its valid,
creates a buffer out of it and stores it down. This also is very low overhead.
Result
------
More flexibility in dealing with JSON documents in combination with custom
JSON marshallers.
Change-Id: Ibd7e37ae48de197df72713acd7f4daeadc352904
Reviewed-on: http://review.couchbase.org/41945
Reviewed-by: Sergey Avseyev <[email protected]>
Tested-by: Sergey Avseyev <[email protected]>
|
p
|
https://github.com/couchbase/couchbase-java-client
|
diff --git a/src/main/java/com/couchbase/client/java/document/RawJsonDocument.java b/src/main/java/com/couchbase/client/java/document/RawJsonDocument.java
new file mode 100644
index 00000000..7b6250db
--- /dev/null
+++ b/src/main/java/com/couchbase/client/java/document/RawJsonDocument.java
@@ -0,0 +1,142 @@
+/**
+ * Copyright (C) 2014 Couchbase, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
+ * IN THE SOFTWARE.
+ */
+package com.couchbase.client.java.document;
+
+/**
+ * Represents a {@link Document} that contains a already encoded JSON document.
+ *
+ * The {@link RawJsonDocument} can be used if a custom JSON library is already in place and the content should just
+ * be passed through and properly flagged as JSON on the server side. The only transcoding that is happening internally
+ * is the conversion into bytes from the provided JSON string.
+ *
+ * @author Michael Nitschinger
+ * @since 2.0
+ */
+public class RawJsonDocument extends AbstractDocument<String> {
+
+ /**
+ * Creates a empty {@link RawJsonDocument}.
+ *
+ * @return a empty {@link RawJsonDocument}.
+ */
+ public static RawJsonDocument empty() {
+ return new RawJsonDocument(null, 0, null, 0);
+ }
+
+ /**
+ * Creates a {@link RawJsonDocument} which the document id.
+ *
+ * @param id the per-bucket unique document id.
+ * @return a {@link RawJsonDocument}.
+ */
+ public static RawJsonDocument create(String id) {
+ return new RawJsonDocument(id, 0, null, 0);
+ }
+
+ /**
+ * Creates a {@link RawJsonDocument} which the document id and JSON content.
+ *
+ * @param id the per-bucket unique document id.
+ * @param content the content of the document.
+ * @return a {@link RawJsonDocument}.
+ */
+ public static RawJsonDocument create(String id, String content) {
+ return new RawJsonDocument(id, 0, content, 0);
+ }
+
+ /**
+ * Creates a {@link RawJsonDocument} which the document id, JSON content and the CAS value.
+ *
+ * @param id the per-bucket unique document id.
+ * @param content the content of the document.
+ * @param cas the CAS (compare and swap) value for optimistic concurrency.
+ * @return a {@link RawJsonDocument}.
+ */
+ public static RawJsonDocument create(String id, String content, long cas) {
+ return new RawJsonDocument(id, 0, content, cas);
+ }
+
+ /**
+ * Creates a {@link RawJsonDocument} which the document id, JSON content and the expiration time.
+ *
+ * @param id the per-bucket unique document id.
+ * @param content the content of the document.
+ * @param expiry the expiration time of the document.
+ * @return a {@link RawJsonDocument}.
+ */
+ public static RawJsonDocument create(String id, int expiry, String content) {
+ return new RawJsonDocument(id, expiry, content, 0);
+ }
+
+ /**
+ * Creates a {@link RawJsonDocument} which the document id, JSON content, CAS value, expiration time and status code.
+ *
+ * This factory method is normally only called within the client library when a response is analyzed and a document
+ * is returned which is enriched with the status code. It does not make sense to pre populate the status field from
+ * the user level code.
+ *
+ * @param id the per-bucket unique document id.
+ * @param content the content of the document.
+ * @param cas the CAS (compare and swap) value for optimistic concurrency.
+ * @param expiry the expiration time of the document.
+ * @return a {@link RawJsonDocument}.
+ */
+ public static RawJsonDocument create(String id, int expiry, String content, long cas) {
+ return new RawJsonDocument(id, expiry, content, cas);
+ }
+
+ /**
+ * Creates a copy from a different {@link RawJsonDocument}, but changes the document ID and content.
+ *
+ * @param doc the original {@link RawJsonDocument} to copy.
+ * @param id the per-bucket unique document id.
+ * @param content the content of the document.
+ * @return a copied {@link RawJsonDocument} with the changed properties.
+ */
+ public static RawJsonDocument from(RawJsonDocument doc, String id, String content) {
+ return RawJsonDocument.create(id, doc.expiry(), content, doc.cas());
+ }
+
+ /**
+ * Creates a copy from a different {@link RawJsonDocument}, but changes the CAS value.
+ *
+ * @param doc the original {@link RawJsonDocument} to copy.
+ * @param cas the CAS (compare and swap) value for optimistic concurrency.
+ * @return a copied {@link RawJsonDocument} with the changed properties.
+ */
+ public static RawJsonDocument from(RawJsonDocument doc, long cas) {
+ return RawJsonDocument.create(doc.id(), doc.expiry(), doc.content(), cas);
+ }
+
+ /**
+ * Private constructor which is called by the static factory methods eventually.
+ *
+ * @param id the per-bucket unique document id.
+ * @param content the content of the document.
+ * @param cas the CAS (compare and swap) value for optimistic concurrency.
+ * @param expiry the expiration time of the document.
+ */
+ private RawJsonDocument(String id, int expiry, String content, long cas) {
+ super(id, expiry, content, cas);
+ }
+
+}
diff --git a/src/main/java/com/couchbase/client/java/transcoder/RawJsonTranscoder.java b/src/main/java/com/couchbase/client/java/transcoder/RawJsonTranscoder.java
new file mode 100644
index 00000000..dcbb4f0d
--- /dev/null
+++ b/src/main/java/com/couchbase/client/java/transcoder/RawJsonTranscoder.java
@@ -0,0 +1,69 @@
+/**
+ * Copyright (C) 2014 Couchbase, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
+ * IN THE SOFTWARE.
+ */
+package com.couchbase.client.java.transcoder;
+
+import com.couchbase.client.core.lang.Tuple;
+import com.couchbase.client.core.lang.Tuple2;
+import com.couchbase.client.core.message.ResponseStatus;
+import com.couchbase.client.deps.io.netty.buffer.ByteBuf;
+import com.couchbase.client.deps.io.netty.buffer.Unpooled;
+import com.couchbase.client.deps.io.netty.util.CharsetUtil;
+import com.couchbase.client.java.document.RawJsonDocument;
+import com.couchbase.client.java.error.TranscodingException;
+
+/**
+ * A transcoder to encode and decode a {@link RawJsonDocument}s.
+ *
+ * @author Michael Nitschinger
+ * @since 2.0
+ */
+public class RawJsonTranscoder extends AbstractTranscoder<RawJsonDocument, String> {
+
+ @Override
+ protected Tuple2<ByteBuf, Integer> doEncode(RawJsonDocument document) throws Exception {
+ return Tuple.create(Unpooled.copiedBuffer(document.content(), CharsetUtil.UTF_8),
+ TranscoderUtils.JSON_COMPAT_FLAGS);
+ }
+
+ @Override
+ protected RawJsonDocument doDecode(String id, ByteBuf content, long cas, int expiry, int flags,
+ ResponseStatus status) throws Exception {
+ if (!TranscoderUtils.hasJsonFlags(flags)) {
+ throw new TranscodingException("Flags (0x" + Integer.toHexString(flags) + ") indicate non-JSON document for "
+ + "id " + id + ", could not decode.");
+ }
+
+ String converted = content.toString(CharsetUtil.UTF_8);
+ content.release();
+ return newDocument(id, expiry, converted, cas);
+ }
+
+ @Override
+ public RawJsonDocument newDocument(String id, int expiry, String content, long cas) {
+ return RawJsonDocument.create(id, expiry, content, cas);
+ }
+
+ @Override
+ public Class<RawJsonDocument> documentType() {
+ return RawJsonDocument.class;
+ }
+}
diff --git a/src/test/java/com/couchbase/client/java/query/dsl/SelectDslSmokeTest.java b/src/test/java/com/couchbase/client/java/query/dsl/SelectDslSmokeTest.java
index 8349cad7..da6f550f 100644
--- a/src/test/java/com/couchbase/client/java/query/dsl/SelectDslSmokeTest.java
+++ b/src/test/java/com/couchbase/client/java/query/dsl/SelectDslSmokeTest.java
@@ -39,7 +39,7 @@
* @author Michael Nitschinger
* @since 2.0
*/
-public class SelectDslSomokeTest {
+public class SelectDslSmokeTest {
@Test
public void test1() {
diff --git a/src/test/java/com/couchbase/client/java/transcoder/BinaryTranscoderTest.java b/src/test/java/com/couchbase/client/java/transcoder/BinaryTranscoderTest.java
index e3873ea7..01775f6f 100644
--- a/src/test/java/com/couchbase/client/java/transcoder/BinaryTranscoderTest.java
+++ b/src/test/java/com/couchbase/client/java/transcoder/BinaryTranscoderTest.java
@@ -1,3 +1,24 @@
+/**
+ * Copyright (C) 2014 Couchbase, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
+ * IN THE SOFTWARE.
+ */
package com.couchbase.client.java.transcoder;
import com.couchbase.client.core.lang.Tuple2;
@@ -5,6 +26,7 @@
import com.couchbase.client.deps.io.netty.buffer.Unpooled;
import com.couchbase.client.deps.io.netty.util.CharsetUtil;
import com.couchbase.client.java.document.BinaryDocument;
+import org.junit.Ignore;
import org.junit.Before;
import org.junit.Test;
@@ -29,11 +51,13 @@ public void shouldEncodeBinary() {
}
@Test
+ @Ignore
public void shouldDecodeCommonBinary() {
}
@Test
+ @Ignore
public void shouldDecodeLegacyBinary() {
}
diff --git a/src/test/java/com/couchbase/client/java/transcoder/JsonDoubleTranscoderTest.java b/src/test/java/com/couchbase/client/java/transcoder/JsonDoubleTranscoderTest.java
index 5da46a6b..3bca73b5 100644
--- a/src/test/java/com/couchbase/client/java/transcoder/JsonDoubleTranscoderTest.java
+++ b/src/test/java/com/couchbase/client/java/transcoder/JsonDoubleTranscoderTest.java
@@ -1,3 +1,24 @@
+/**
+ * Copyright (C) 2014 Couchbase, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
+ * IN THE SOFTWARE.
+ */
package com.couchbase.client.java.transcoder;
import com.couchbase.client.core.lang.Tuple2;
diff --git a/src/test/java/com/couchbase/client/java/transcoder/JsonStringTranscoderTest.java b/src/test/java/com/couchbase/client/java/transcoder/JsonStringTranscoderTest.java
index 9f6516ff..29a44be7 100644
--- a/src/test/java/com/couchbase/client/java/transcoder/JsonStringTranscoderTest.java
+++ b/src/test/java/com/couchbase/client/java/transcoder/JsonStringTranscoderTest.java
@@ -1,3 +1,24 @@
+/**
+ * Copyright (C) 2014 Couchbase, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
+ * IN THE SOFTWARE.
+ */
package com.couchbase.client.java.transcoder;
import com.couchbase.client.core.lang.Tuple2;
diff --git a/src/test/java/com/couchbase/client/java/transcoder/RawJsonTranscoderTest.java b/src/test/java/com/couchbase/client/java/transcoder/RawJsonTranscoderTest.java
new file mode 100644
index 00000000..0411da78
--- /dev/null
+++ b/src/test/java/com/couchbase/client/java/transcoder/RawJsonTranscoderTest.java
@@ -0,0 +1,62 @@
+/**
+ * Copyright (C) 2014 Couchbase, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
+ * IN THE SOFTWARE.
+ */
+package com.couchbase.client.java.transcoder;
+
+import com.couchbase.client.core.lang.Tuple2;
+import com.couchbase.client.core.message.ResponseStatus;
+import com.couchbase.client.deps.io.netty.buffer.ByteBuf;
+import com.couchbase.client.deps.io.netty.buffer.Unpooled;
+import com.couchbase.client.deps.io.netty.util.CharsetUtil;
+import com.couchbase.client.java.document.RawJsonDocument;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class RawJsonTranscoderTest {
+
+ private RawJsonTranscoder converter;
+
+ @Before
+ public void setup() {
+ converter = new RawJsonTranscoder();
+ }
+
+ @Test
+ public void shouldEncodeRawJson() {
+ RawJsonDocument document = RawJsonDocument.create("id", "{\"test:\":true}");
+ Tuple2<ByteBuf, Integer> encoded = converter.encode(document);
+
+ assertEquals("{\"test:\":true}", encoded.value1().toString(CharsetUtil.UTF_8));
+ assertEquals(TranscoderUtils.JSON_COMPAT_FLAGS, (long) encoded.value2());
+ }
+
+ @Test
+ public void shouldDecodeRawJson() {
+ ByteBuf content = Unpooled.copiedBuffer("{\"test:\":true}", CharsetUtil.UTF_8);
+ RawJsonDocument decoded = converter.decode("id", content, 0, 0, TranscoderUtils.JSON_COMPAT_FLAGS,
+ ResponseStatus.SUCCESS);
+
+ assertEquals("{\"test:\":true}", decoded.content());
+ }
+
+}
diff --git a/src/test/java/com/couchbase/client/java/transcoder/StringTranscoderTest.java b/src/test/java/com/couchbase/client/java/transcoder/StringTranscoderTest.java
index 547b203e..e9f164b9 100644
--- a/src/test/java/com/couchbase/client/java/transcoder/StringTranscoderTest.java
+++ b/src/test/java/com/couchbase/client/java/transcoder/StringTranscoderTest.java
@@ -1,3 +1,24 @@
+/**
+ * Copyright (C) 2014 Couchbase, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
+ * IN THE SOFTWARE.
+ */
package com.couchbase.client.java.transcoder;
import com.couchbase.client.core.lang.Tuple2;
|
28a4035f884b1de99d7d48ce4d08dcf89f84e3a2
|
Vala
|
gio-2.0: various ownership and type_arguments fixes for generics
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi
index 5275479583..87de1b20d7 100644
--- a/vapi/gio-2.0.vapi
+++ b/vapi/gio-2.0.vapi
@@ -6,8 +6,8 @@ namespace GLib {
public class AppLaunchContext : GLib.Object {
[CCode (has_construct_function = false)]
public AppLaunchContext ();
- public virtual unowned string get_display (GLib.AppInfo info, GLib.List files);
- public virtual unowned string get_startup_notify_id (GLib.AppInfo info, GLib.List files);
+ public virtual unowned string get_display (GLib.AppInfo info, GLib.List<GLib.File> files);
+ public virtual unowned string get_startup_notify_id (GLib.AppInfo info, GLib.List<GLib.File> files);
public virtual void launch_failed (string startup_notify_id);
}
[CCode (cheader_filename = "gio/gio.h")]
@@ -117,7 +117,7 @@ namespace GLib {
[CCode (type = "GIcon*", has_construct_function = false)]
public EmblemedIcon (GLib.Icon icon, GLib.Emblem emblem);
public void add_emblem (GLib.Emblem emblem);
- public unowned GLib.List get_emblems ();
+ public unowned GLib.List<GLib.Emblem> get_emblems ();
public unowned GLib.Icon get_icon ();
}
[Compact]
@@ -342,7 +342,7 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public class IOExtensionPoint {
public unowned GLib.IOExtension get_extension_by_name (string name);
- public unowned GLib.List get_extensions ();
+ public unowned GLib.List<GLib.IOExtension> get_extensions ();
public GLib.Type get_required_type ();
public static unowned GLib.IOExtension implement (string extension_point_name, GLib.Type type, string extension_name, int priority);
public static unowned GLib.IOExtensionPoint lookup (string name);
@@ -562,8 +562,6 @@ namespace GLib {
[CCode (cheader_filename = "gio/gio.h")]
public class Resolver : GLib.Object {
public static GLib.Quark error_quark ();
- public static void free_addresses (GLib.List addresses);
- public static void free_targets (GLib.List targets);
public static unowned GLib.Resolver get_default ();
public virtual unowned string lookup_by_address (GLib.InetAddress address, GLib.Cancellable? cancellable) throws GLib.Error;
public virtual async unowned string lookup_by_address_async (GLib.InetAddress address, GLib.Cancellable? cancellable) throws GLib.Error;
@@ -813,7 +811,7 @@ namespace GLib {
public uint16 get_port ();
public uint16 get_priority ();
public uint16 get_weight ();
- public static unowned GLib.List list_sort (GLib.List targets);
+ public static GLib.List<GLib.SrvTarget> list_sort (owned GLib.List<GLib.SrvTarget> targets);
}
[CCode (cheader_filename = "gio/gio.h")]
public class TcpConnection : GLib.SocketConnection {
@@ -875,11 +873,11 @@ namespace GLib {
public class VolumeMonitor : GLib.Object {
public virtual unowned GLib.Volume adopt_orphan_mount (GLib.Mount mount);
public static GLib.VolumeMonitor @get ();
- public virtual GLib.List get_connected_drives ();
+ public virtual GLib.List<GLib.Drive> get_connected_drives ();
public virtual GLib.Mount get_mount_for_uuid (string uuid);
- public virtual GLib.List get_mounts ();
+ public virtual GLib.List<GLib.Mount> get_mounts ();
public virtual GLib.Volume get_volume_for_uuid (string uuid);
- public virtual GLib.List get_volumes ();
+ public virtual GLib.List<GLib.Volume> get_volumes ();
[NoWrapper]
public virtual bool is_supported ();
public virtual signal void drive_changed (GLib.Drive drive);
@@ -906,8 +904,8 @@ namespace GLib {
public abstract bool do_delete ();
public abstract unowned GLib.AppInfo dup ();
public abstract bool equal (GLib.AppInfo appinfo2);
- public static unowned GLib.List get_all ();
- public static unowned GLib.List get_all_for_type (string content_type);
+ public static GLib.List<GLib.AppInfo> get_all ();
+ public static GLib.List<GLib.AppInfo> get_all_for_type (string content_type);
public abstract unowned string get_commandline ();
public static unowned GLib.AppInfo get_default_for_type (string content_type, bool must_support_uris);
public static unowned GLib.AppInfo get_default_for_uri_scheme (string uri_scheme);
@@ -916,9 +914,9 @@ namespace GLib {
public abstract unowned GLib.Icon get_icon ();
public abstract unowned string get_id ();
public abstract unowned string get_name ();
- public abstract bool launch (GLib.List? files, GLib.AppLaunchContext? launch_context) throws GLib.Error;
+ public abstract bool launch (GLib.List<GLib.File>? files, GLib.AppLaunchContext? launch_context) throws GLib.Error;
public static bool launch_default_for_uri (string uri, GLib.AppLaunchContext? launch_context) throws GLib.Error;
- public abstract bool launch_uris (GLib.List? uris, GLib.AppLaunchContext launch_context) throws GLib.Error;
+ public abstract bool launch_uris (GLib.List<string>? uris, GLib.AppLaunchContext launch_context) throws GLib.Error;
public abstract bool remove_supports_type (string content_type) throws GLib.Error;
public static void reset_type_associations (string content_type);
public abstract bool set_as_default_for_extension (string extension) throws GLib.Error;
@@ -957,7 +955,7 @@ namespace GLib {
public abstract unowned string get_identifier (string kind);
public abstract unowned string get_name ();
public abstract GLib.DriveStartStopType get_start_stop_type ();
- public abstract unowned GLib.List get_volumes ();
+ public abstract GLib.List<GLib.Volume> get_volumes ();
public abstract bool has_media ();
public abstract bool has_volumes ();
public abstract bool is_media_check_automatic ();
@@ -1619,13 +1617,13 @@ namespace GLib {
[CCode (cname = "g_content_type_is_unknown", cheader_filename = "gio/gio.h")]
public static bool g_content_type_is_unknown (string type);
[CCode (cname = "g_content_types_get_registered", cheader_filename = "gio/gio.h")]
- public static unowned GLib.List g_content_types_get_registered ();
+ public static GLib.List<string> g_content_types_get_registered ();
[CCode (cname = "g_io_error_from_errno", cheader_filename = "gio/gio.h")]
public static unowned GLib.IOError g_io_error_from_errno (int err_no);
[CCode (cname = "g_io_error_quark", cheader_filename = "gio/gio.h")]
public static GLib.Quark g_io_error_quark ();
[CCode (cname = "g_io_modules_load_all_in_directory", cheader_filename = "gio/gio.h")]
- public static unowned GLib.List g_io_modules_load_all_in_directory (string dirname);
+ public static GLib.List<weak GLib.TypeModule> g_io_modules_load_all_in_directory (string dirname);
[CCode (cname = "g_io_scheduler_cancel_all_jobs", cheader_filename = "gio/gio.h")]
public static void g_io_scheduler_cancel_all_jobs ();
[CCode (cname = "g_io_scheduler_push_job", cheader_filename = "gio/gio.h")]
diff --git a/vapi/packages/gio-2.0/gio-2.0.metadata b/vapi/packages/gio-2.0/gio-2.0.metadata
index 17defe2321..b7c3d6db94 100644
--- a/vapi/packages/gio-2.0/gio-2.0.metadata
+++ b/vapi/packages/gio-2.0/gio-2.0.metadata
@@ -1,12 +1,17 @@
GLib cprefix="G" lower_case_cprefix="g_" cheader_filename="gio/gio.h" gir_namespace="Gio" gir_version="2.0"
+g_app_info_get_all type_arguments="AppInfo" transfer_ownership="1"
+g_app_info_get_all_for_type type_arguments="AppInfo" transfer_ownership="1"
g_app_info_launch.envp is_array="1"
g_app_info_launch.launch_context nullable="1"
g_app_info_launch_default_for_uri.launch_context nullable="1"
g_app_info_launch_uris.envp is_array="1"
+g_app_launch_context_get_display.files type_arguments="File"
+g_app_launch_context_get_startup_notify_id.files type_arguments="File"
GAsyncReadyCallback.source_object nullable="1"
g_buffered_input_stream_peek_buffer.count is_out="1"
g_content_type_guess.data_size hidden="1"
g_content_type_guess.result_uncertain is_out="1"
+g_content_types_get_registered type_arguments="string" transfer_ownership="1"
g_data_input_stream_read_line nullable="1" transfer_ownership="1"
g_data_input_stream_read_line.length is_out="1"
g_data_input_stream_read_line_finish nullable="1" transfer_ownership="1"
@@ -17,9 +22,11 @@ g_data_input_stream_read_until_finish nullable="1" transfer_ownership="1"
g_data_input_stream_read_until_finish.length is_out="1"
g_drive_eject async="1"
g_drive_eject_with_operation async="1"
+g_drive_get_volumes type_arguments="Volume" transfer_ownership="1"
g_drive_poll_for_media async="1"
g_drive_start async="1"
g_drive_stop async="1"
+g_emblemed_icon_get_emblems type_arguments="Emblem"
g_file_append_to transfer_ownership="1"
g_file_append_to_finish transfer_ownership="1"
g_file_copy.progress_callback_data hidden="1"
@@ -84,6 +91,8 @@ g_file_unmount_mountable_with_operation async="1"
g_inet_address_to_string transfer_ownership="1"
g_input_stream_read_all.bytes_read is_out="1"
GIOErrorEnum rename_to="IOError" errordomain="1"
+g_io_extension_point_get_extensions type_arguments="IOExtension"
+g_io_modules_load_all_in_directory type_arguments="unowned TypeModule" transfer_ownership="1"
g_memory_input_stream_add_data.destroy nullable="1"
g_memory_input_stream_new_from_data.destroy nullable="1"
g_mount_eject async="1"
@@ -94,6 +103,8 @@ g_mount_unmount async="1"
g_mount_unmount_with_operation async="1"
GMountOperation::reply has_emitter="1"
g_output_stream_write_all.bytes_written is_out="1"
+g_resolver_free_addresses hidden="1"
+g_resolver_free_targets hidden="1"
g_resolver_lookup_by_name transfer_ownership="1" type_arguments="InetAddress"
g_resolver_lookup_by_name_finish transfer_ownership="1" type_arguments="InetAddress"
g_resolver_lookup_service transfer_ownership="1" type_arguments="SrvTarget"
@@ -103,6 +114,8 @@ g_seekable_truncate_fn hidden="1"
g_socket_listener_add_address.source_object nullable="1"
g_socket_listener_add_inet_port.source_object nullable="1"
g_socket_listener_add_socket.source_object nullable="1"
+g_srv_target_list_sort type_arguments="SrvTarget" transfer_ownership="1"
+g_srv_target_list_sort.targets type_arguments="SrvTarget" transfer_ownership="1"
g_themed_icon_new_from_names.iconnames is_array="1"
g_themed_icon_new_from_names.len hidden="1"
g_themed_icon_get_names is_array="1" no_array_length="1"
@@ -138,8 +151,8 @@ g_file_info_get_attribute_data.value_pp nullable="1"
g_file_info_get_attribute_data.status nullable="1"
g_app_info_create_from_commandline.app_name nullable="1"
-g_app_info_launch.files nullable="1"
-g_app_info_launch_uris.uris nullable="1"
+g_app_info_launch.files nullable="1" type_arguments="File"
+g_app_info_launch_uris.uris nullable="1" type_arguments="string"
g_loadable_icon_load.type nullable="1"
g_loadable_icon_load_finish.type nullable="1"
@@ -162,8 +175,8 @@ g_simple_async_result_new.source_object nullable="1"
GSocketService::incoming.source_object nullable="1"
g_volume_monitor_get transfer_ownership="1"
-g_volume_monitor_get_connected_drives transfer_ownership="1"
+g_volume_monitor_get_connected_drives type_arguments="Drive" transfer_ownership="1"
g_volume_monitor_get_mount_for_uuid transfer_ownership="1"
-g_volume_monitor_get_mounts transfer_ownership="1"
+g_volume_monitor_get_mounts type_arguments="Mount" transfer_ownership="1"
g_volume_monitor_get_volume_for_uuid transfer_ownership="1"
-g_volume_monitor_get_volumes transfer_ownership="1"
+g_volume_monitor_get_volumes type_arguments="Volume" transfer_ownership="1"
|
3e74d3b2fbea16c55805b9b73c182bdc02e70b83
|
spring-framework
|
Add putIfAbsent on Cache abstraction--This commit adds a putIfAbsent method to the Cache interface. This-method offers an atomic put if the key is not already associated in-the cache.--Issue: SPR-11400-
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheCache.java b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheCache.java
index c730c637e893..31bfd2f530cb 100644
--- a/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheCache.java
+++ b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheCache.java
@@ -29,6 +29,7 @@
*
* @author Costin Leau
* @author Juergen Hoeller
+ * @author Stephane Nicoll
* @since 3.1
*/
public class EhCacheCache implements Cache {
@@ -62,7 +63,7 @@ public final Ehcache getNativeCache() {
@Override
public ValueWrapper get(Object key) {
Element element = this.cache.get(key);
- return (element != null ? new SimpleValueWrapper(element.getObjectValue()) : null);
+ return toWrapper(element);
}
@Override
@@ -81,6 +82,12 @@ public void put(Object key, Object value) {
this.cache.put(new Element(key, value));
}
+ @Override
+ public ValueWrapper putIfAbsent(Object key, Object value) {
+ Element existingElement = this.cache.putIfAbsent(new Element(key, value));
+ return toWrapper(existingElement);
+ }
+
@Override
public void evict(Object key) {
this.cache.remove(key);
@@ -91,4 +98,8 @@ public void clear() {
this.cache.removeAll();
}
+ private ValueWrapper toWrapper(Element element) {
+ return (element != null ? new SimpleValueWrapper(element.getObjectValue()) : null);
+ }
+
}
diff --git a/spring-context-support/src/main/java/org/springframework/cache/guava/GuavaCache.java b/spring-context-support/src/main/java/org/springframework/cache/guava/GuavaCache.java
index 6a9cf4cbe73f..6acc2aad0b6c 100644
--- a/spring-context-support/src/main/java/org/springframework/cache/guava/GuavaCache.java
+++ b/spring-context-support/src/main/java/org/springframework/cache/guava/GuavaCache.java
@@ -17,6 +17,8 @@
package org.springframework.cache.guava;
import java.io.Serializable;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
@@ -29,6 +31,7 @@
* <p>Requires Google Guava 12.0 or higher.
*
* @author Juergen Hoeller
+ * @author Stephane Nicoll
* @since 4.0
*/
public class GuavaCache implements Cache {
@@ -83,7 +86,7 @@ public final boolean isAllowNullValues() {
@Override
public ValueWrapper get(Object key) {
Object value = this.cache.getIfPresent(key);
- return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
+ return toWrapper(value);
}
@Override
@@ -101,6 +104,17 @@ public void put(Object key, Object value) {
this.cache.put(key, toStoreValue(value));
}
+ @Override
+ public ValueWrapper putIfAbsent(Object key, final Object value) {
+ try {
+ PutIfAbsentCallable callable = new PutIfAbsentCallable(value);
+ Object result = this.cache.get(key, callable);
+ return (callable.called ? null : toWrapper(result));
+ } catch (ExecutionException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+
@Override
public void evict(Object key) {
this.cache.invalidate(key);
@@ -138,9 +152,29 @@ protected Object toStoreValue(Object userValue) {
return userValue;
}
+ private ValueWrapper toWrapper(Object value) {
+ return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
+ }
+
@SuppressWarnings("serial")
private static class NullHolder implements Serializable {
}
+ private class PutIfAbsentCallable implements Callable<Object> {
+ private boolean called;
+
+ private final Object value;
+
+ private PutIfAbsentCallable(Object value) {
+ this.value = value;
+ }
+
+ @Override
+ public Object call() throws Exception {
+ called = true;
+ return toStoreValue(value);
+ }
+ }
+
}
diff --git a/spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCache.java b/spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCache.java
index a0b34470f188..372e754c9fad 100644
--- a/spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCache.java
+++ b/spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCache.java
@@ -29,6 +29,7 @@
* <p>Note: This class has been updated for JCache 1.0, as of Spring 4.0.
*
* @author Juergen Hoeller
+ * @author Stephane Nicoll
* @since 3.2
*/
public class JCacheCache implements Cache {
@@ -95,6 +96,12 @@ public void put(Object key, Object value) {
this.cache.put(key, toStoreValue(value));
}
+ @Override
+ public ValueWrapper putIfAbsent(Object key, Object value) {
+ boolean set = this.cache.putIfAbsent(key, toStoreValue(value));
+ return (set ? null : get(key));
+ }
+
@Override
public void evict(Object key) {
this.cache.remove(key);
diff --git a/spring-context-support/src/main/java/org/springframework/cache/transaction/TransactionAwareCacheDecorator.java b/spring-context-support/src/main/java/org/springframework/cache/transaction/TransactionAwareCacheDecorator.java
index adc931abe33b..e239b96d1ee1 100644
--- a/spring-context-support/src/main/java/org/springframework/cache/transaction/TransactionAwareCacheDecorator.java
+++ b/spring-context-support/src/main/java/org/springframework/cache/transaction/TransactionAwareCacheDecorator.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.
@@ -28,7 +28,11 @@
* successful transaction. If no transaction is active, {@link #put} and {@link #evict}
* operations will be performed immediately, as usual.
*
+ * <p>Use of more aggressive operations such as {@link #putIfAbsent} cannot be deferred
+ * to the after-commit phase of a running transaction. Use these with care.
+ *
* @author Juergen Hoeller
+ * @author Stephane Nicoll
* @since 3.2
* @see TransactionAwareCacheManagerProxy
*/
@@ -82,6 +86,11 @@ public void afterCommit() {
}
}
+ @Override
+ public ValueWrapper putIfAbsent(final Object key, final Object value) {
+ return this.targetCache.putIfAbsent(key, value);
+ }
+
@Override
public void evict(final Object key) {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
diff --git a/spring-context-support/src/test/java/org/springframework/cache/AbstractCacheTests.java b/spring-context-support/src/test/java/org/springframework/cache/AbstractCacheTests.java
new file mode 100644
index 000000000000..ba41bfa1800f
--- /dev/null
+++ b/spring-context-support/src/test/java/org/springframework/cache/AbstractCacheTests.java
@@ -0,0 +1,105 @@
+/*
+ * 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.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+/**
+ * @author Stephane Nicoll
+ */
+public abstract class AbstractCacheTests<T extends Cache> {
+
+ protected final static String CACHE_NAME = "testCache";
+
+ protected abstract T getCache();
+
+ protected abstract Object getNativeCache();
+
+ @Test
+ public void testCacheName() throws Exception {
+ assertEquals(CACHE_NAME, getCache().getName());
+ }
+
+ @Test
+ public void testNativeCache() throws Exception {
+ assertSame(getNativeCache(), getCache().getNativeCache());
+ }
+
+ @Test
+ public void testCachePut() throws Exception {
+ T cache = getCache();
+
+ Object key = "enescu";
+ Object value = "george";
+
+ assertNull(cache.get(key));
+ assertNull(cache.get(key, String.class));
+ assertNull(cache.get(key, Object.class));
+
+ cache.put(key, value);
+ assertEquals(value, cache.get(key).get());
+ assertEquals(value, cache.get(key, String.class));
+ assertEquals(value, cache.get(key, Object.class));
+ assertEquals(value, cache.get(key, null));
+
+ cache.put(key, null);
+ assertNotNull(cache.get(key));
+ assertNull(cache.get(key).get());
+ assertNull(cache.get(key, String.class));
+ assertNull(cache.get(key, Object.class));
+ }
+
+ @Test
+ public void testCachePutIfAbsent() throws Exception {
+ T cache = getCache();
+
+ Object key = new Object();
+ Object value = "initialValue";
+
+ assertNull(cache.get(key));
+ assertNull(cache.putIfAbsent(key, value));
+ assertEquals(value, cache.get(key).get());
+ assertEquals("initialValue", cache.putIfAbsent(key, "anotherValue").get());
+ assertEquals(value, cache.get(key).get()); // not changed
+ }
+
+ @Test
+ public void testCacheRemove() throws Exception {
+ T cache = getCache();
+
+ Object key = "enescu";
+ Object value = "george";
+
+ assertNull(cache.get(key));
+ cache.put(key, value);
+ }
+
+ @Test
+ public void testCacheClear() throws Exception {
+ T cache = getCache();
+
+ assertNull(cache.get("enescu"));
+ cache.put("enescu", "george");
+ assertNull(cache.get("vlaicu"));
+ cache.put("vlaicu", "aurel");
+ cache.clear();
+ assertNull(cache.get("vlaicu"));
+ assertNull(cache.get("enescu"));
+ }
+}
diff --git a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheCacheTests.java b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheCacheTests.java
index 587eb95a1f3c..b6d58d214d17 100644
--- a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheCacheTests.java
+++ b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheCacheTests.java
@@ -16,56 +16,55 @@
package org.springframework.cache.ehcache;
+import static org.junit.Assert.*;
+
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
+import net.sf.ehcache.config.Configuration;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-
-import org.springframework.cache.Cache;
+import org.springframework.cache.AbstractCacheTests;
import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
-import static org.junit.Assert.*;
-
/**
* @author Costin Leau
+ * @author Stephane Nicoll
* @author Juergen Hoeller
*/
-public class EhCacheCacheTests {
-
- protected final static String CACHE_NAME = "testCache";
-
- protected Ehcache nativeCache;
-
- protected Cache cache;
+public class EhCacheCacheTests extends AbstractCacheTests<EhCacheCache> {
+ private CacheManager cacheManager;
+ private Ehcache nativeCache;
+ private EhCacheCache cache;
@Before
- public void setUp() throws Exception {
- if (CacheManager.getInstance().cacheExists(CACHE_NAME)) {
- nativeCache = CacheManager.getInstance().getEhcache(CACHE_NAME);
- }
- else {
- nativeCache = new net.sf.ehcache.Cache(new CacheConfiguration(CACHE_NAME, 100));
- CacheManager.getInstance().addCache(nativeCache);
- }
+ public void setUp() {
+ cacheManager = new CacheManager(new Configuration().name("EhCacheCacheTests")
+ .defaultCache(new CacheConfiguration("default", 100)));
+ nativeCache = new net.sf.ehcache.Cache(new CacheConfiguration(CACHE_NAME, 100));
+ cacheManager.addCache(nativeCache);
+
cache = new EhCacheCache(nativeCache);
- cache.clear();
}
-
- @Test
- public void testCacheName() throws Exception {
- assertEquals(CACHE_NAME, cache.getName());
+ @After
+ public void tearDown() {
+ cacheManager.shutdown();
}
- @Test
- public void testNativeCache() throws Exception {
- assertSame(nativeCache, cache.getNativeCache());
+ @Override
+ protected EhCacheCache getCache() {
+ return cache;
}
+ @Override
+ protected Ehcache getNativeCache() {
+ return nativeCache;
+ }
@Test
public void testCachePut() throws Exception {
Object key = "enescu";
@@ -88,26 +87,6 @@ public void testCachePut() throws Exception {
assertNull(cache.get(key, Object.class));
}
- @Test
- public void testCacheRemove() throws Exception {
- Object key = "enescu";
- Object value = "george";
-
- assertNull(cache.get(key));
- cache.put(key, value);
- }
-
- @Test
- public void testCacheClear() throws Exception {
- assertNull(cache.get("enescu"));
- cache.put("enescu", "george");
- assertNull(cache.get("vlaicu"));
- cache.put("vlaicu", "aurel");
- cache.clear();
- assertNull(cache.get("vlaicu"));
- assertNull(cache.get("enescu"));
- }
-
@Test
public void testExpiredElements() throws Exception {
Assume.group(TestGroup.LONG_RUNNING);
@@ -123,5 +102,4 @@ public void testExpiredElements() throws Exception {
Thread.sleep(5 * 1000);
assertNull(cache.get(key));
}
-
}
diff --git a/spring-context-support/src/test/java/org/springframework/cache/guava/GuavaCacheTests.java b/spring-context-support/src/test/java/org/springframework/cache/guava/GuavaCacheTests.java
new file mode 100644
index 000000000000..763e56abb2be
--- /dev/null
+++ b/spring-context-support/src/test/java/org/springframework/cache/guava/GuavaCacheTests.java
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.guava;
+
+import static org.junit.Assert.*;
+
+import com.google.common.cache.CacheBuilder;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.springframework.cache.AbstractCacheTests;
+import org.springframework.cache.Cache;
+
+/**
+ * @author Stephane Nicoll
+ */
+public class GuavaCacheTests extends AbstractCacheTests<GuavaCache> {
+
+ private com.google.common.cache.Cache<Object, Object> nativeCache;
+ private GuavaCache cache;
+
+ @Before
+ public void setUp() {
+ nativeCache = CacheBuilder.newBuilder().build();
+ cache = new GuavaCache(CACHE_NAME, nativeCache);
+ }
+
+ @Override
+ protected GuavaCache getCache() {
+ return cache;
+ }
+
+ @Override
+ protected Object getNativeCache() {
+ return nativeCache;
+ }
+
+ @Test
+ public void putIfAbsentNullValue() throws Exception {
+ GuavaCache cache = getCache();
+
+ Object key = new Object();
+ Object value = null;
+
+ assertNull(cache.get(key));
+ assertNull(cache.putIfAbsent(key, value));
+ assertEquals(value, cache.get(key).get());
+ Cache.ValueWrapper wrapper = cache.putIfAbsent(key, "anotherValue");
+ assertNotNull(wrapper); // A value is set but is 'null'
+ assertEquals(null, wrapper.get());
+ assertEquals(value, cache.get(key).get()); // not changed
+ }
+}
diff --git a/spring-context-support/src/test/java/org/springframework/cache/transaction/TransactionAwareCacheDecoratorTests.java b/spring-context-support/src/test/java/org/springframework/cache/transaction/TransactionAwareCacheDecoratorTests.java
index 553aa74b1607..e43c721bd33a 100644
--- a/spring-context-support/src/test/java/org/springframework/cache/transaction/TransactionAwareCacheDecoratorTests.java
+++ b/spring-context-support/src/test/java/org/springframework/cache/transaction/TransactionAwareCacheDecoratorTests.java
@@ -90,6 +90,18 @@ public void putTransactional() {
assertEquals("123", target.get(key, String.class));
}
+ @Test
+ public void putIfAbsent() { // no transactional support for putIfAbsent
+ Cache target = new ConcurrentMapCache("testCache");
+ Cache cache = new TransactionAwareCacheDecorator(target);
+
+ Object key = new Object();
+ assertNull(cache.putIfAbsent(key, "123"));
+ assertEquals("123", target.get(key, String.class));
+ assertEquals("123", cache.putIfAbsent(key, "456").get());
+ assertEquals("123", target.get(key, String.class)); // unchanged
+ }
+
@Test
public void evictNonTransactional() {
Cache target = new ConcurrentMapCache("testCache");
diff --git a/spring-context/src/main/java/org/springframework/cache/Cache.java b/spring-context/src/main/java/org/springframework/cache/Cache.java
index bfe32443d1c7..61058eace1fc 100644
--- a/spring-context/src/main/java/org/springframework/cache/Cache.java
+++ b/spring-context/src/main/java/org/springframework/cache/Cache.java
@@ -80,6 +80,33 @@ public interface Cache {
*/
void put(Object key, Object value);
+ /**
+ * Atomically associate the specified value with the specified key in this cache if
+ * it is not set already.
+ * <p>This is equivalent to:
+ * <pre><code>
+ * Object existingValue = cache.get(key);
+ * if (existingValue == null) {
+ * cache.put(key, value);
+ * return null;
+ * } else {
+ * return existingValue;
+ * }
+ * </code></pre>
+ * except that the action is performed atomically. While all known providers are
+ * able to perform the put atomically, the returned value may be retrieved after
+ * the attempt to put (i.e. in a non atomic way). Check the documentation of
+ * the native cache implementation that you are using for more details.
+ * @param key the key with which the specified value is to be associated
+ * @param value the value to be associated with the specified key
+ * @return the value to which this cache maps the specified key (which may
+ * be {@code null} itself), or also {@code null} if the cache did not contain
+ * any mapping for that key prior to this call. Returning {@code null} is
+ * therefore an indicator that the given {@code value} has been associated
+ * with the key
+ */
+ ValueWrapper putIfAbsent(Object key, Object value);
+
/**
* Evict the mapping for this key from this cache if it is present.
* @param key the key whose mapping is to be removed from the cache
diff --git a/spring-context/src/main/java/org/springframework/cache/concurrent/ConcurrentMapCache.java b/spring-context/src/main/java/org/springframework/cache/concurrent/ConcurrentMapCache.java
index 0cf8264dd04b..8601245ea826 100644
--- a/spring-context/src/main/java/org/springframework/cache/concurrent/ConcurrentMapCache.java
+++ b/spring-context/src/main/java/org/springframework/cache/concurrent/ConcurrentMapCache.java
@@ -103,7 +103,7 @@ public final boolean isAllowNullValues() {
@Override
public ValueWrapper get(Object key) {
Object value = this.store.get(key);
- return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
+ return toWrapper(value);
}
@Override
@@ -121,6 +121,12 @@ public void put(Object key, Object value) {
this.store.put(key, toStoreValue(value));
}
+ @Override
+ public ValueWrapper putIfAbsent(Object key, Object value) {
+ Object existing = this.store.putIfAbsent(key, value);
+ return toWrapper(existing);
+ }
+
@Override
public void evict(Object key) {
this.store.remove(key);
@@ -158,6 +164,9 @@ protected Object toStoreValue(Object userValue) {
return userValue;
}
+ private ValueWrapper toWrapper(Object value) {
+ return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
+ }
@SuppressWarnings("serial")
private static class NullHolder implements Serializable {
diff --git a/spring-context/src/main/java/org/springframework/cache/support/NoOpCacheManager.java b/spring-context/src/main/java/org/springframework/cache/support/NoOpCacheManager.java
index c76c79731d16..0b486804a695 100644
--- a/spring-context/src/main/java/org/springframework/cache/support/NoOpCacheManager.java
+++ b/spring-context/src/main/java/org/springframework/cache/support/NoOpCacheManager.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.
@@ -34,6 +34,7 @@
* <p>Will simply accept any items into the cache not actually storing them.
*
* @author Costin Leau
+ * @author Stephane Nicoll
* @since 3.1
* @see CompositeCacheManager
*/
@@ -111,6 +112,11 @@ public Object getNativeCache() {
@Override
public void put(Object key, Object value) {
}
+
+ @Override
+ public ValueWrapper putIfAbsent(Object key, Object value) {
+ return null;
+ }
}
}
diff --git a/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentCacheTests.java b/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentCacheTests.java
index a80bc9560b9f..cba7db7d517a 100644
--- a/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentCacheTests.java
+++ b/spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentCacheTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2014 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.
@@ -29,6 +29,7 @@
/**
* @author Costin Leau
* @author Juergen Hoeller
+ * @author Stephane Nicoll
*/
public class ConcurrentCacheTests {
@@ -79,6 +80,18 @@ public void testCachePut() throws Exception {
assertNull(cache.get(key, Object.class));
}
+ @Test
+ public void testCachePutIfAbsent() throws Exception {
+ Object key = new Object();
+ Object value = "initialValue";
+
+ assertNull(cache.get(key));
+ assertNull(cache.putIfAbsent(key, value));
+ assertEquals(value, cache.get(key).get());
+ assertEquals("initialValue", cache.putIfAbsent(key, "anotherValue").get());
+ assertEquals(value, cache.get(key).get()); // not changed
+ }
+
@Test
public void testCacheRemove() throws Exception {
Object key = "enescu";
|
0744b7f381289147be4eb9e43a0f03e449c1768c
|
intellij-community
|
fix navbar rebuild on popup invocation--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java
index a660037d7346f..6ba150185b141 100644
--- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java
+++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2011 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.
@@ -436,8 +436,9 @@ void navigateInsideBar(final Object object) {
myContextObject = null;
myUpdateQueue.cancelAllUpdates();
-
- myUpdateQueue.queueModelUpdateForObject(obj);
+ if (myNodePopup != null && myNodePopup.isVisible()) {
+ myUpdateQueue.queueModelUpdateForObject(obj);
+ }
myUpdateQueue.queueRebuildUi();
myUpdateQueue.queueAfterAll(new Runnable() {
|
17fdbe6c71b97305d5c1d8dd78a6c7b249c9e481
|
tomakehurst$wiremock
|
More flexibility with request body matching
|
p
|
https://github.com/wiremock/wiremock
|
diff --git a/docs-v2/_docs/record-playback.md b/docs-v2/_docs/record-playback.md
index 4f701d4f25..42ae79074c 100644
--- a/docs-v2/_docs/record-playback.md
+++ b/docs-v2/_docs/record-playback.md
@@ -191,6 +191,11 @@ POST /__admin/recordings/start
"caseInsensitive" : true
}
},
+ "requestBodyPattern" : {
+ "matcher" : "equalToJson",
+ "ignoreArrayOrder" : false,
+ "ignoreExtraElements" : true
+ },
"extractBodyCriteria" : {
"textSizeThreshold" : "2048",
"binarySizeThreshold" : "10240"
@@ -200,10 +205,6 @@ POST /__admin/recordings/start
"transformers" : [ "modify-response-header" ],
"transformerParameters" : {
"headerValue" : "123"
- },
- "jsonMatchingFlags" : {
- "ignoreArrayOrder" : false,
- "ignoreExtraElements" : true
}
}
```
@@ -245,6 +246,11 @@ POST /__admin/recordings/snapshot
"caseInsensitive" : true
}
},
+ "requestBodyPattern" : {
+ "matcher" : "equalToJson",
+ "ignoreArrayOrder" : false,
+ "ignoreExtraElements" : true
+ },
"extractBodyCriteria" : {
"textSizeThreshold" : "2 kb",
"binarySizeThreshold" : "1 Mb"
@@ -255,10 +261,6 @@ POST /__admin/recordings/snapshot
"transformers" : [ "modify-response-header" ],
"transformerParameters" : {
"headerValue" : "123"
- },
- "jsonMatchingFlags" : {
- "ignoreArrayOrder" : false,
- "ignoreExtraElements" : true
}
}
```
@@ -355,20 +357,26 @@ As with other types of WireMock extension, parameters can be supplied. The exact
```
-### JSON matching flags
+### Request body matching
-When a stub is recorded from a request with a JSON body, its body match operator will be set to `equalToJson` (rather than `equalTo`, the default).
-This operator has two optional parameters, indicating whether array order should be ignored, and whether extra elements should be ignored.
+By default, the body match operator for a recorded stub is based on the `Content-Type` header of the request. For `*/json` MIME types, the operator will be `equalToJson` with both the `ignoreArrayOrder` and `ignoreExtraElements` options set to `true`. For `*/xml` MIME types, it will use `equalToXml`. Otherwise, it will use `equalTo` with the `caseInsensitive` option set to `false`.
+
+ This behavior can be customized via the `requestBodyPattern` parameter, which accepts a `matcher` (either `equalTo`, `equalToJson`, `equalToXml`, or `auto`) and any relevant matcher options (`ignoreArrayOrder`, `ignoreExtraElements`, or `caseInsensitive`). For example, here's how to preserve the default behavior, but set `ignoreArrayOrder` to `false` when `equalToJson` is used:
```json
-"jsonMatchingFlags" : {
- "ignoreArrayOrder" : false,
- "ignoreExtraElements" : true
+"requestBodyPattern" : {
+ "matcher": "auto",
+ "ignoreArrayOrder" : false
}
```
-If not specified, both of these will default to `false`.
-
+If you want to always match request bodies with `equalTo` case-insensitively, regardless of the MIME type, use:
+```json
+"requestBodyPattern" : {
+ "matcher": "equalTo",
+ "caseInsenstivie" : true
+ }
+```
> **note**
>
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java
index dc834bac28..655f96cf6e 100644
--- a/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java
@@ -34,6 +34,8 @@ public class RecordSpec {
private final ProxiedServeEventFilters filters;
// Headers from the request to include in the stub mapping, if they match the corresponding matcher
private final Map<String, CaptureHeadersSpec> captureHeaders;
+ // Factory for the StringValuePattern that will be used to match request bodies
+ private final RequestBodyPatternFactory requestBodyPatternFactory;
// Criteria for extracting body from responses
private final ResponseDefinitionBodyMatcher extractBodyCriteria;
// How to format StubMappings in the response body
@@ -46,30 +48,29 @@ public class RecordSpec {
private final List<String> transformers;
// Parameters for stub mapping transformers
private final Parameters transformerParameters;
- private final JsonMatchingFlags jsonMatchingFlags;
@JsonCreator
public RecordSpec(
@JsonProperty("targetBaseUrl") String targetBaseUrl,
@JsonProperty("filters") ProxiedServeEventFilters filters,
@JsonProperty("captureHeaders") Map<String, CaptureHeadersSpec> captureHeaders,
+ @JsonProperty("requestBodyPattern") RequestBodyPatternFactory requestBodyPatternFactory,
@JsonProperty("extractBodyCriteria") ResponseDefinitionBodyMatcher extractBodyCriteria,
@JsonProperty("outputFormat") SnapshotOutputFormatter outputFormat,
@JsonProperty("persist") Boolean persist,
@JsonProperty("repeatsAsScenarios") Boolean repeatsAsScenarios,
@JsonProperty("transformers") List<String> transformers,
- @JsonProperty("transformerParameters") Parameters transformerParameters,
- @JsonProperty("jsonMatchingFlags") JsonMatchingFlags jsonMatchingFlags) {
+ @JsonProperty("transformerParameters") Parameters transformerParameters) {
this.targetBaseUrl = targetBaseUrl;
this.filters = filters == null ? new ProxiedServeEventFilters() : filters;
this.captureHeaders = captureHeaders;
+ this.requestBodyPatternFactory = requestBodyPatternFactory == null ? RequestBodyAutomaticPatternFactory.DEFAULTS : requestBodyPatternFactory;
this.extractBodyCriteria = extractBodyCriteria;
this.outputFormat = outputFormat == null ? SnapshotOutputFormatter.FULL : outputFormat;
this.persist = persist == null ? true : persist;
this.repeatsAsScenarios = repeatsAsScenarios;
this.transformers = transformers;
this.transformerParameters = transformerParameters;
- this.jsonMatchingFlags = jsonMatchingFlags;
}
private RecordSpec() {
@@ -79,7 +80,7 @@ private RecordSpec() {
public static final RecordSpec DEFAULTS = new RecordSpec();
public static RecordSpec forBaseUrl(String targetBaseUrl) {
- return new RecordSpec(targetBaseUrl, null, null, null, null, null, true, null, null, null);
+ return new RecordSpec(targetBaseUrl, null, null, null, null, null, null, true, null, null);
}
public String getTargetBaseUrl() {
@@ -110,7 +111,5 @@ public Boolean getRepeatsAsScenarios() {
public ResponseDefinitionBodyMatcher getExtractBodyCriteria() { return extractBodyCriteria; }
- public JsonMatchingFlags getJsonMatchingFlags() {
- return jsonMatchingFlags;
- }
+ public RequestBodyPatternFactory getRequestBodyPatternFactory() { return requestBodyPatternFactory; }
}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java
index 4fea93623a..862056c43f 100644
--- a/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java
@@ -16,8 +16,7 @@
package com.github.tomakehurst.wiremock.recording;
import com.github.tomakehurst.wiremock.extension.Parameters;
-import com.github.tomakehurst.wiremock.matching.RequestPattern;
-import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
+import com.github.tomakehurst.wiremock.matching.*;
import java.util.List;
import java.util.Map;
@@ -32,13 +31,13 @@ public class RecordSpecBuilder {
private RequestPatternBuilder filterRequestPatternBuilder;
private List<UUID> filterIds;
private Map<String, CaptureHeadersSpec> headers = newLinkedHashMap();
+ private RequestBodyPatternFactory requestBodyPatternFactory;
private long maxTextBodySize = ResponseDefinitionBodyMatcher.DEFAULT_MAX_TEXT_SIZE;
private long maxBinaryBodySize = ResponseDefinitionBodyMatcher.DEFAULT_MAX_BINARY_SIZE;
private boolean persistentStubs = true;
private boolean repeatsAsScenarios = true;
private List<String> transformerNames;
private Parameters transformerParameters;
- private JsonMatchingFlags jsonMatchingFlags;
public RecordSpecBuilder forTarget(String targetBaseUrl) {
this.targetBaseUrl = targetBaseUrl;
@@ -98,6 +97,26 @@ public RecordSpecBuilder captureHeader(String key, Boolean caseInsensitive) {
return this;
}
+ public RecordSpecBuilder requestBodyAutoPattern(boolean ignoreArrayOrder, boolean ignoreExtraElements, boolean caseInsensitive) {
+ this.requestBodyPatternFactory = new RequestBodyAutomaticPatternFactory(ignoreArrayOrder, ignoreExtraElements, caseInsensitive);
+ return this;
+ }
+
+ public RecordSpecBuilder requestBodyEqualToJsonPattern(boolean ignoreArrayOrder, boolean ignoreExtraElements) {
+ this.requestBodyPatternFactory = new RequestBodyEqualToJsonPatternFactory(ignoreArrayOrder, ignoreExtraElements);
+ return this;
+ }
+
+ public RecordSpecBuilder requestBodyEqualToXmlPattern() {
+ this.requestBodyPatternFactory = new RequestBodyEqualToXmlPatternFactory();
+ return this;
+ }
+
+ public RecordSpecBuilder requestBodyEqualToPattern(boolean caseInsensitive) {
+ this.requestBodyPatternFactory = new RequestBodyEqualToPatternFactory(caseInsensitive);
+ return this;
+ }
+
public RecordSpec build() {
RequestPattern filterRequestPattern = filterRequestPatternBuilder != null ?
filterRequestPatternBuilder.build() :
@@ -112,17 +131,12 @@ public RecordSpec build() {
targetBaseUrl,
filters,
headers.isEmpty() ? null : headers,
+ requestBodyPatternFactory,
responseDefinitionBodyMatcher,
SnapshotOutputFormatter.FULL,
persistentStubs,
repeatsAsScenarios,
transformerNames,
- transformerParameters,
- jsonMatchingFlags);
- }
-
- public RecordSpecBuilder jsonBodyMatchFlags(boolean ignoreArrayOrder, boolean ignoreExtraElements) {
- this.jsonMatchingFlags = new JsonMatchingFlags(ignoreArrayOrder, ignoreExtraElements);
- return this;
+ transformerParameters);
}
}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/Recorder.java b/src/main/java/com/github/tomakehurst/wiremock/recording/Recorder.java
index a80b967ced..9bbe627f16 100644
--- a/src/main/java/com/github/tomakehurst/wiremock/recording/Recorder.java
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/Recorder.java
@@ -106,7 +106,7 @@ public SnapshotRecordResult takeSnapshot(List<ServeEvent> serveEvents, RecordSpe
final List<StubMapping> stubMappings = serveEventsToStubMappings(
Lists.reverse(serveEvents),
recordSpec.getFilters(),
- new SnapshotStubMappingGenerator(recordSpec.getCaptureHeaders(), recordSpec.getJsonMatchingFlags()),
+ new SnapshotStubMappingGenerator(recordSpec.getCaptureHeaders(), recordSpec.getRequestBodyPatternFactory()),
getStubMappingPostProcessor(admin.getOptions(), recordSpec)
);
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactory.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactory.java
new file mode 100644
index 0000000000..f0f3c3bc50
--- /dev/null
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactory.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2011 Thomas Akehurst
+ *
+ * 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.github.tomakehurst.wiremock.recording;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.github.tomakehurst.wiremock.http.ContentTypeHeader;
+import com.github.tomakehurst.wiremock.http.Request;
+import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern;
+import com.github.tomakehurst.wiremock.matching.EqualToPattern;
+import com.github.tomakehurst.wiremock.matching.EqualToXmlPattern;
+import com.github.tomakehurst.wiremock.matching.StringValuePattern;
+
+public class RequestBodyAutomaticPatternFactory implements RequestBodyPatternFactory {
+
+ private final Boolean caseInsensitive;
+ private final Boolean ignoreArrayOrder;
+ private final Boolean ignoreExtraElements;
+
+ @JsonCreator
+ public RequestBodyAutomaticPatternFactory(
+ @JsonProperty("ignoreArrayOrder") Boolean ignoreArrayOrder,
+ @JsonProperty("ignoreExtraElements") Boolean ignoreExtraElements,
+ @JsonProperty("caseInsensitive") Boolean caseInsensitive) {
+ this.ignoreArrayOrder = ignoreArrayOrder == null ? true : ignoreArrayOrder;
+ this.ignoreExtraElements = ignoreExtraElements == null ? true : ignoreExtraElements;
+ this.caseInsensitive = caseInsensitive == null ? false : caseInsensitive;
+ }
+
+ private RequestBodyAutomaticPatternFactory() {
+ this(null, null, null);
+ }
+
+ public static final RequestBodyAutomaticPatternFactory DEFAULTS = new RequestBodyAutomaticPatternFactory();
+
+ public Boolean isIgnoreArrayOrder() {
+ return ignoreArrayOrder;
+ }
+
+ public Boolean isIgnoreExtraElements() {
+ return ignoreExtraElements;
+ }
+
+ public Boolean isCaseInsensitive() {
+ return caseInsensitive;
+ }
+
+ /**
+ * If request body was JSON or XML, use "equalToJson" or "equalToXml" (respectively) in the RequestPattern so it's
+ * easier to read. Otherwise, just use "equalTo"
+ */
+ @Override
+ public StringValuePattern forRequest(Request request) {
+ final ContentTypeHeader contentType = request.getHeaders().getContentTypeHeader();
+ if (contentType.mimeTypePart() != null) {
+ if (contentType.mimeTypePart().contains("json")) {
+ return new EqualToJsonPattern(request.getBodyAsString(), ignoreArrayOrder, ignoreExtraElements);
+ } else if (contentType.mimeTypePart().contains("xml")) {
+ return new EqualToXmlPattern(request.getBodyAsString());
+ }
+ }
+
+ return new EqualToPattern(request.getBodyAsString(), caseInsensitive);
+ }
+}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/JsonMatchingFlags.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactory.java
similarity index 62%
rename from src/main/java/com/github/tomakehurst/wiremock/recording/JsonMatchingFlags.java
rename to src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactory.java
index 2a7f3c69fe..87b54fc90c 100644
--- a/src/main/java/com/github/tomakehurst/wiremock/recording/JsonMatchingFlags.java
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactory.java
@@ -15,15 +15,20 @@
*/
package com.github.tomakehurst.wiremock.recording;
+import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
+import com.github.tomakehurst.wiremock.http.Request;
+import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern;
-public class JsonMatchingFlags {
+public class RequestBodyEqualToJsonPatternFactory implements RequestBodyPatternFactory {
private final Boolean ignoreArrayOrder;
private final Boolean ignoreExtraElements;
- public JsonMatchingFlags(@JsonProperty("ignoreArrayOrder") Boolean ignoreArrayOrder,
- @JsonProperty("ignoreExtraElements") Boolean ignoreExtraElements) {
+ @JsonCreator
+ public RequestBodyEqualToJsonPatternFactory(
+ @JsonProperty("ignoreArrayOrder") Boolean ignoreArrayOrder,
+ @JsonProperty("ignoreExtraElements") Boolean ignoreExtraElements) {
this.ignoreArrayOrder = ignoreArrayOrder;
this.ignoreExtraElements = ignoreExtraElements;
}
@@ -35,4 +40,9 @@ public Boolean isIgnoreArrayOrder() {
public Boolean isIgnoreExtraElements() {
return ignoreExtraElements;
}
+
+ @Override
+ public EqualToJsonPattern forRequest(Request request) {
+ return new EqualToJsonPattern(request.getBodyAsString(), ignoreArrayOrder, ignoreExtraElements);
+ }
}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToPatternFactory.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToPatternFactory.java
new file mode 100644
index 0000000000..f6c7b9dad0
--- /dev/null
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToPatternFactory.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2011 Thomas Akehurst
+ *
+ * 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.github.tomakehurst.wiremock.recording;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.github.tomakehurst.wiremock.http.Request;
+import com.github.tomakehurst.wiremock.matching.EqualToPattern;
+
+public class RequestBodyEqualToPatternFactory implements RequestBodyPatternFactory {
+
+ private final Boolean caseInsensitive;
+
+ @JsonCreator
+ public RequestBodyEqualToPatternFactory(@JsonProperty("caseInsensitive") Boolean caseInsensitive) {
+ this.caseInsensitive = caseInsensitive;
+ }
+
+ public Boolean isCaseInsensitive() {
+ return caseInsensitive;
+ }
+
+ @Override
+ public EqualToPattern forRequest(Request request) {
+ return new EqualToPattern(request.getBodyAsString(), caseInsensitive);
+ }
+}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToXmlPatternFactory.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToXmlPatternFactory.java
new file mode 100644
index 0000000000..0c31cc75c7
--- /dev/null
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToXmlPatternFactory.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2011 Thomas Akehurst
+ *
+ * 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.github.tomakehurst.wiremock.recording;
+
+import com.github.tomakehurst.wiremock.http.Request;
+import com.github.tomakehurst.wiremock.matching.EqualToXmlPattern;
+
+public class RequestBodyEqualToXmlPatternFactory implements RequestBodyPatternFactory {
+
+ @Override
+ public EqualToXmlPattern forRequest(Request request) {
+ return new EqualToXmlPattern(request.getBodyAsString());
+ }
+}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactory.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactory.java
new file mode 100644
index 0000000000..c2f350d292
--- /dev/null
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactory.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2011 Thomas Akehurst
+ *
+ * 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.github.tomakehurst.wiremock.recording;
+
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.github.tomakehurst.wiremock.http.Request;
+import com.github.tomakehurst.wiremock.matching.StringValuePattern;
+
+/**
+ * Factory for the StringValuePattern to use in a recorded stub mapping to match request bodies
+ */
+@JsonTypeInfo(
+ use = JsonTypeInfo.Id.NAME,
+ include = JsonTypeInfo.As.PROPERTY,
+ property = "matcher",
+ defaultImpl = RequestBodyAutomaticPatternFactory.class
+)
+@JsonSubTypes({
+ @JsonSubTypes.Type(value = RequestBodyAutomaticPatternFactory.class, name = "auto"),
+ @JsonSubTypes.Type(value = RequestBodyEqualToPatternFactory.class, name = "equalTo"),
+ @JsonSubTypes.Type(value = RequestBodyEqualToJsonPatternFactory.class, name = "equalToJson"),
+ @JsonSubTypes.Type(value = RequestBodyEqualToXmlPatternFactory.class, name = "equalToXml")
+})
+public interface RequestBodyPatternFactory {
+ StringValuePattern forRequest(Request request);
+}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformer.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformer.java
index 65c7c36afd..dd194e99b7 100644
--- a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformer.java
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformer.java
@@ -15,9 +15,6 @@
*/
package com.github.tomakehurst.wiremock.recording;
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.github.tomakehurst.wiremock.http.ContentTypeHeader;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.matching.*;
import com.google.common.base.Function;
@@ -33,13 +30,13 @@
*/
public class RequestPatternTransformer implements Function<Request, RequestPatternBuilder> {
private final Map<String, CaptureHeadersSpec> headers;
- private final JsonMatchingFlags jsonMatchingFlags;
+ private final RequestBodyPatternFactory bodyPatternFactory;
- @JsonCreator
- public RequestPatternTransformer(@JsonProperty("headers") Map<String, CaptureHeadersSpec> headers,
- @JsonProperty("jsonMatchingFlags") JsonMatchingFlags jsonMatchingFlags) {
+ public RequestPatternTransformer(
+ Map<String, CaptureHeadersSpec> headers,
+ RequestBodyPatternFactory bodyPatternFactory) {
this.headers = headers;
- this.jsonMatchingFlags = jsonMatchingFlags;
+ this.bodyPatternFactory = bodyPatternFactory;
}
/**
@@ -62,29 +59,10 @@ public RequestPatternBuilder apply(Request request) {
}
String body = request.getBodyAsString();
- if (body != null && !body.isEmpty()) {
- builder.withRequestBody(valuePatternForContentType(request));
+ if (bodyPatternFactory != null && body != null && !body.isEmpty()) {
+ builder.withRequestBody(bodyPatternFactory.forRequest(request));
}
return builder;
}
-
- /**
- * If request body was JSON or XML, use "equalToJson" or "equalToXml" (respectively) in the RequestPattern so it's
- * easier to read. Otherwise, just use "equalTo"
- */
- private StringValuePattern valuePatternForContentType(Request request) {
- final ContentTypeHeader contentType = request.getHeaders().getContentTypeHeader();
- if (contentType.mimeTypePart() != null) {
- if (contentType.mimeTypePart().contains("json")) {
- return jsonMatchingFlags == null ?
- equalToJson(request.getBodyAsString()) :
- equalToJson(request.getBodyAsString(), jsonMatchingFlags.isIgnoreArrayOrder(), jsonMatchingFlags.isIgnoreExtraElements());
- } else if (contentType.mimeTypePart().contains("xml")) {
- return equalToXml(request.getBodyAsString());
- }
- }
-
- return equalTo(request.getBodyAsString());
- }
}
diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGenerator.java b/src/main/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGenerator.java
index 32e9ecebad..5fb93f6715 100644
--- a/src/main/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGenerator.java
+++ b/src/main/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGenerator.java
@@ -40,9 +40,9 @@ public SnapshotStubMappingGenerator(
this.responseTransformer = responseTransformer;
}
- public SnapshotStubMappingGenerator(Map<String, CaptureHeadersSpec> captureHeaders, JsonMatchingFlags jsonMatchingFlags) {
+ public SnapshotStubMappingGenerator(Map<String, CaptureHeadersSpec> captureHeaders, RequestBodyPatternFactory requestBodyPatternFactory) {
this(
- new RequestPatternTransformer(captureHeaders, jsonMatchingFlags),
+ new RequestPatternTransformer(captureHeaders, requestBodyPatternFactory),
new LoggedResponseDefinitionTransformer()
);
}
diff --git a/src/main/resources/raml/examples/record-spec.example.json b/src/main/resources/raml/examples/record-spec.example.json
index 8fff7ed1bc..fef1992388 100644
--- a/src/main/resources/raml/examples/record-spec.example.json
+++ b/src/main/resources/raml/examples/record-spec.example.json
@@ -10,6 +10,11 @@
"caseInsensitive" : true
}
},
+ "requestBodyPattern" : {
+ "matcher" : "equalToJson",
+ "ignoreArrayOrder" : false,
+ "ignoreExtraElements" : true
+ },
"extractBodyCriteria" : {
"textSizeThreshold" : "2048",
"binarySizeThreshold" : "10240"
@@ -19,9 +24,5 @@
"transformers" : [ "modify-response-header" ],
"transformerParameters" : {
"headerValue" : "123"
- },
- "jsonMatchingFlags" : {
- "ignoreArrayOrder" : false,
- "ignoreExtraElements" : true
}
}
\ No newline at end of file
diff --git a/src/main/resources/raml/examples/snapshot-spec.example.json b/src/main/resources/raml/examples/snapshot-spec.example.json
index 45317b706f..b9a3e18fba 100644
--- a/src/main/resources/raml/examples/snapshot-spec.example.json
+++ b/src/main/resources/raml/examples/snapshot-spec.example.json
@@ -10,6 +10,11 @@
"caseInsensitive" : true
}
},
+ "requestBodyPattern" : {
+ "matcher" : "equalToJson",
+ "ignoreArrayOrder" : false,
+ "ignoreExtraElements" : true
+ },
"extractBodyCriteria" : {
"textSizeThreshold" : "2 kb",
"binarySizeThreshold" : "1 Mb"
@@ -20,9 +25,5 @@
"transformers" : [ "modify-response-header" ],
"transformerParameters" : {
"headerValue" : "123"
- },
- "jsonMatchingFlags" : {
- "ignoreArrayOrder" : false,
- "ignoreExtraElements" : true
}
}
\ No newline at end of file
diff --git a/src/main/resources/raml/schemas/record-spec.schema.json b/src/main/resources/raml/schemas/record-spec.schema.json
index 4c49d63585..e3db883663 100644
--- a/src/main/resources/raml/schemas/record-spec.schema.json
+++ b/src/main/resources/raml/schemas/record-spec.schema.json
@@ -18,6 +18,29 @@
}
}
},
+ "requestBodyPattern": {
+ "type": "object",
+ "properties": {
+ "matcher": {
+ "type": "string",
+ "enum": [
+ "equalTo",
+ "equalToJson",
+ "equalToXml",
+ "auto"
+ ]
+ },
+ "ignoreArrayOrder": {
+ "type": "boolean"
+ },
+ "ignoreExtraElements": {
+ "type": "boolean"
+ },
+ "caseInsensitive": {
+ "type": "boolean"
+ }
+ }
+ },
"filters": {
"type": "object",
"properties": {
@@ -35,17 +58,6 @@
}
}
},
- "jsonMatchingFlags": {
- "type": "object",
- "properties": {
- "ignoreArrayOrder": {
- "type": "boolean"
- },
- "ignoreExtraElements": {
- "type": "boolean"
- }
- }
- },
"persist": {
"type": "boolean"
},
diff --git a/src/test/java/com/github/tomakehurst/wiremock/RecordingDslAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/RecordingDslAcceptanceTest.java
index dc3233ed89..e7c592e9c0 100644
--- a/src/test/java/com/github/tomakehurst/wiremock/RecordingDslAcceptanceTest.java
+++ b/src/test/java/com/github/tomakehurst/wiremock/RecordingDslAcceptanceTest.java
@@ -199,7 +199,7 @@ public void supportsInstanceClientWithSpec() {
adminClient.startStubRecording(
recordSpec()
.forTarget(targetBaseUrl)
- .jsonBodyMatchFlags(true, true)
+ .requestBodyEqualToJsonPattern(true, true)
);
client.postJson("/record-this-with-body", "{}");
@@ -218,7 +218,7 @@ public void supportsDirectDslCallsWithSpec() {
proxyingService.startRecording(
recordSpec()
.forTarget(targetBaseUrl)
- .jsonBodyMatchFlags(true, true)
+ .requestBodyEqualToJsonPattern(true, true)
);
client.postJson("/record-this-with-body", "{}");
diff --git a/src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java
index 89129b6cfb..35a96d31bd 100644
--- a/src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java
+++ b/src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java
@@ -22,9 +22,7 @@
import com.github.tomakehurst.wiremock.extension.StubMappingTransformer;
import com.github.tomakehurst.wiremock.http.RequestMethod;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
-import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern;
-import com.github.tomakehurst.wiremock.matching.EqualToPattern;
-import com.github.tomakehurst.wiremock.matching.StringValuePattern;
+import com.github.tomakehurst.wiremock.matching.*;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import com.github.tomakehurst.wiremock.testsupport.WireMatchers;
@@ -106,8 +104,8 @@ public void snapshotRecordsAllLoggedRequestsWhenNoParametersPassed() throws Exce
JSONAssert.assertEquals("{ \"counter\": 55 }", bodyPattern.getExpected(), true);
EqualToJsonPattern equalToJsonPattern = (EqualToJsonPattern) bodyPattern;
- assertThat(equalToJsonPattern.isIgnoreArrayOrder(), nullValue());
- assertThat(equalToJsonPattern.isIgnoreExtraElements(), nullValue());
+ assertThat(equalToJsonPattern.isIgnoreArrayOrder(), is(true));
+ assertThat(equalToJsonPattern.isIgnoreExtraElements(), is(true));
}
@Test
@@ -253,27 +251,64 @@ public void appliesTransformerWithParameters() {
}
@Test
- public void supportsConfigurationOfJsonBodyMatching() {
+ public void supportsConfigurationOfAutoRequestBodyPatternFactory() {
client.postJson("/some-json", "{}");
+ client.postWithBody("/some-json", "<foo/>", "application/xml", "utf-8");
+ client.postWithBody("/some-json", "foo", "application/text", "utf-8");
- List<StubMapping> mappings = snapshotRecord(
- recordSpec().jsonBodyMatchFlags(true, true)
- );
+ List<StubMapping> mappings = snapshotRecord(recordSpec().requestBodyAutoPattern(false, false, true));
+
+ EqualToJsonPattern jsonBodyPattern = (EqualToJsonPattern) mappings.get(0).getRequest().getBodyPatterns().get(0);
+ assertThat(jsonBodyPattern.getEqualToJson(), is("{}"));
+ assertThat(jsonBodyPattern.isIgnoreArrayOrder(), is(false));
+ assertThat(jsonBodyPattern.isIgnoreExtraElements(), is(false));
+
+ EqualToXmlPattern xmlBodyPattern = (EqualToXmlPattern) mappings.get(1).getRequest().getBodyPatterns().get(0);
+ assertThat(xmlBodyPattern.getEqualToXml(), is("<foo/>"));
+
+ EqualToPattern textBodyPattern = (EqualToPattern) mappings.get(2).getRequest().getBodyPatterns().get(0);
+ assertThat(textBodyPattern.getEqualTo(), is("foo"));
+ assertThat(textBodyPattern.getCaseInsensitive(), is(true));
+ }
+
+ @Test
+ public void supportsConfigurationOfRequestBodyPatternFactoryWithEqualToJsonPattern() {
+ client.postJson("/some-json", "{}");
+
+ List<StubMapping> mappings = snapshotRecord(recordSpec().requestBodyEqualToJsonPattern(false, true));
EqualToJsonPattern bodyPattern = (EqualToJsonPattern) mappings.get(0).getRequest().getBodyPatterns().get(0);
- assertThat(bodyPattern.isIgnoreArrayOrder(), is(true));
+ assertThat(bodyPattern.isIgnoreArrayOrder(), is(false));
assertThat(bodyPattern.isIgnoreExtraElements(), is(true));
}
@Test
- public void defaultsToNoJsonBodyMatchingFlags() {
+ public void supportsConfigurationOfRequestBodyPatternFactoryWithEqualToXmlPattern() {
+ client.postWithBody("/some-json", "<foo/>", "application/xml", "utf-8");
+
+ List<StubMapping> mappings = snapshotRecord(recordSpec().requestBodyEqualToXmlPattern());
+
+ assertThat(mappings.get(0).getRequest().getBodyPatterns().get(0), instanceOf(EqualToXmlPattern.class));
+ }
+
+ @Test
+ public void supportsConfigurationOfRequestBodyPatternFactoryWithEqualToPattern() {
+ client.postWithBody("/some-json", "foo", "application/text", "utf-8");
+
+ List<StubMapping> mappings = snapshotRecord(recordSpec().requestBodyEqualToPattern(true));
+
+ EqualToPattern bodyPattern = (EqualToPattern) mappings.get(0).getRequest().getBodyPatterns().get(0);
+ assertThat(bodyPattern.getCaseInsensitive(), is(true));
+ }
+
+ @Test
+ public void defaultsToAutomaticRequestBodyPattern() {
client.postJson("/some-json", "{}");
List<StubMapping> mappings = snapshotRecord(recordSpec());
EqualToJsonPattern bodyPattern = (EqualToJsonPattern) mappings.get(0).getRequest().getBodyPatterns().get(0);
- assertThat(bodyPattern.isIgnoreArrayOrder(), nullValue());
- assertThat(bodyPattern.isIgnoreExtraElements(), nullValue());
+ assertThat(bodyPattern, is(new EqualToJsonPattern("{}", true, true)));
}
@Test
diff --git a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactoryTest.java b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactoryTest.java
new file mode 100644
index 0000000000..a64088f4c6
--- /dev/null
+++ b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactoryTest.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2011 Thomas Akehurst
+ *
+ * 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.github.tomakehurst.wiremock.recording;
+
+import com.github.tomakehurst.wiremock.http.Request;
+import com.github.tomakehurst.wiremock.matching.*;
+import org.junit.Test;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;
+
+public class RequestBodyAutomaticPatternFactoryTest {
+ private final static String JSON_TEST_STRING = "{ \"foo\": 1 }";
+ private final static String XML_TEST_STRING = "<foo/>";
+
+ @Test
+ public void forRequestWithTextBodyIsCaseSensitiveByDefault() {
+ Request request = mockRequest().body(JSON_TEST_STRING);
+ EqualToPattern pattern = (EqualToPattern) patternForRequest(request);
+
+ assertThat(pattern.getEqualTo(), is(JSON_TEST_STRING));
+ assertThat(pattern.getCaseInsensitive(), is(false));
+ }
+
+ @Test
+ public void forRequestWithTextBodyRespectsCaseInsensitiveOption() {
+ Request request = mockRequest().body(JSON_TEST_STRING);
+ RequestBodyAutomaticPatternFactory patternFactory = new RequestBodyAutomaticPatternFactory(false, false, true);
+ EqualToPattern pattern = (EqualToPattern) patternFactory.forRequest(request);
+
+ assertThat(pattern.getEqualTo(), is(JSON_TEST_STRING));
+ assertThat(pattern.getCaseInsensitive(), is(true));
+ }
+
+ @Test
+ public void forRequestWithJsonBodyIgnoresExtraElementsAndArrayOrderByDefault() {
+ Request request = mockRequest()
+ .header("Content-Type", "application/json")
+ .body(JSON_TEST_STRING);
+ EqualToJsonPattern pattern = (EqualToJsonPattern) patternForRequest(request);
+
+ assertThat(pattern.getEqualToJson(), is(JSON_TEST_STRING));
+ assertThat(pattern.isIgnoreExtraElements(), is(true));
+ assertThat(pattern.isIgnoreArrayOrder(), is(true));
+ }
+
+ @Test
+ public void forRequestWithJsonBodyRespectsOptions() {
+ RequestBodyAutomaticPatternFactory patternFactory = new RequestBodyAutomaticPatternFactory(false, false, false);
+ Request request = mockRequest()
+ .header("Content-Type", "application/json")
+ .body(JSON_TEST_STRING);
+ EqualToJsonPattern pattern = (EqualToJsonPattern) patternFactory.forRequest(request);
+
+ assertThat(pattern.getEqualToJson(), is(JSON_TEST_STRING));
+ assertThat(pattern.isIgnoreExtraElements(), is(false));
+ assertThat(pattern.isIgnoreArrayOrder(), is(false));
+ }
+
+ @Test
+ public void forRequestWithXmlBody() {
+ Request request = mockRequest()
+ .header("Content-Type", "application/xml")
+ .body(XML_TEST_STRING);
+ EqualToXmlPattern pattern = (EqualToXmlPattern) patternForRequest(request);
+
+ assertThat(pattern.getEqualToXml(), is(XML_TEST_STRING));
+ }
+
+ private static StringValuePattern patternForRequest(Request request) {
+ return RequestBodyAutomaticPatternFactory.DEFAULTS.forRequest(request);
+ }
+}
diff --git a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactoryTest.java b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactoryTest.java
new file mode 100644
index 0000000000..4b30beebef
--- /dev/null
+++ b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactoryTest.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2011 Thomas Akehurst
+ *
+ * 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.github.tomakehurst.wiremock.recording;
+
+import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern;
+import org.junit.Test;
+
+import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+public class RequestBodyEqualToJsonPatternFactoryTest {
+
+ @Test
+ public void withIgnoreArrayOrder() {
+ RequestBodyEqualToJsonPatternFactory patternFactory = new RequestBodyEqualToJsonPatternFactory(true, false);
+ EqualToJsonPattern pattern = (EqualToJsonPattern) patternFactory.forRequest(mockRequest().body("{}"));
+
+ assertThat(pattern.getEqualToJson(), is("{}"));
+ assertThat(pattern.isIgnoreExtraElements(), is(false));
+ assertThat(pattern.isIgnoreArrayOrder(), is(true));
+ }
+
+ @Test
+ public void withIgnoreExtraElements() {
+ RequestBodyEqualToJsonPatternFactory patternFactory = new RequestBodyEqualToJsonPatternFactory(false, true);
+ EqualToJsonPattern pattern = (EqualToJsonPattern) patternFactory.forRequest(mockRequest().body("{}"));
+
+ assertThat(pattern.getEqualToJson(), is("{}"));
+ assertThat(pattern.isIgnoreExtraElements(), is(true));
+ assertThat(pattern.isIgnoreArrayOrder(), is(false));
+ }
+}
diff --git a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactoryJsonDeserializerTest.java b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactoryJsonDeserializerTest.java
new file mode 100644
index 0000000000..ee2b6c3021
--- /dev/null
+++ b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactoryJsonDeserializerTest.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2011 Thomas Akehurst
+ *
+ * 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.github.tomakehurst.wiremock.recording;
+
+import com.github.tomakehurst.wiremock.common.Json;
+import com.github.tomakehurst.wiremock.matching.*;
+import org.junit.Test;
+
+import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+public class RequestBodyPatternFactoryJsonDeserializerTest {
+ @Test
+ public void correctlyDeserializesWithEmptyObject() {
+ RequestBodyPatternFactory bodyPatternFactory = deserializeJson("{}");
+ assertThat(bodyPatternFactory, instanceOf(RequestBodyAutomaticPatternFactory.class));
+ }
+
+ @Test
+ public void correctlyDeserializesWithAutoMatcher() {
+ RequestBodyPatternFactory bodyPatternFactory = deserializeJson("{ \"matcher\": \"auto\" }");
+ assertThat(bodyPatternFactory, instanceOf(RequestBodyAutomaticPatternFactory.class));
+ }
+
+ @Test
+ public void correctlyDeserializesWithEqualToMatcher() {
+ RequestBodyPatternFactory bodyPatternFactory = deserializeJson(
+ "{ \n" +
+ " \"matcher\": \"equalTo\", \n" +
+ " \"caseInsensitive\": true \n" +
+ "} "
+ );
+ EqualToPattern bodyPattern = (EqualToPattern) bodyPatternFactory.forRequest(mockRequest());
+ assertThat(bodyPattern.getCaseInsensitive(), is(true));
+ }
+
+ @Test
+ public void correctlyDeserializesWithEqualToJsonMatcher() {
+ RequestBodyPatternFactory bodyPatternFactory = deserializeJson(
+ "{ \n" +
+ " \"matcher\": \"equalToJson\", \n" +
+ " \"ignoreArrayOrder\": false, \n" +
+ " \"ignoreExtraElements\": true \n" +
+ "} "
+ );
+ EqualToJsonPattern bodyPattern = (EqualToJsonPattern) bodyPatternFactory.forRequest(mockRequest().body("1"));
+ assertThat(bodyPattern.isIgnoreArrayOrder(), is(false));
+ assertThat(bodyPattern.isIgnoreExtraElements(), is(true));
+
+ }
+
+ @Test
+ public void correctlyDeserializesWithEqualToXmlMatcher() {
+ RequestBodyPatternFactory bodyPatternFactory = deserializeJson("{ \"matcher\": \"equalToXml\" }");
+ assertThat(bodyPatternFactory, instanceOf(RequestBodyEqualToXmlPatternFactory.class));
+ }
+
+ private static RequestBodyPatternFactory deserializeJson(String json) {
+ return Json.read(json, RequestBodyPatternFactory.class);
+ }
+}
diff --git a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformerTest.java b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformerTest.java
index 007a2d24c2..3bbe1ac1b8 100644
--- a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformerTest.java
+++ b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformerTest.java
@@ -15,75 +15,50 @@
*/
package com.github.tomakehurst.wiremock.recording;
-import com.github.tomakehurst.wiremock.recording.CaptureHeadersSpec;
-import com.github.tomakehurst.wiremock.recording.RequestPatternTransformer;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.RequestMethod;
-import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
+import com.github.tomakehurst.wiremock.matching.*;
+import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import java.util.Map;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;
-import static com.google.common.collect.Maps.newLinkedHashMap;
import static org.junit.Assert.assertEquals;
public class RequestPatternTransformerTest {
@Test
- public void applyWithDefaultsAndNoBody() {
+ public void applyIncludesMethodAndUrlMatchers() {
Request request = mockRequest()
.url("/foo")
.method(RequestMethod.GET)
.header("User-Agent", "foo")
.header("X-Foo", "bar");
+
RequestPatternBuilder expected = new RequestPatternBuilder(RequestMethod.GET, urlEqualTo("/foo"));
- // Default is to include method and URL exactly
assertEquals(expected.build(), new RequestPatternTransformer(null, null).apply(request).build());
}
@Test
- public void applyWithUrlAndPlainTextBody() {
+ public void applyWithHeaders() {
Request request = mockRequest()
- .url("/foo")
- .method(RequestMethod.GET)
- .body("HELLO")
- .header("Accept", "foo")
- .header("User-Agent", "bar");
+ .url("/")
+ .method(RequestMethod.POST)
+ .header("X-CaseSensitive", "foo")
+ .header("X-Ignored", "ignored")
+ .header("X-CaseInsensitive", "Baz");
- RequestPatternBuilder expected = new RequestPatternBuilder(RequestMethod.GET, urlEqualTo("/foo"))
- .withRequestBody(equalTo("HELLO"));
+ RequestPatternBuilder expected = new RequestPatternBuilder(RequestMethod.POST, urlEqualTo("/"))
+ .withHeader("X-CaseSensitive", equalTo("foo"))
+ .withHeader("X-CaseInsensitive", equalToIgnoreCase("Baz"));
- Map<String, CaptureHeadersSpec> headers = newLinkedHashMap();
+ Map<String, CaptureHeadersSpec> headers = ImmutableMap.of(
+ "X-CaseSensitive", new CaptureHeadersSpec(false),
+ "X-CaseInsensitive", new CaptureHeadersSpec(true)
+ );
assertEquals(expected.build(), new RequestPatternTransformer(headers, null).apply(request).build());
}
-
- @Test
- public void applyWithOnlyJsonBody() {
- Request request = mockRequest()
- .url("/somewhere")
- .header("Content-Type", "application/json")
- .body("['hello']");
- RequestPatternBuilder expected = new RequestPatternBuilder()
- .withUrl("/somewhere")
- .withRequestBody(equalToJson("['hello']"));
-
- assertEquals(expected.build(), new RequestPatternTransformer(null, null).apply(request).build());
- }
-
- @Test
- public void applyWithOnlyXmlBody() {
- Request request = mockRequest()
- .url("/somewhere")
- .header("Content-Type", "application/xml")
- .body("<foo/>");
-
- RequestPatternBuilder expected = new RequestPatternBuilder()
- .withUrl("/somewhere")
- .withRequestBody(equalToXml("<foo/>"));
-
- assertEquals(expected.build(), new RequestPatternTransformer(null, null).apply(request).build());
- }
}
diff --git a/src/test/java/ignored/Examples.java b/src/test/java/ignored/Examples.java
index 4dd2fd738b..fc50a248de 100644
--- a/src/test/java/ignored/Examples.java
+++ b/src/test/java/ignored/Examples.java
@@ -417,7 +417,7 @@ public void recordingDsl() {
.ignoreRepeatRequests()
.transformers("modify-response-header")
.transformerParameters(Parameters.one("headerValue", "123"))
- .jsonBodyMatchFlags(false, true)
+ .requestBodyEqualToJsonPattern(false, true)
);
System.out.println(Json.write(recordSpec()
@@ -431,7 +431,7 @@ public void recordingDsl() {
.ignoreRepeatRequests()
.transformers("modify-response-header")
.transformerParameters(Parameters.one("headerValue", "123"))
- .jsonBodyMatchFlags(false, true)
+ .requestBodyEqualToJsonPattern(false, true)
.build()));
}
@@ -449,7 +449,7 @@ public void snapshotDsl() {
.ignoreRepeatRequests()
.transformers("modify-response-header")
.transformerParameters(Parameters.one("headerValue", "123"))
- .jsonBodyMatchFlags(false, true)
+ .requestBodyEqualToJsonPattern(false, true)
);
System.out.println(Json.write(recordSpec()
@@ -463,7 +463,7 @@ public void snapshotDsl() {
.ignoreRepeatRequests()
.transformers("modify-response-header")
.transformerParameters(Parameters.one("headerValue", "123"))
- .jsonBodyMatchFlags(false, true)
+ .requestBodyEqualToJsonPattern(false, true)
.build()));
}
}
|
96a1477d02e29b3002678f4da9ca55184888a54c
|
hadoop
|
HADOOP-6534. Trim whitespace from directory lists- initializing LocalDirAllocator. Contributed by Todd Lipcon--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@909806 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index d42bd21c00c19..c02fbd20426ec 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -137,6 +137,9 @@ Trunk (unreleased changes)
HADOOP-6552. Puts renewTGT=true and useTicketCache=true for the keytab
kerberos options. (ddas)
+ HADOOP-6534. Trim whitespace from directory lists initializing
+ LocalDirAllocator. (Todd Lipcon via cdouglas)
+
OPTIMIZATIONS
BUG FIXES
diff --git a/src/java/org/apache/hadoop/fs/LocalDirAllocator.java b/src/java/org/apache/hadoop/fs/LocalDirAllocator.java
index 1aa4663b15a25..d04bb56b27e53 100644
--- a/src/java/org/apache/hadoop/fs/LocalDirAllocator.java
+++ b/src/java/org/apache/hadoop/fs/LocalDirAllocator.java
@@ -213,7 +213,7 @@ public AllocatorPerContext(String contextCfgItemName) {
private void confChanged(Configuration conf) throws IOException {
String newLocalDirs = conf.get(contextCfgItemName);
if (!newLocalDirs.equals(savedLocalDirs)) {
- localDirs = conf.getStrings(contextCfgItemName);
+ localDirs = conf.getTrimmedStrings(contextCfgItemName);
localFS = FileSystem.getLocal(conf);
int numDirs = localDirs.length;
ArrayList<String> dirs = new ArrayList<String>(numDirs);
|
7cac25d2c8d7809824d45bdefc1ad95124c21fb6
|
Vala
|
gtk+-2.0: make Gtk.AccelKey a struct
Fixes bug 617963.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gtk+-2.0.vapi b/vapi/gtk+-2.0.vapi
index e37749b909..d189273e19 100644
--- a/vapi/gtk+-2.0.vapi
+++ b/vapi/gtk+-2.0.vapi
@@ -66,7 +66,7 @@ namespace Gtk {
public void connect_by_path (string accel_path, GLib.Closure closure);
public bool disconnect (GLib.Closure closure);
public bool disconnect_key (uint accel_key, Gdk.ModifierType accel_mods);
- public unowned Gtk.AccelKey find (Gtk.AccelGroupFindFunc find_func, void* data);
+ public Gtk.AccelKey find (Gtk.AccelGroupFindFunc find_func, void* data);
public static unowned Gtk.AccelGroup from_accel_closure (GLib.Closure closure);
public bool get_is_locked ();
public Gdk.ModifierType get_modifier_mask ();
@@ -83,14 +83,7 @@ namespace Gtk {
public class AccelGroupEntry {
public GLib.Quark accel_path_quark;
public weak GLib.Closure closure;
- public weak Gtk.AccelKey key;
- }
- [Compact]
- [CCode (cheader_filename = "gtk/gtk.h")]
- public class AccelKey {
- public uint accel_flags;
- public uint accel_key;
- public Gdk.ModifierType accel_mods;
+ public Gtk.AccelKey key;
}
[CCode (cheader_filename = "gtk/gtk.h")]
public class AccelLabel : Gtk.Label, Atk.Implementor, Gtk.Buildable {
@@ -5953,6 +5946,12 @@ namespace Gtk {
[HasEmitter]
public signal void sort_column_changed ();
}
+ [CCode (type_id = "GTK_TYPE_ACCEL_KEY", cheader_filename = "gtk/gtk.h")]
+ public struct AccelKey {
+ public uint accel_key;
+ public Gdk.ModifierType accel_mods;
+ public uint accel_flags;
+ }
[CCode (type_id = "GTK_TYPE_ACTION_ENTRY", cheader_filename = "gtk/gtk.h")]
public struct ActionEntry {
public weak string name;
diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
index ffe1460729..0d175bb5d7 100644
--- a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
+++ b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
@@ -11,6 +11,7 @@ gtk_about_dialog_set_url_hook.data hidden="1"
gtk_about_dialog_set_url_hook.destroy hidden="1"
gtk_about_dialog_set_url_hook type_name="void"
gtk_accel_groups_from_object type_arguments="AccelGroup"
+GtkAccelKey is_value_type="1"
gtk_accelerator_parse.accelerator_key is_out="1"
gtk_accelerator_parse.accelerator_mods is_out="1"
gtk_action_get_proxies type_arguments="Widget"
|
8ccfca3a2f0193f0a4da38e206c35cf08402218f
|
elasticsearch
|
Fielddata: Remove- BytesValues.WithOrdinals.currentOrd and copyShared.--These methods don't exist in Lucene's sorted set doc values.--Relates to -6524-
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/index/fielddata/AtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/AtomicFieldData.java
index 10afc29ec1154..21188c0f3e9f4 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/AtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/AtomicFieldData.java
@@ -19,10 +19,8 @@
package org.elasticsearch.index.fielddata;
-import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.index.fielddata.ScriptDocValues.Strings;
-import org.elasticsearch.index.fielddata.plain.AtomicFieldDataWithOrdinalsTermsEnum;
/**
* The thread safe {@link org.apache.lucene.index.AtomicReader} level cache of the data.
@@ -90,19 +88,9 @@ public long getOrd(int docId) {
public long getMaxOrd() {
return 0;
}
-
- @Override
- public long currentOrd() {
- return MISSING_ORDINAL;
- }
};
}
- @Override
- public TermsEnum getTermsEnum() {
- return new AtomicFieldDataWithOrdinalsTermsEnum(this);
- }
-
};
/**
@@ -111,11 +99,6 @@ public TermsEnum getTermsEnum() {
*/
BytesValues.WithOrdinals getBytesValues();
- /**
- * Returns a terms enum to iterate over all the underlying values.
- */
- TermsEnum getTermsEnum();
-
}
/**
diff --git a/src/main/java/org/elasticsearch/index/fielddata/BytesValues.java b/src/main/java/org/elasticsearch/index/fielddata/BytesValues.java
index ae15105d5ee87..fb615ac6703d3 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/BytesValues.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/BytesValues.java
@@ -20,8 +20,10 @@
package org.elasticsearch.index.fielddata;
import org.apache.lucene.index.SortedSetDocValues;
+import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchIllegalStateException;
+import org.elasticsearch.index.fielddata.plain.BytesValuesWithOrdinalsTermsEnum;
/**
* A state-full lightweight per document set of <code>byte[]</code> values.
@@ -60,15 +62,6 @@ public final boolean isMultiValued() {
return multiValued;
}
- /**
- * Converts the current shared {@link BytesRef} to a stable instance. Note,
- * this calls makes the bytes safe for *reads*, not writes (into the same BytesRef). For example,
- * it makes it safe to be placed in a map.
- */
- public BytesRef copyShared() {
- return BytesRef.deepCopyOf(scratch);
- }
-
/**
* Sets iteration to the specified docID and returns the number of
* values for this document ID,
@@ -139,12 +132,6 @@ protected WithOrdinals(boolean multiValued) {
*/
public abstract long nextOrd();
- /**
- * Returns the current ordinal in the iteration
- * @return the current ordinal in the iteration
- */
- public abstract long currentOrd();
-
/**
* Returns the value for the given ordinal.
* @param ord the ordinal to lookup.
@@ -157,6 +144,13 @@ protected WithOrdinals(boolean multiValued) {
public BytesRef nextValue() {
return getValueByOrd(nextOrd());
}
+
+ /**
+ * Returns a terms enum to iterate over all the underlying values.
+ */
+ public TermsEnum getTermsEnum() {
+ return new BytesValuesWithOrdinalsTermsEnum(this);
+ }
}
/**
diff --git a/src/main/java/org/elasticsearch/index/fielddata/ordinals/GlobalOrdinalMapping.java b/src/main/java/org/elasticsearch/index/fielddata/ordinals/GlobalOrdinalMapping.java
index 9b9d93ac8ba8e..d7b690db90a8f 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/ordinals/GlobalOrdinalMapping.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/ordinals/GlobalOrdinalMapping.java
@@ -43,11 +43,6 @@ public class GlobalOrdinalMapping extends BytesValues.WithOrdinals {
int readerIndex;
- @Override
- public BytesRef copyShared() {
- return bytesValues[readerIndex].copyShared();
- }
-
@Override
public long getMaxOrd() {
return ordinalMap.getValueCount();
@@ -67,11 +62,6 @@ public long nextOrd() {
return getGlobalOrd(values.nextOrd());
}
- @Override
- public long currentOrd() {
- return getGlobalOrd(values.currentOrd());
- }
-
@Override
public int setDocument(int docId) {
return values.setDocument(docId);
diff --git a/src/main/java/org/elasticsearch/index/fielddata/ordinals/InternalGlobalOrdinalsBuilder.java b/src/main/java/org/elasticsearch/index/fielddata/ordinals/InternalGlobalOrdinalsBuilder.java
index e9f721147d7a1..03307bd7c8ce3 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/ordinals/InternalGlobalOrdinalsBuilder.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/ordinals/InternalGlobalOrdinalsBuilder.java
@@ -49,7 +49,7 @@ public IndexFieldData.WithOrdinals build(final IndexReader indexReader, IndexFie
final TermsEnum[] subs = new TermsEnum[indexReader.leaves().size()];
for (int i = 0; i < indexReader.leaves().size(); ++i) {
atomicFD[i] = indexFieldData.load(indexReader.leaves().get(i));
- subs[i] = atomicFD[i].getTermsEnum();
+ subs[i] = atomicFD[i].getBytesValues().getTermsEnum();
}
final OrdinalMap ordinalMap = new OrdinalMap(null, subs);
final long memorySizeInBytes = ordinalMap.ramBytesUsed();
diff --git a/src/main/java/org/elasticsearch/index/fielddata/ordinals/InternalGlobalOrdinalsIndexFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/ordinals/InternalGlobalOrdinalsIndexFieldData.java
index 9007eabf6cb8c..d6f8b9bfba988 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/ordinals/InternalGlobalOrdinalsIndexFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/ordinals/InternalGlobalOrdinalsIndexFieldData.java
@@ -20,14 +20,12 @@
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.MultiDocValues.OrdinalMap;
-import org.apache.lucene.index.TermsEnum;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.fielddata.AtomicFieldData;
import org.elasticsearch.index.fielddata.BytesValues;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.ScriptDocValues;
-import org.elasticsearch.index.fielddata.plain.AtomicFieldDataWithOrdinalsTermsEnum;
import org.elasticsearch.index.mapper.FieldMapper;
/**
@@ -86,11 +84,6 @@ public ScriptDocValues getScriptValues() {
throw new UnsupportedOperationException("Script values not supported on global ordinals");
}
- @Override
- public TermsEnum getTermsEnum() {
- return new AtomicFieldDataWithOrdinalsTermsEnum(this);
- }
-
@Override
public void close() {
}
diff --git a/src/main/java/org/elasticsearch/index/fielddata/ordinals/MultiOrdinals.java b/src/main/java/org/elasticsearch/index/fielddata/ordinals/MultiOrdinals.java
index 9dd61999d6e49..7d0f53acb4afe 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/ordinals/MultiOrdinals.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/ordinals/MultiOrdinals.java
@@ -93,7 +93,6 @@ public static class MultiDocs extends BytesValues.WithOrdinals {
private final AppendingPackedLongBuffer ords;
private long offset;
private long limit;
- private long currentOrd;
private final ValuesHolder values;
MultiDocs(MultiOrdinals ordinals, ValuesHolder values) {
@@ -114,16 +113,16 @@ public long getOrd(int docId) {
final long startOffset = docId > 0 ? endOffsets.get(docId - 1) : 0;
final long endOffset = endOffsets.get(docId);
if (startOffset == endOffset) {
- return currentOrd = MISSING_ORDINAL; // ord for missing values
+ return MISSING_ORDINAL; // ord for missing values
} else {
- return currentOrd = ords.get(startOffset);
+ return ords.get(startOffset);
}
}
@Override
public long nextOrd() {
assert offset < limit;
- return currentOrd = ords.get(offset++);
+ return ords.get(offset++);
}
@Override
@@ -135,19 +134,9 @@ public int setDocument(int docId) {
return (int) (endOffset - startOffset);
}
- @Override
- public long currentOrd() {
- return currentOrd;
- }
-
@Override
public BytesRef getValueByOrd(long ord) {
return values.getValueByOrd(ord);
}
-
- @Override
- public BytesRef copyShared() {
- return values.copy(scratch);
- }
}
}
diff --git a/src/main/java/org/elasticsearch/index/fielddata/ordinals/SinglePackedOrdinals.java b/src/main/java/org/elasticsearch/index/fielddata/ordinals/SinglePackedOrdinals.java
index 5a00b1d089aaf..ea31542382ddf 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/ordinals/SinglePackedOrdinals.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/ordinals/SinglePackedOrdinals.java
@@ -95,19 +95,9 @@ public int setDocument(int docId) {
return 1 + (int) Math.min(currentOrdinal, 0);
}
- @Override
- public long currentOrd() {
- return currentOrdinal;
- }
-
@Override
public BytesRef getValueByOrd(long ord) {
return values.getValueByOrd(ord);
}
-
- @Override
- public BytesRef copyShared() {
- return values.copy(scratch);
- }
}
}
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/FSTBytesAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/FSTBytesAtomicFieldData.java
index 3bbc9f1c62db4..25360570bf789 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/FSTBytesAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/FSTBytesAtomicFieldData.java
@@ -18,7 +18,6 @@
*/
package org.elasticsearch.index.fielddata.plain;
-import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IntsRef;
import org.apache.lucene.util.fst.FST;
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/IndexIndexFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/IndexIndexFieldData.java
index 062407769d4bc..b18ab993e616b 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/IndexIndexFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/IndexIndexFieldData.java
@@ -21,7 +21,6 @@
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.Index;
@@ -75,11 +74,6 @@ public long getMaxOrd() {
return 1;
}
- @Override
- public long currentOrd() {
- return BytesValues.WithOrdinals.MIN_ORDINAL;
- }
-
@Override
public BytesRef getValueByOrd(long ord) {
return scratch;
@@ -114,11 +108,6 @@ public ScriptDocValues getScriptValues() {
public void close() {
}
- @Override
- public TermsEnum getTermsEnum() {
- return new AtomicFieldDataWithOrdinalsTermsEnum(this);
- }
-
}
private final FieldMapper.Names names;
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesAtomicFieldData.java
index bc590ec7d3b36..38451424ceaac 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/PagedBytesAtomicFieldData.java
@@ -18,7 +18,6 @@
*/
package org.elasticsearch.index.fielddata.plain;
-import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.PagedBytes;
import org.apache.lucene.util.packed.MonotonicAppendingLongBuffer;
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/ParentChildAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/ParentChildAtomicFieldData.java
index 4babac2caaad4..f380aea9bbf33 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/ParentChildAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/ParentChildAtomicFieldData.java
@@ -68,8 +68,7 @@ public int setDocument(int docId) {
int numValues = values.setDocument(docId);
assert numValues <= 1 : "Per doc/type combination only a single value is allowed";
if (numValues == 1) {
- values.nextValue();
- terms[counter++] = values.copyShared();
+ terms[counter++] = BytesRef.deepCopyOf(values.nextValue());
}
}
assert counter <= 2 : "A single doc can potentially be both parent and child, so the maximum allowed values is 2";
diff --git a/src/main/java/org/elasticsearch/index/fielddata/plain/SortedSetDVAtomicFieldData.java b/src/main/java/org/elasticsearch/index/fielddata/plain/SortedSetDVAtomicFieldData.java
index fb7fb6a397b44..b2c028f43454b 100644
--- a/src/main/java/org/elasticsearch/index/fielddata/plain/SortedSetDVAtomicFieldData.java
+++ b/src/main/java/org/elasticsearch/index/fielddata/plain/SortedSetDVAtomicFieldData.java
@@ -96,7 +96,6 @@ static class SortedSetValues extends BytesValues.WithOrdinals {
private final SortedSetDocValues values;
private long[] ords;
private int ordIndex = Integer.MAX_VALUE;
- private long currentOrdinal = -1;
SortedSetValues(SortedSetDocValues values) {
super(DocValues.unwrapSingleton(values) == null);
@@ -112,13 +111,13 @@ public long getMaxOrd() {
@Override
public long getOrd(int docId) {
values.setDocument(docId);
- return currentOrdinal = values.nextOrd();
+ return values.nextOrd();
}
@Override
public long nextOrd() {
assert ordIndex < ords.length;
- return currentOrdinal = ords[ordIndex++];
+ return ords[ordIndex++];
}
@Override
@@ -135,11 +134,6 @@ public int setDocument(int docId) {
return i;
}
- @Override
- public long currentOrd() {
- return currentOrdinal;
- }
-
@Override
public BytesRef getValueByOrd(long ord) {
values.lookupOrd(ord, scratch);
diff --git a/src/main/java/org/elasticsearch/index/percolator/QueriesLoaderCollector.java b/src/main/java/org/elasticsearch/index/percolator/QueriesLoaderCollector.java
index c988eef480c8d..67002ad878825 100644
--- a/src/main/java/org/elasticsearch/index/percolator/QueriesLoaderCollector.java
+++ b/src/main/java/org/elasticsearch/index/percolator/QueriesLoaderCollector.java
@@ -74,7 +74,7 @@ public void collect(int doc) throws IOException {
// id is only used for logging, if we fail we log the id in the catch statement
final Query parseQuery = percolator.parsePercolatorDocument(null, fieldsVisitor.source());
if (parseQuery != null) {
- queries.put(idValues.copyShared(), parseQuery);
+ queries.put(BytesRef.deepCopyOf(id), parseQuery);
} else {
logger.warn("failed to add query [{}] - parser returned null", id);
}
diff --git a/src/main/java/org/elasticsearch/index/search/child/ParentIdsFilter.java b/src/main/java/org/elasticsearch/index/search/child/ParentIdsFilter.java
index 4fbfcd72ec3c1..30460a59ee48c 100644
--- a/src/main/java/org/elasticsearch/index/search/child/ParentIdsFilter.java
+++ b/src/main/java/org/elasticsearch/index/search/child/ParentIdsFilter.java
@@ -23,14 +23,17 @@
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Filter;
-import org.apache.lucene.util.*;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.FixedBitSet;
+import org.apache.lucene.util.LongBitSet;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.lucene.search.AndFilter;
+import org.elasticsearch.common.util.BytesRefHash;
import org.elasticsearch.common.util.LongHash;
import org.elasticsearch.index.fielddata.BytesValues;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.mapper.internal.UidFieldMapper;
-import org.elasticsearch.common.util.BytesRefHash;
import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
@@ -49,8 +52,7 @@ static Filter createShortCircuitFilter(Filter nonNestedDocsFilter, SearchContext
String parentType, BytesValues.WithOrdinals globalValues,
LongBitSet parentOrds, long numFoundParents) {
if (numFoundParents == 1) {
- globalValues.getValueByOrd(parentOrds.nextSetBit(0));
- BytesRef id = globalValues.copyShared();
+ BytesRef id = globalValues.getValueByOrd(parentOrds.nextSetBit(0));
if (nonNestedDocsFilter != null) {
List<Filter> filters = Arrays.asList(
new TermFilter(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(parentType, id))),
@@ -83,8 +85,7 @@ static Filter createShortCircuitFilter(Filter nonNestedDocsFilter, SearchContext
String parentType, BytesValues.WithOrdinals globalValues,
LongHash parentIdxs, long numFoundParents) {
if (numFoundParents == 1) {
- globalValues.getValueByOrd(parentIdxs.get(0));
- BytesRef id = globalValues.copyShared();
+ BytesRef id = globalValues.getValueByOrd(parentIdxs.get(0));
if (nonNestedDocsFilter != null) {
List<Filter> filters = Arrays.asList(
new TermFilter(new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(parentType, id))),
diff --git a/src/main/java/org/elasticsearch/percolator/PercolatorService.java b/src/main/java/org/elasticsearch/percolator/PercolatorService.java
index 8326c79519817..9d1d12c7677b5 100644
--- a/src/main/java/org/elasticsearch/percolator/PercolatorService.java
+++ b/src/main/java/org/elasticsearch/percolator/PercolatorService.java
@@ -765,7 +765,7 @@ public PercolateShardResponse doPercolate(PercolateShardRequest request, Percola
final int numValues = values.setDocument(localDocId);
assert numValues == 1;
BytesRef bytes = values.nextValue();
- matches.add(values.copyShared());
+ matches.add(BytesRef.deepCopyOf(bytes));
if (hls != null) {
Query query = context.percolateQueries().get(bytes);
context.parsedQuery(new ParsedQuery(query, ImmutableMap.<String, Filter>of()));
diff --git a/src/main/java/org/elasticsearch/percolator/QueryCollector.java b/src/main/java/org/elasticsearch/percolator/QueryCollector.java
index f26eb447ccbe2..2b75753e4513e 100644
--- a/src/main/java/org/elasticsearch/percolator/QueryCollector.java
+++ b/src/main/java/org/elasticsearch/percolator/QueryCollector.java
@@ -212,7 +212,7 @@ public void collect(int doc) throws IOException {
}
if (collector.exists()) {
if (!limit || counter < size) {
- matches.add(values.copyShared());
+ matches.add(BytesRef.deepCopyOf(current));
if (context.highlight() != null) {
highlightPhase.hitExecute(context, context.hitContext());
hls.add(context.hitContext().hit().getHighlightFields());
@@ -334,7 +334,7 @@ public void collect(int doc) throws IOException {
}
if (collector.exists()) {
if (!limit || counter < size) {
- matches.add(values.copyShared());
+ matches.add(BytesRef.deepCopyOf(current));
scores.add(scorer.score());
if (context.highlight() != null) {
highlightPhase.hitExecute(context, context.hitContext());
diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/GlobalOrdinalsStringTermsAggregator.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/GlobalOrdinalsStringTermsAggregator.java
index 5d880322a343a..8c935a6f0738b 100644
--- a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/GlobalOrdinalsStringTermsAggregator.java
+++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/GlobalOrdinalsStringTermsAggregator.java
@@ -376,19 +376,9 @@ public int setDocument(int docId) {
return numAcceptedOrds;
}
- @Override
- public long currentOrd() {
- return currentOrd;
- }
-
@Override
public BytesRef getValueByOrd(long ord) {
return inner.getValueByOrd(ord);
}
-
- @Override
- public BytesRef copyShared() {
- return inner.copyShared();
- }
}
}
diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/StringTermsAggregator.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/StringTermsAggregator.java
index 3767c13fad42c..22b20347a4a2a 100644
--- a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/StringTermsAggregator.java
+++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/StringTermsAggregator.java
@@ -89,6 +89,7 @@ public void collect(int doc, long owningBucketOrdinal) throws IOException {
}
}
+ // TODO: use terms enum
/** Returns an iterator over the field data terms. */
private static Iterator<BytesRef> terms(final BytesValues.WithOrdinals bytesValues, boolean reverse) {
if (reverse) {
@@ -103,8 +104,7 @@ public boolean hasNext() {
@Override
public BytesRef next() {
- bytesValues.getValueByOrd(i--);
- return bytesValues.copyShared();
+ return BytesRef.deepCopyOf(bytesValues.getValueByOrd(i--));
}
};
@@ -120,8 +120,7 @@ public boolean hasNext() {
@Override
public BytesRef next() {
- bytesValues.getValueByOrd(i++);
- return bytesValues.copyShared();
+ return BytesRef.deepCopyOf(bytesValues.getValueByOrd(i++));
}
};
diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/support/IncludeExclude.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/support/IncludeExclude.java
index 517a6511811e2..11a66ad801aad 100644
--- a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/support/IncludeExclude.java
+++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/support/IncludeExclude.java
@@ -79,7 +79,7 @@ public boolean accept(BytesRef value) {
* Computes which global ordinals are accepted by this IncludeExclude instance.
*/
public LongBitSet acceptedGlobalOrdinals(BytesValues.WithOrdinals globalOrdinals, ValuesSource.Bytes.WithOrdinals valueSource) {
- TermsEnum globalTermsEnum = valueSource.getGlobalTermsEnum();
+ TermsEnum globalTermsEnum = valueSource.globalBytesValues().getTermsEnum();
LongBitSet acceptedGlobalOrdinals = new LongBitSet(globalOrdinals.getMaxOrd());
try {
for (BytesRef term = globalTermsEnum.next(); term != null; term = globalTermsEnum.next()) {
diff --git a/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSource.java b/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSource.java
index 77e88267d3530..a79ee07477c82 100644
--- a/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSource.java
+++ b/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSource.java
@@ -21,7 +21,6 @@
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexReaderContext;
-import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
@@ -176,8 +175,6 @@ public static abstract class WithOrdinals extends Bytes implements TopReaderCont
public abstract long globalMaxOrd(IndexSearcher indexSearcher);
- public abstract TermsEnum getGlobalTermsEnum();
-
public static class FieldData extends WithOrdinals implements ReaderContextAware {
protected final IndexFieldData.WithOrdinals<?> indexFieldData;
@@ -262,11 +259,6 @@ public long globalMaxOrd(IndexSearcher indexSearcher) {
return maxOrd = values.getMaxOrd();
}
}
-
- @Override
- public TermsEnum getGlobalTermsEnum() {
- return globalAtomicFieldData.getTermsEnum();
- }
}
}
diff --git a/src/main/java/org/elasticsearch/search/facet/terms/strings/TermsStringOrdinalsFacetExecutor.java b/src/main/java/org/elasticsearch/search/facet/terms/strings/TermsStringOrdinalsFacetExecutor.java
index 91ec3093dc08a..1d05ea5ceb30c 100644
--- a/src/main/java/org/elasticsearch/search/facet/terms/strings/TermsStringOrdinalsFacetExecutor.java
+++ b/src/main/java/org/elasticsearch/search/facet/terms/strings/TermsStringOrdinalsFacetExecutor.java
@@ -280,7 +280,7 @@ public boolean nextPosition() {
}
public BytesRef copyCurrent() {
- return values.copyShared();
+ return BytesRef.deepCopyOf(current);
}
@Override
diff --git a/src/main/java/org/elasticsearch/search/facet/termsstats/strings/TermsStatsStringFacetExecutor.java b/src/main/java/org/elasticsearch/search/facet/termsstats/strings/TermsStatsStringFacetExecutor.java
index 1b62bc5cf0c02..5aff3b64d86ca 100644
--- a/src/main/java/org/elasticsearch/search/facet/termsstats/strings/TermsStatsStringFacetExecutor.java
+++ b/src/main/java/org/elasticsearch/search/facet/termsstats/strings/TermsStatsStringFacetExecutor.java
@@ -170,7 +170,7 @@ public void onValue(int docId, BytesRef value, int hashCode, BytesValues values)
spare.reset(value, hashCode);
InternalTermsStatsStringFacet.StringEntry stringEntry = entries.get(spare);
if (stringEntry == null) {
- HashedBytesRef theValue = new HashedBytesRef(values.copyShared(), hashCode);
+ HashedBytesRef theValue = new HashedBytesRef(BytesRef.deepCopyOf(value), hashCode);
stringEntry = new InternalTermsStatsStringFacet.StringEntry(theValue, 0, 0, 0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY);
entries.put(theValue, stringEntry);
}
@@ -210,7 +210,7 @@ public void onValue(int docId, BytesRef value, int hashCode, BytesValues values)
spare.reset(value, hashCode);
InternalTermsStatsStringFacet.StringEntry stringEntry = entries.get(spare);
if (stringEntry == null) {
- HashedBytesRef theValue = new HashedBytesRef(values.copyShared(), hashCode);
+ HashedBytesRef theValue = new HashedBytesRef(BytesRef.deepCopyOf(value), hashCode);
stringEntry = new InternalTermsStatsStringFacet.StringEntry(theValue, 1, 0, 0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY);
entries.put(theValue, stringEntry);
} else {
diff --git a/src/test/java/org/elasticsearch/index/fielddata/AbstractStringFieldDataTests.java b/src/test/java/org/elasticsearch/index/fielddata/AbstractStringFieldDataTests.java
index 9bc4d7db61b29..d0f98e2b58648 100644
--- a/src/test/java/org/elasticsearch/index/fielddata/AbstractStringFieldDataTests.java
+++ b/src/test/java/org/elasticsearch/index/fielddata/AbstractStringFieldDataTests.java
@@ -506,7 +506,7 @@ public void testTermsEnum() throws Exception {
IndexFieldData.WithOrdinals ifd = getForField("value");
AtomicFieldData.WithOrdinals afd = ifd.load(atomicReaderContext);
- TermsEnum termsEnum = afd.getTermsEnum();
+ TermsEnum termsEnum = afd.getBytesValues().getTermsEnum();
int size = 0;
while (termsEnum.next() != null) {
size++;
diff --git a/src/test/java/org/elasticsearch/search/aggregations/support/FieldDataSourceTests.java b/src/test/java/org/elasticsearch/search/aggregations/support/FieldDataSourceTests.java
index 299f64c133d73..4f18bd4ee456a 100644
--- a/src/test/java/org/elasticsearch/search/aggregations/support/FieldDataSourceTests.java
+++ b/src/test/java/org/elasticsearch/search/aggregations/support/FieldDataSourceTests.java
@@ -112,40 +112,8 @@ public double runAsDouble() {
};
}
- private static void assertConsistent(BytesValues values) {
- final int numDocs = scaledRandomIntBetween(10, 100);
- for (int i = 0; i < numDocs; ++i) {
- final int valueCount = values.setDocument(i);
- for (int j = 0; j < valueCount; ++j) {
- final BytesRef term = values.nextValue();
- assertTrue(term.bytesEquals(values.copyShared()));
- }
- }
- }
-
- @Test
- public void bytesValuesWithScript() {
- final BytesValues values = randomBytesValues();
- ValuesSource source = new ValuesSource.Bytes() {
-
- @Override
- public BytesValues bytesValues() {
- return values;
- }
-
- @Override
- public MetaData metaData() {
- throw new UnsupportedOperationException();
- }
-
- };
- SearchScript script = randomScript();
- assertConsistent(new ValuesSource.WithScript.BytesValues(source, script));
- }
-
@Test
public void sortedUniqueBytesValues() {
- assertConsistent(new ValuesSource.Bytes.SortedAndUnique.SortedUniqueBytesValues(randomBytesValues()));
assertSortedAndUnique(new ValuesSource.Bytes.SortedAndUnique.SortedUniqueBytesValues(randomBytesValues()));
}
@@ -160,7 +128,7 @@ private static void assertSortedAndUnique(BytesValues values) {
if (j > 0) {
assertThat(BytesRef.getUTF8SortedAsUnicodeComparator().compare(ref.get(ref.size() - 1), term), lessThan(0));
}
- ref.add(values.copyShared());
+ ref.add(BytesRef.deepCopyOf(term));
}
}
}
|
21cad21f6765e2af1b6faf3d1e716cb9860d433f
|
Mylyn Reviews
|
Removed stderr output
|
p
|
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 13f92a7e..695f25f4 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
@@ -49,7 +49,6 @@ private ReaderCreator getPatch() {
@Override
public Reader createReader() throws CoreException {
try {
- System.err.println(attachment.getUrl());
return new InputStreamReader(
new URL(attachment.getUrl()).openStream());
} catch (Exception e) {
|
fa6c7e82d706d9e733fd2dac0164f3fcbde86d05
|
apache$hama
|
[HAMA-704]: Optimization of memory usage during message processing
git-svn-id: https://svn.apache.org/repos/asf/hama/trunk@1449666 13f79535-47bb-0310-9956-ffa450edef68
|
p
|
https://github.com/apache/hama
|
diff --git a/CHANGES.txt b/CHANGES.txt
index c6940e524..e7cbf2b64 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -19,6 +19,7 @@ Release 0.7 (unreleased changes)
IMPROVEMENTS
+ HAMA-704: Optimization of memory usage during message processing (tjungblut)
HAMA-735: Tighten the graph API (tjungblut)
HAMA-714: Align format consistency between examples and generators (edwardyoon)
HAMA-531: Reimplementation of partitioner (edwardyoon)
diff --git a/conf/hama-default.xml b/conf/hama-default.xml
index c7225a85a..c52616385 100644
--- a/conf/hama-default.xml
+++ b/conf/hama-default.xml
@@ -91,6 +91,11 @@
<value>${hama.tmp.dir}/messages/</value>
<description>Temporary directory on the local message buffer on disk.</description>
</property>
+ <property>
+ <name>hama.disk.vertices.path</name>
+ <value>${hama.tmp.dir}/graph/</value>
+ <description>Disk directory for graph data.</description>
+ </property>
<property>
<name>bsp.child.java.opts</name>
<value>-Xmx1024m</value>
diff --git a/core/src/main/java/org/apache/hama/bsp/SimpleTaskScheduler.java b/core/src/main/java/org/apache/hama/bsp/SimpleTaskScheduler.java
index f47ac924a..3827049da 100644
--- a/core/src/main/java/org/apache/hama/bsp/SimpleTaskScheduler.java
+++ b/core/src/main/java/org/apache/hama/bsp/SimpleTaskScheduler.java
@@ -357,8 +357,7 @@ public void run() {
final Act act = new Act(new ZKCollector(zk, "jvm", "Jvm metrics.",
jvmPath), new CollectorHandler() {
@Override
- public void handle(@SuppressWarnings("rawtypes")
- Future future) {
+ public void handle(@SuppressWarnings("rawtypes") Future future) {
try {
MetricsRecord record = (MetricsRecord) future.get();
if (null != record) {
diff --git a/core/src/main/java/org/apache/hama/bsp/ft/AsyncRcvdMsgCheckpointImpl.java b/core/src/main/java/org/apache/hama/bsp/ft/AsyncRcvdMsgCheckpointImpl.java
index ca38934b8..57778f67b 100644
--- a/core/src/main/java/org/apache/hama/bsp/ft/AsyncRcvdMsgCheckpointImpl.java
+++ b/core/src/main/java/org/apache/hama/bsp/ft/AsyncRcvdMsgCheckpointImpl.java
@@ -280,8 +280,7 @@ private void restartJob(long superstep,
@Override
public FaultTolerantPeerService<M> constructPeerFaultTolerance(BSPJob job,
- @SuppressWarnings("rawtypes")
- BSPPeer bspPeer, PeerSyncClient syncClient,
+ @SuppressWarnings("rawtypes") BSPPeer bspPeer, PeerSyncClient syncClient,
InetSocketAddress peerAddress, TaskAttemptID taskAttemptId,
long superstep, Configuration conf, MessageManager<M> messenger)
throws Exception {
@@ -327,8 +326,9 @@ public static class CheckpointPeerService<M extends Writable> implements
volatile private FSDataOutputStream checkpointStream;
volatile private long checkpointMessageCount;
- public void initialize(BSPJob job, @SuppressWarnings("rawtypes")
- BSPPeer bspPeer, PeerSyncClient syncClient, InetSocketAddress peerAddress,
+ public void initialize(BSPJob job,
+ @SuppressWarnings("rawtypes") BSPPeer bspPeer,
+ PeerSyncClient syncClient, InetSocketAddress peerAddress,
TaskAttemptID taskAttemptId, long superstep, Configuration conf,
MessageManager<M> messenger) throws IOException {
diff --git a/core/src/main/java/org/apache/hama/bsp/ft/BSPFaultTolerantService.java b/core/src/main/java/org/apache/hama/bsp/ft/BSPFaultTolerantService.java
index ab031a167..d817c542b 100644
--- a/core/src/main/java/org/apache/hama/bsp/ft/BSPFaultTolerantService.java
+++ b/core/src/main/java/org/apache/hama/bsp/ft/BSPFaultTolerantService.java
@@ -81,8 +81,7 @@ public FaultTolerantMasterService constructMasterFaultTolerance(
* <code>FaultTolerantPeerService</code>
*/
public FaultTolerantPeerService<M> constructPeerFaultTolerance(BSPJob job,
- @SuppressWarnings("rawtypes")
- BSPPeer bspPeer, PeerSyncClient syncClient,
+ @SuppressWarnings("rawtypes") BSPPeer bspPeer, PeerSyncClient syncClient,
InetSocketAddress peerAddress, TaskAttemptID taskAttemptId,
long superstep, Configuration conf, MessageManager<M> messenger)
throws Exception;
diff --git a/core/src/main/java/org/apache/hama/util/ReflectionUtils.java b/core/src/main/java/org/apache/hama/util/ReflectionUtils.java
index 01fe07a08..0b8537be0 100644
--- a/core/src/main/java/org/apache/hama/util/ReflectionUtils.java
+++ b/core/src/main/java/org/apache/hama/util/ReflectionUtils.java
@@ -49,6 +49,7 @@ public static <T> T newInstance(Class<T> theClass) {
Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass);
if (null == meth) {
meth = theClass.getDeclaredConstructor(new Class[0]);
+ meth.setAccessible(true);
CONSTRUCTOR_CACHE.put(theClass, meth);
}
result = meth.newInstance();
diff --git a/core/src/test/java/org/apache/hama/bsp/TestCheckpoint.java b/core/src/test/java/org/apache/hama/bsp/TestCheckpoint.java
index 60541d7bb..b8994d562 100644
--- a/core/src/test/java/org/apache/hama/bsp/TestCheckpoint.java
+++ b/core/src/test/java/org/apache/hama/bsp/TestCheckpoint.java
@@ -442,8 +442,8 @@ public void close() throws IOException {
}
private static void checkSuperstepMsgCount(PeerSyncClient syncClient,
- @SuppressWarnings("rawtypes")
- BSPPeer bspTask, BSPJob job, long step, long count) {
+ @SuppressWarnings("rawtypes") BSPPeer bspTask, BSPJob job, long step,
+ long count) {
ArrayWritable writableVal = new ArrayWritable(LongWritable.class);
diff --git a/core/src/test/java/org/apache/hama/monitor/TestFederator.java b/core/src/test/java/org/apache/hama/monitor/TestFederator.java
index 95270f7fd..e90c0f7c5 100644
--- a/core/src/test/java/org/apache/hama/monitor/TestFederator.java
+++ b/core/src/test/java/org/apache/hama/monitor/TestFederator.java
@@ -71,8 +71,7 @@ public void testExecutionFlow() throws Exception {
final Act act = new Act(new DummyCollector(expected),
new CollectorHandler() {
@Override
- public void handle(@SuppressWarnings("rawtypes")
- Future future) {
+ public void handle(@SuppressWarnings("rawtypes") Future future) {
try {
finalResult.set(((Integer) future.get()).intValue());
LOG.info("Value after submitted: " + finalResult);
diff --git a/examples/src/main/java/org/apache/hama/examples/BipartiteMatching.java b/examples/src/main/java/org/apache/hama/examples/BipartiteMatching.java
index ba41939ff..b6b264b44 100644
--- a/examples/src/main/java/org/apache/hama/examples/BipartiteMatching.java
+++ b/examples/src/main/java/org/apache/hama/examples/BipartiteMatching.java
@@ -17,8 +17,6 @@
*/
package org.apache.hama.examples;
-import java.io.DataInput;
-import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
@@ -59,22 +57,15 @@ public static class BipartiteMatchingVertex extends
private final static Text LEFT = new Text("L");
private final static Text RIGHT = new Text("R");
- // Needed because Vertex value and message sent have same types.
- private TextPair reusableMessage;
- private Random random;
-
@Override
public void setup(Configuration conf) {
this.getPeer().getNumCurrentMessages();
- reusableMessage = new TextPair(new Text(getVertexID()), new Text("1"))
- .setNames("SourceVertex", "Vestige");
- random = new Random(Long.parseLong(getConf().get(SEED_CONFIGURATION_KEY,
- System.currentTimeMillis() + "")));
}
@Override
- public void compute(Iterator<TextPair> messages) throws IOException {
-
+ public void compute(Iterable<TextPair> msgs) throws IOException {
+ Random random = new Random(Long.parseLong(getConf().get(
+ SEED_CONFIGURATION_KEY)));
if (isMatched()) {
voteToHalt();
return;
@@ -90,8 +81,8 @@ public void compute(Iterator<TextPair> messages) throws IOException {
case 1:
if (Objects.equal(getComponent(), RIGHT)) {
List<TextPair> buffer = new ArrayList<TextPair>();
- while (messages.hasNext()) {
- buffer.add(messages.next());
+ for (TextPair next : msgs) {
+ buffer.add(new TextPair(next.getFirst(), next.getSecond()));
}
if (buffer.size() > 0) {
TextPair luckyMsg = buffer.get(RandomUtils.nextInt(random,
@@ -106,9 +97,8 @@ public void compute(Iterator<TextPair> messages) throws IOException {
case 2:
if (Objects.equal(getComponent(), LEFT)) {
List<TextPair> buffer = new ArrayList<TextPair>();
-
- while (messages.hasNext()) {
- buffer.add(messages.next());
+ for (TextPair next : msgs) {
+ buffer.add(new TextPair(next.getFirst(), next.getSecond()));
}
if (buffer.size() > 0) {
TextPair luckyMsg = buffer.get(RandomUtils.nextInt(random,
@@ -123,8 +113,10 @@ public void compute(Iterator<TextPair> messages) throws IOException {
case 3:
if (Objects.equal(getComponent(), RIGHT)) {
+ Iterator<TextPair> messages = msgs.iterator();
if (messages.hasNext()) {
- Text sourceVertex = getSourceVertex(messages.next());
+ TextPair next = messages.next();
+ Text sourceVertex = getSourceVertex(next);
setMatchVertex(sourceVertex);
}
}
@@ -147,7 +139,7 @@ private void setMatchVertex(Text matchVertex) {
}
private TextPair getNewMessage() {
- return reusableMessage;
+ return new TextPair(new Text(getVertexID()), new Text("1"));
}
/**
@@ -161,26 +153,6 @@ private boolean isMatched() {
return !getValue().getFirst().equals(UNMATCHED);
}
- @Override
- public void readState(DataInput in) throws IOException {
- if (in.readBoolean()) {
- reusableMessage = new TextPair();
- reusableMessage.readFields(in);
- }
-
- }
-
- @Override
- public void writeState(DataOutput out) throws IOException {
- if (reusableMessage == null) {
- out.writeBoolean(false);
- } else {
- out.writeBoolean(true);
- reusableMessage.write(out);
- }
-
- }
-
}
/**
@@ -204,8 +176,7 @@ public boolean parseVertex(LongWritable key, Text value,
String[] selfArray = tokenArray[0].trim().split(" ");
vertex.setVertexID(new Text(selfArray[0]));
- vertex.setValue(new TextPair(UNMATCHED, new Text(selfArray[1])).setNames(
- "MatchVertex", "Component"));
+ vertex.setValue(new TextPair(UNMATCHED, new Text(selfArray[1])));
// initially a node is unmatched, which is denoted by U.
for (String adjNode : adjArray) {
diff --git a/examples/src/main/java/org/apache/hama/examples/InlinkCount.java b/examples/src/main/java/org/apache/hama/examples/InlinkCount.java
index 369f8881c..81cfa21a5 100644
--- a/examples/src/main/java/org/apache/hama/examples/InlinkCount.java
+++ b/examples/src/main/java/org/apache/hama/examples/InlinkCount.java
@@ -18,7 +18,6 @@
package org.apache.hama.examples;
import java.io.IOException;
-import java.util.Iterator;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
@@ -37,14 +36,13 @@
public class InlinkCount extends Vertex<Text, NullWritable, IntWritable> {
@Override
- public void compute(Iterator<IntWritable> messages) throws IOException {
+ public void compute(Iterable<IntWritable> messages) throws IOException {
if (getSuperstepCount() == 0L) {
setValue(new IntWritable(0));
sendMessageToNeighbors(new IntWritable(1));
} else {
- while (messages.hasNext()) {
- IntWritable msg = messages.next();
+ for (IntWritable msg : messages) {
this.setValue(new IntWritable(this.getValue().get() + msg.get()));
}
voteToHalt();
diff --git a/examples/src/main/java/org/apache/hama/examples/MindistSearch.java b/examples/src/main/java/org/apache/hama/examples/MindistSearch.java
index 784cfca39..73d5e563f 100644
--- a/examples/src/main/java/org/apache/hama/examples/MindistSearch.java
+++ b/examples/src/main/java/org/apache/hama/examples/MindistSearch.java
@@ -18,7 +18,6 @@
package org.apache.hama.examples;
import java.io.IOException;
-import java.util.Iterator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
@@ -49,7 +48,7 @@ public static class MindistSearchVertex extends
Vertex<Text, NullWritable, Text> {
@Override
- public void compute(Iterator<Text> messages) throws IOException {
+ public void compute(Iterable<Text> messages) throws IOException {
Text currentComponent = getValue();
if (getSuperstepCount() == 0L) {
// if we have no associated component, pick the lowest in our direct
@@ -66,8 +65,7 @@ public void compute(Iterator<Text> messages) throws IOException {
}
} else {
boolean updated = false;
- while (messages.hasNext()) {
- Text next = messages.next();
+ for (Text next : messages) {
if (currentComponent != null && next != null) {
if (currentComponent.compareTo(next) > 0) {
updated = true;
diff --git a/examples/src/main/java/org/apache/hama/examples/PageRank.java b/examples/src/main/java/org/apache/hama/examples/PageRank.java
index 64b0cc5fe..c00e4a22c 100644
--- a/examples/src/main/java/org/apache/hama/examples/PageRank.java
+++ b/examples/src/main/java/org/apache/hama/examples/PageRank.java
@@ -18,7 +18,6 @@
package org.apache.hama.examples;
import java.io.IOException;
-import java.util.Iterator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
@@ -31,7 +30,6 @@
import org.apache.hama.bsp.SequenceFileInputFormat;
import org.apache.hama.bsp.TextArrayWritable;
import org.apache.hama.bsp.TextOutputFormat;
-import org.apache.hama.graph.AbstractAggregator;
import org.apache.hama.graph.AverageAggregator;
import org.apache.hama.graph.Edge;
import org.apache.hama.graph.GraphJob;
@@ -49,8 +47,6 @@ public static class PageRankVertex extends
static double DAMPING_FACTOR = 0.85;
static double MAXIMUM_CONVERGENCE_ERROR = 0.001;
- int numEdges;
-
@Override
public void setup(Configuration conf) {
String val = conf.get("hama.pagerank.alpha");
@@ -61,30 +57,20 @@ public void setup(Configuration conf) {
if (val != null) {
MAXIMUM_CONVERGENCE_ERROR = Double.parseDouble(val);
}
- numEdges = this.getEdges().size();
}
@Override
- public void compute(Iterator<DoubleWritable> messages) throws IOException {
+ public void compute(Iterable<DoubleWritable> messages) throws IOException {
// initialize this vertex to 1 / count of global vertices in this graph
if (this.getSuperstepCount() == 0) {
this.setValue(new DoubleWritable(1.0 / this.getNumVertices()));
} else if (this.getSuperstepCount() >= 1) {
- DoubleWritable danglingNodeContribution = getLastAggregatedValue(1);
double sum = 0;
- while (messages.hasNext()) {
- DoubleWritable msg = messages.next();
+ for (DoubleWritable msg : messages) {
sum += msg.get();
}
- if (danglingNodeContribution == null) {
- double alpha = (1.0d - DAMPING_FACTOR) / this.getNumVertices();
- this.setValue(new DoubleWritable(alpha + (DAMPING_FACTOR * sum)));
- } else {
- double alpha = (1.0d - DAMPING_FACTOR) / this.getNumVertices();
- this.setValue(new DoubleWritable(alpha
- + (DAMPING_FACTOR * (sum + danglingNodeContribution.get()
- / this.getNumVertices()))));
- }
+ double alpha = (1.0d - DAMPING_FACTOR) / this.getNumVertices();
+ this.setValue(new DoubleWritable(alpha + (sum * DAMPING_FACTOR)));
}
// if we have not reached our global error yet, then proceed.
@@ -94,34 +80,10 @@ public void compute(Iterator<DoubleWritable> messages) throws IOException {
voteToHalt();
return;
}
+
// in each superstep we are going to send a new rank to our neighbours
sendMessageToNeighbors(new DoubleWritable(this.getValue().get()
- / numEdges));
- }
-
- }
-
- public static class DanglingNodeAggregator
- extends
- AbstractAggregator<DoubleWritable, Vertex<Text, NullWritable, DoubleWritable>> {
-
- double danglingNodeSum;
-
- @Override
- public void aggregate(Vertex<Text, NullWritable, DoubleWritable> vertex,
- DoubleWritable value) {
- if (vertex != null) {
- if (vertex.getEdges().size() == 0) {
- danglingNodeSum += value.get();
- }
- } else {
- danglingNodeSum += value.get();
- }
- }
-
- @Override
- public DoubleWritable getValue() {
- return new DoubleWritable(danglingNodeSum);
+ / this.getEdges().size()));
}
}
@@ -142,7 +104,6 @@ public boolean parseVertex(Text key, TextArrayWritable value,
}
}
- @SuppressWarnings("unchecked")
public static GraphJob createJob(String[] args, HamaConfiguration conf)
throws IOException {
GraphJob pageJob = new GraphJob(conf, PageRank.class);
@@ -155,15 +116,17 @@ public static GraphJob createJob(String[] args, HamaConfiguration conf)
// set the defaults
pageJob.setMaxIteration(30);
pageJob.set("hama.pagerank.alpha", "0.85");
+ // reference vertices to itself, because we don't have a dangling node
+ // contribution here
+ pageJob.set("hama.graph.self.ref", "true");
pageJob.set("hama.graph.max.convergence.error", "0.001");
if (args.length == 3) {
pageJob.setNumBspTask(Integer.parseInt(args[2]));
}
- // error, dangling node probability sum
- pageJob.setAggregatorClass(AverageAggregator.class,
- DanglingNodeAggregator.class);
+ // error
+ pageJob.setAggregatorClass(AverageAggregator.class);
// Vertex reader
pageJob.setVertexInputReaderClass(PagerankSeqReader.class);
diff --git a/examples/src/main/java/org/apache/hama/examples/SSSP.java b/examples/src/main/java/org/apache/hama/examples/SSSP.java
index b3e168977..6b3b3aa90 100644
--- a/examples/src/main/java/org/apache/hama/examples/SSSP.java
+++ b/examples/src/main/java/org/apache/hama/examples/SSSP.java
@@ -20,6 +20,7 @@
import java.io.IOException;
import java.util.Iterator;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
@@ -41,7 +42,8 @@ public class SSSP {
public static class ShortestPathVertex extends
Vertex<Text, IntWritable, IntWritable> {
- public ShortestPathVertex() {
+ @Override
+ public void setup(Configuration conf) {
this.setValue(new IntWritable(Integer.MAX_VALUE));
}
@@ -51,11 +53,10 @@ public boolean isStartVertex() {
}
@Override
- public void compute(Iterator<IntWritable> messages) throws IOException {
+ public void compute(Iterable<IntWritable> messages) throws IOException {
int minDist = isStartVertex() ? 0 : Integer.MAX_VALUE;
- while (messages.hasNext()) {
- IntWritable msg = messages.next();
+ for (IntWritable msg : messages) {
if (msg.get() < minDist) {
minDist = msg.get();
}
diff --git a/examples/src/main/java/org/apache/hama/examples/util/TextPair.java b/examples/src/main/java/org/apache/hama/examples/util/TextPair.java
index c8f4f959d..975f41e37 100644
--- a/examples/src/main/java/org/apache/hama/examples/util/TextPair.java
+++ b/examples/src/main/java/org/apache/hama/examples/util/TextPair.java
@@ -24,8 +24,6 @@
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
-import com.google.common.base.Objects;
-
/**
* TextPair class for use in BipartiteMatching algorithm.
*
@@ -35,9 +33,6 @@ public final class TextPair implements Writable {
Text first;
Text second;
- String nameFirst = "First";
- String nameSecond = "Second";
-
public TextPair() {
first = new Text();
second = new Text();
@@ -48,15 +43,6 @@ public TextPair(Text first, Text second) {
this.second = second;
}
- /**
- * Sets the names of the attributes
- */
- public TextPair setNames(String nameFirst, String nameSecond) {
- this.nameFirst = nameFirst;
- this.nameSecond = nameSecond;
- return this;
- }
-
public Text getFirst() {
return first;
}
@@ -75,8 +61,6 @@ public void setSecond(Text second) {
@Override
public void write(DataOutput out) throws IOException {
- (new Text(nameFirst)).write(out);
- (new Text(nameSecond)).write(out);
first.write(out);
second.write(out);
}
@@ -84,20 +68,13 @@ public void write(DataOutput out) throws IOException {
@Override
public void readFields(DataInput in) throws IOException {
- Text t1 = new Text();
- Text t2 = new Text();
- t1.readFields(in);
- t2.readFields(in);
- nameFirst = t1.toString();
- nameSecond = t2.toString();
first.readFields(in);
second.readFields(in);
}
@Override
public String toString() {
- return Objects.toStringHelper(this).add(nameFirst, getFirst())
- .add(nameSecond, getSecond()).toString();
+ return first + " " + second;
}
}
diff --git a/examples/src/test/java/org/apache/hama/examples/BipartiteMatchingTest.java b/examples/src/test/java/org/apache/hama/examples/BipartiteMatchingTest.java
index 610038501..f32d2c5b2 100644
--- a/examples/src/test/java/org/apache/hama/examples/BipartiteMatchingTest.java
+++ b/examples/src/test/java/org/apache/hama/examples/BipartiteMatchingTest.java
@@ -46,15 +46,13 @@ public class BipartiteMatchingTest extends TestCase {
private final static String DELIMETER = "\t";
- @SuppressWarnings("serial")
- private Map<String, String> output1 = new HashMap<String, String>() {
- {
- put("C", "TextPair{MatchVertex=D, Component=L}");
- put("A", "TextPair{MatchVertex=B, Component=L}");
- put("D", "TextPair{MatchVertex=C, Component=R}");
- put("B", "TextPair{MatchVertex=A, Component=R}");
- }
- };
+ private Map<String, String> output1 = new HashMap<String, String>();
+ {
+ output1.put("A", "D L");
+ output1.put("B", "C R");
+ output1.put("C", "B L");
+ output1.put("D", "A R");
+ }
public static class CustomTextPartitioner implements
Partitioner<Text, TextPair> {
@@ -110,36 +108,27 @@ private void generateTestData() {
private void verifyResult() throws IOException {
FileStatus[] files = fs.globStatus(new Path(OUTPUT + "/part-*"));
- assertTrue(files.length == 2);
-
- Text key = new Text();
- Text value = new Text();
+ assertTrue("Not enough files found: " + files.length, files.length == 2);
for (FileStatus file : files) {
if (file.getLen() > 0) {
FSDataInputStream in = fs.open(file.getPath());
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
- String s = bin.readLine();
- while (s != null) {
- next(key, value, s);
- String expValue = output1.get(key.toString());
- System.out.println(key + " " + value + " expvalue = " + expValue);
- assertEquals(expValue, value.toString());
-
- s = bin.readLine();
+ String s = null;
+ while ((s = bin.readLine()) != null) {
+ String[] lineA = s.split(DELIMETER);
+ String expValue = output1.get(lineA[0]);
+ assertNotNull(expValue);
+ System.out.println(lineA[0] + " -> " + lineA[1] + " expvalue = "
+ + expValue);
+ assertEquals(expValue, lineA[1]);
}
in.close();
}
}
}
- private static void next(Text key, Text value, String line) {
- String[] lineA = line.split(DELIMETER);
- key.set(lineA[0]);
- value.set(lineA[1]);
- }
-
private void deleteTempDirs() {
try {
if (fs.exists(new Path(INPUT)))
diff --git a/examples/src/test/java/org/apache/hama/examples/PageRankTest.java b/examples/src/test/java/org/apache/hama/examples/PageRankTest.java
new file mode 100644
index 000000000..8e74554b9
--- /dev/null
+++ b/examples/src/test/java/org/apache/hama/examples/PageRankTest.java
@@ -0,0 +1,126 @@
+/**
+ * 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.hama.examples;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+import junit.framework.TestCase;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.SequenceFile;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.Writable;
+import org.apache.hama.HamaConfiguration;
+import org.apache.hama.bsp.TextArrayWritable;
+import org.junit.Test;
+
+/**
+ * Testcase for {@link PageRank}
+ */
+public class PageRankTest extends TestCase {
+ String[] input = new String[] { "1\t2\t3", "2", "3\t1\t2\t5", "4\t5\t6",
+ "5\t4\t6", "6\t4", "7\t2\t4" };
+
+ private static String INPUT = "/tmp/page-tmp.seq";
+ private static String TEXT_INPUT = "/tmp/page.txt";
+ private static String TEXT_OUTPUT = INPUT + "page.txt.seq";
+ private static String OUTPUT = "/tmp/page-out";
+ private Configuration conf = new HamaConfiguration();
+ private FileSystem fs;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ fs = FileSystem.get(conf);
+ }
+
+ @Test
+ public void testPageRank() throws IOException, InterruptedException,
+ ClassNotFoundException, InstantiationException, IllegalAccessException {
+
+ generateTestData();
+ try {
+ PageRank.main(new String[] { INPUT, OUTPUT, "3" });
+ verifyResult();
+ } finally {
+ deleteTempDirs();
+ }
+ }
+
+ private void verifyResult() throws IOException {
+ FileStatus[] globStatus = fs.globStatus(new Path(OUTPUT + "/part-*"));
+ double sum = 0d;
+ for (FileStatus fts : globStatus) {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ fs.open(fts.getPath())));
+ String line = null;
+ while ((line = reader.readLine()) != null) {
+ System.out.println(line);
+ String[] split = line.split("\t");
+ sum += Double.parseDouble(split[1]);
+ }
+ }
+ System.out.println(sum);
+ assertTrue("Sum was: " + sum, sum > 0.9 && sum < 1.1);
+ }
+
+ private void generateTestData() {
+ try {
+ SequenceFile.Writer writer1 = SequenceFile.createWriter(fs, conf,
+ new Path(INPUT + "/part0"), Text.class, TextArrayWritable.class);
+
+ for (int i = 0; i < input.length; i++) {
+ String[] x = input[i].split("\t");
+
+ Text vertex = new Text(x[0]);
+ TextArrayWritable arr = new TextArrayWritable();
+ Writable[] values = new Writable[x.length - 1];
+ for (int j = 1; j < x.length; j++) {
+ values[j - 1] = new Text(x[j]);
+ }
+ arr.set(values);
+ writer1.append(vertex, arr);
+ }
+
+ writer1.close();
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void deleteTempDirs() {
+ try {
+ if (fs.exists(new Path(INPUT)))
+ fs.delete(new Path(INPUT), true);
+ if (fs.exists(new Path(OUTPUT)))
+ fs.delete(new Path(OUTPUT), true);
+ if (fs.exists(new Path(TEXT_INPUT)))
+ fs.delete(new Path(TEXT_INPUT), true);
+ if (fs.exists(new Path(TEXT_OUTPUT)))
+ fs.delete(new Path(TEXT_OUTPUT), true);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/examples/src/test/java/org/apache/hama/examples/SSSPTest.java b/examples/src/test/java/org/apache/hama/examples/SSSPTest.java
index 75ca88a67..3d7f03f18 100644
--- a/examples/src/test/java/org/apache/hama/examples/SSSPTest.java
+++ b/examples/src/test/java/org/apache/hama/examples/SSSPTest.java
@@ -32,14 +32,23 @@
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hama.HamaConfiguration;
+import org.junit.Test;
/**
* Testcase for {@link ShortestPaths}
*/
public class SSSPTest extends TestCase {
- String[] input = new String[] { "1:85\t2:217\t4:173", "0:85\t5:80",
- "0:217\t6:186\t7:103", "7:183", "0:173\t9:502", "1:80\t8:250", "2:186",
- "3:183\t9:167\t2:103", "5:250\t9:84", "4:502\t7:167\t8:84" };
+ String[] input = new String[] { "1:85\t2:217\t4:173",// 0
+ "0:85\t5:80",// 1
+ "0:217\t6:186\t7:103",// 2
+ "7:183",// 3
+ "0:173\t9:502", // 4
+ "1:80\t8:250", // 5
+ "2:186", // 6
+ "3:183\t9:167\t2:103", // 7
+ "5:250\t9:84", // 8
+ "4:502\t7:167\t8:84" // 9
+ };
private static String INPUT = "/tmp/sssp-tmp.seq";
private static String TEXT_INPUT = "/tmp/sssp.txt";
@@ -54,6 +63,7 @@ protected void setUp() throws Exception {
fs = FileSystem.get(conf);
}
+ @Test
public void testShortestPaths() throws IOException, InterruptedException,
ClassNotFoundException, InstantiationException, IllegalAccessException {
diff --git a/graph/src/main/java/org/apache/hama/graph/AggregationRunner.java b/graph/src/main/java/org/apache/hama/graph/AggregationRunner.java
index 53e70e806..17f89c08c 100644
--- a/graph/src/main/java/org/apache/hama/graph/AggregationRunner.java
+++ b/graph/src/main/java/org/apache/hama/graph/AggregationRunner.java
@@ -36,7 +36,7 @@
* configured.
*
*/
-public final class AggregationRunner<V extends WritableComparable<V>, E extends Writable, M extends Writable> {
+public final class AggregationRunner<V extends WritableComparable<? super V>, E extends Writable, M extends Writable> {
// multiple aggregator arrays
private Aggregator<M, Vertex<V, E, M>>[] aggregators;
@@ -166,31 +166,23 @@ public void doMasterAggregation(MapWritable updatedCnt) {
}
/**
- * Receives aggregated values from a master task, by doing an additional
- * barrier sync and parsing the messages.
+ * Receives aggregated values from a master task.
*
* @return always true if no aggregators are defined, false if aggregators say
* we haven't seen any messages anymore.
*/
- public boolean receiveAggregatedValues(
- BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer,
+ public boolean receiveAggregatedValues(MapWritable updatedValues,
long iteration) throws IOException, SyncException, InterruptedException {
- // if we have an aggregator defined, we must make an additional sync
- // to have the updated values available on all our peers.
- if (isEnabled() && iteration > 1) {
- peer.sync();
-
- MapWritable updatedValues = peer.getCurrentMessage().getMap();
- for (int i = 0; i < aggregators.length; i++) {
- globalAggregatorResult[i] = updatedValues.get(aggregatorValueFlag[i]);
- globalAggregatorIncrement[i] = (IntWritable) updatedValues
- .get(aggregatorIncrementFlag[i]);
- }
- IntWritable count = (IntWritable) updatedValues
- .get(GraphJobRunner.FLAG_MESSAGE_COUNTS);
- if (count != null && count.get() == Integer.MIN_VALUE) {
- return false;
- }
+ // map is the first value that is in the queue
+ for (int i = 0; i < aggregators.length; i++) {
+ globalAggregatorResult[i] = updatedValues.get(aggregatorValueFlag[i]);
+ globalAggregatorIncrement[i] = (IntWritable) updatedValues
+ .get(aggregatorIncrementFlag[i]);
+ }
+ IntWritable count = (IntWritable) updatedValues
+ .get(GraphJobRunner.FLAG_MESSAGE_COUNTS);
+ if (count != null && count.get() == Integer.MIN_VALUE) {
+ return false;
}
return true;
}
diff --git a/graph/src/main/java/org/apache/hama/graph/DiskVerticesInfo.java b/graph/src/main/java/org/apache/hama/graph/DiskVerticesInfo.java
new file mode 100644
index 000000000..4f4251ae8
--- /dev/null
+++ b/graph/src/main/java/org/apache/hama/graph/DiskVerticesInfo.java
@@ -0,0 +1,359 @@
+/**
+ * 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.hama.graph;
+
+import static com.google.common.base.Preconditions.checkArgument;
+
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.Collections;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.LocalFileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.IOUtils;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.WritableComparable;
+import org.apache.hama.bsp.TaskAttemptID;
+import org.apache.hama.graph.IDSkippingIterator.Strategy;
+
+public final class DiskVerticesInfo<V extends WritableComparable<? super V>, E extends Writable, M extends Writable>
+ implements VerticesInfo<V, E, M> {
+
+ public static final String DISK_VERTICES_PATH_KEY = "hama.disk.vertices.path";
+
+ private static final byte NULL = 0;
+ private static final byte NOT_NULL = 1;
+
+ private RandomAccessFile staticGraphParts;
+ private RandomAccessFile softGraphParts;
+ private RandomAccessFile softGraphPartsNextIteration;
+
+ private BitSet activeVertices;
+ private long[] softValueOffsets;
+ private long[] softValueOffsetsNextIteration;
+ private long[] staticOffsets;
+
+ private ArrayList<Long> tmpSoftOffsets;
+ private ArrayList<Long> tmpStaticOffsets;
+
+ private int size;
+ private boolean lockedAdditions = false;
+ private String rootPath;
+ private Vertex<V, E, M> cachedVertexInstance;
+ private int currentStep = 0;
+ private int index = 0;
+ private Configuration conf;
+ private GraphJobRunner<V, E, M> runner;
+
+ @Override
+ public void init(GraphJobRunner<V, E, M> runner, Configuration conf,
+ TaskAttemptID attempt) throws IOException {
+ this.runner = runner;
+ this.conf = conf;
+ tmpSoftOffsets = new ArrayList<Long>();
+ tmpStaticOffsets = new ArrayList<Long>();
+ String p = conf.get(DISK_VERTICES_PATH_KEY, "/tmp/graph/");
+ rootPath = p + attempt.getJobID().toString() + "/" + attempt.toString()
+ + "/";
+ LocalFileSystem local = FileSystem.getLocal(conf);
+ local.mkdirs(new Path(rootPath));
+ // make sure that those files do not exist
+ String staticFile = rootPath + "static.graph";
+ local.delete(new Path(staticFile), false);
+ staticGraphParts = new RandomAccessFile(staticFile, "rw");
+ String softGraphFileName = getSoftGraphFileName(rootPath, currentStep);
+ local.delete(new Path(softGraphFileName), false);
+ softGraphParts = new RandomAccessFile(softGraphFileName, "rw");
+ }
+
+ @Override
+ public void cleanup(Configuration conf, TaskAttemptID attempt)
+ throws IOException {
+ IOUtils.cleanup(null, softGraphParts, softGraphPartsNextIteration);
+ // delete the contents
+ FileSystem.getLocal(conf).delete(new Path(rootPath), true);
+ }
+
+ @Override
+ public void addVertex(Vertex<V, E, M> vertex) throws IOException {
+ // messages must be added in sorted order to work this out correctly
+ checkArgument(!lockedAdditions,
+ "Additions are locked now, nobody is allowed to change the structure anymore.");
+
+ // write the static parts
+ tmpStaticOffsets.add(staticGraphParts.length());
+ vertex.getVertexID().write(staticGraphParts);
+ staticGraphParts.writeInt(vertex.getEdges() == null ? 0 : vertex.getEdges()
+ .size());
+ for (Edge<?, ?> e : vertex.getEdges()) {
+ e.getDestinationVertexID().write(staticGraphParts);
+ }
+
+ serializeSoft(vertex, -1, null, softGraphParts);
+
+ size++;
+ }
+
+ /**
+ * Serializes the vertex's soft parts to its file. If the vertex does not have
+ * an index yet (e.G. at startup) you can provide -1 and it will be added to
+ * the temporary storage.
+ */
+ private void serializeSoft(Vertex<V, E, M> vertex, int index,
+ long[] softValueOffsets, RandomAccessFile softGraphParts)
+ throws IOException {
+ // safe offset write the soft parts
+ if (index >= 0) {
+ softValueOffsets[index] = softGraphParts.length();
+ // only set the bitset if we've finished the setup
+ activeVertices.set(index, vertex.isHalted());
+ } else {
+ tmpSoftOffsets.add(softGraphParts.length());
+ }
+ if (vertex.getValue() == null) {
+ softGraphParts.write(NULL);
+ } else {
+ softGraphParts.write(NOT_NULL);
+ vertex.getValue().write(softGraphParts);
+ }
+ vertex.writeState(softGraphParts);
+ softGraphParts.writeInt(vertex.getEdges().size());
+ for (Edge<?, ?> e : vertex.getEdges()) {
+ if (e.getValue() == null) {
+ softGraphParts.write(NULL);
+ } else {
+ softGraphParts.write(NOT_NULL);
+ e.getValue().write(softGraphParts);
+ }
+ }
+ }
+
+ @Override
+ public void finishAdditions() {
+ // copy the arraylist to a plain array
+ softValueOffsets = copy(tmpSoftOffsets);
+ softValueOffsetsNextIteration = copy(tmpSoftOffsets);
+ staticOffsets = copy(tmpStaticOffsets);
+ activeVertices = new BitSet(size);
+
+ tmpStaticOffsets = null;
+ tmpSoftOffsets = null;
+
+ // prevent additional vertices from beeing added
+ lockedAdditions = true;
+ }
+
+ private static long[] copy(ArrayList<Long> lst) {
+ long[] arr = new long[lst.size()];
+ for (int i = 0; i < arr.length; i++) {
+ arr[i] = lst.get(i);
+ }
+ return arr;
+ }
+
+ @Override
+ public boolean isFinishedAdditions() {
+ return lockedAdditions;
+ }
+
+ @Override
+ public void startSuperstep() throws IOException {
+ index = 0;
+ String softGraphFileName = getSoftGraphFileName(rootPath, currentStep);
+ FileSystem.getLocal(conf).delete(new Path(softGraphFileName), true);
+ softGraphPartsNextIteration = new RandomAccessFile(softGraphFileName, "rw");
+ softValueOffsets = softValueOffsetsNextIteration;
+ softValueOffsetsNextIteration = new long[softValueOffsetsNextIteration.length];
+ }
+
+ @Override
+ public void finishVertexComputation(Vertex<V, E, M> vertex)
+ throws IOException {
+ // write to the soft parts
+ serializeSoft(vertex, index++, softValueOffsetsNextIteration,
+ softGraphPartsNextIteration);
+ }
+
+ @Override
+ public void finishSuperstep() throws IOException {
+ // do not delete files in the first step
+ if (currentStep > 0) {
+ softGraphParts.close();
+ FileSystem.getLocal(conf).delete(
+ new Path(getSoftGraphFileName(rootPath, currentStep - 1)), true);
+ softGraphParts = softGraphPartsNextIteration;
+ }
+ currentStep++;
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ private final class IDSkippingDiskIterator extends
+ IDSkippingIterator<V, E, M> {
+
+ int currentIndex = 0;
+
+ @Override
+ public Vertex<V, E, M> next() {
+ return cachedVertexInstance;
+ }
+
+ @Override
+ public boolean hasNext(V e,
+ org.apache.hama.graph.IDSkippingIterator.Strategy strat) {
+ if (currentIndex >= size) {
+ return false;
+ } else {
+ currentIndex = fill(strat, currentIndex, e);
+ return true;
+ }
+ }
+
+ }
+
+ @Override
+ public IDSkippingIterator<V, E, M> skippingIterator() {
+ try {
+ // reset
+ staticGraphParts.seek(0);
+ softGraphParts.seek(0);
+ // ensure the vertex is not null
+ if (cachedVertexInstance == null) {
+ cachedVertexInstance = GraphJobRunner
+ .<V, E, M> newVertexInstance(GraphJobRunner.VERTEX_CLASS);
+ cachedVertexInstance.runner = runner;
+ }
+ ensureVertexIDNotNull();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return new IDSkippingDiskIterator();
+ }
+
+ @SuppressWarnings("unchecked")
+ private void ensureVertexIDNotNull() {
+ if (cachedVertexInstance.getVertexID() == null) {
+ cachedVertexInstance.setVertexID((V) GraphJobRunner
+ .createVertexIDObject());
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void ensureVertexValueNotNull() {
+ if (cachedVertexInstance.getValue() == null) {
+ cachedVertexInstance.setValue((M) GraphJobRunner.createVertexValue());
+ }
+ }
+
+ @SuppressWarnings({ "unchecked", "static-method" })
+ private void ensureEdgeIDNotNull(Edge<V, E> edge) {
+ if (edge.getDestinationVertexID() == null) {
+ edge.setDestinationVertexID((V) GraphJobRunner.createVertexIDObject());
+ }
+ }
+
+ @SuppressWarnings({ "unchecked", "static-method" })
+ private void ensureEdgeValueNotNull(Edge<V, E> edge) {
+ if (edge.getValue() == null) {
+ edge.setCost((E) GraphJobRunner.createEdgeCostObject());
+ }
+ }
+
+ /**
+ * Fills the cachedVertexInstance with the next acceptable item after the
+ * given index that matches the given messageVertexID if provided.
+ *
+ * @param strat the strategy that defines if a vertex that is serialized
+ * should be accepted.
+ * @param index the index of the vertices to start from.
+ * @param messageVertexId the message vertex id that can be matched by the
+ * strategy. Can be null as well, this is handled by the strategy.
+ * @return the index of the item after the currently found item.
+ */
+ private int fill(Strategy strat, int index, V messageVertexId) {
+ try {
+ while (true) {
+ // seek until we found something that satisfied our strategy
+ staticGraphParts.seek(staticOffsets[index]);
+ boolean halted = activeVertices.get(index);
+ cachedVertexInstance.setVotedToHalt(halted);
+ cachedVertexInstance.getVertexID().readFields(staticGraphParts);
+ if (strat.accept(cachedVertexInstance, messageVertexId)) {
+ break;
+ }
+ if (++index >= size) {
+ return size;
+ }
+ }
+ softGraphParts.seek(softValueOffsets[index]);
+
+ // setting vertex value null here, because it may be overridden. Messaging
+ // is not materializing the message directly- so it is possible for the
+ // read fields method to change this object (thus a new object).
+ cachedVertexInstance.setValue(null);
+ if (softGraphParts.readByte() == NOT_NULL) {
+ ensureVertexValueNotNull();
+ cachedVertexInstance.getValue().readFields(softGraphParts);
+ }
+
+ cachedVertexInstance.readState(softGraphParts);
+ int numEdges = staticGraphParts.readInt();
+ int softEdges = softGraphParts.readInt();
+ if (softEdges != numEdges) {
+ throw new IllegalArgumentException(
+ "Number of edges seemed to change. This is not possible (yet).");
+ }
+ // edges could actually be cached, however the local mode is preventing it
+ // sometimes as edge destinations are send and possible overridden in
+ // messages here.
+ ArrayList<Edge<V, E>> edges = new ArrayList<Edge<V, E>>();
+ // read the soft file in parallel
+ for (int i = 0; i < numEdges; i++) {
+ Edge<V, E> edge = new Edge<V, E>();
+ ensureEdgeValueNotNull(edge);
+ ensureEdgeIDNotNull(edge);
+ edge.getDestinationVertexID().readFields(staticGraphParts);
+ if (softGraphParts.readByte() == NOT_NULL) {
+ ensureEdgeValueNotNull(edge);
+ edge.getCost().readFields(softGraphParts);
+ } else {
+ edge.setCost(null);
+ }
+ edges.add(edge);
+ }
+
+ // make edges unmodifiable
+ cachedVertexInstance.setEdges(Collections.unmodifiableList(edges));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return index + 1;
+ }
+
+ private static String getSoftGraphFileName(String root, int step) {
+ return root + "soft_" + step + ".graph";
+ }
+
+}
diff --git a/graph/src/main/java/org/apache/hama/graph/Edge.java b/graph/src/main/java/org/apache/hama/graph/Edge.java
index c90a38cfe..ba2b7e60b 100644
--- a/graph/src/main/java/org/apache/hama/graph/Edge.java
+++ b/graph/src/main/java/org/apache/hama/graph/Edge.java
@@ -25,8 +25,12 @@
* The edge class
*/
public final class Edge<VERTEX_ID extends WritableComparable<? super VERTEX_ID>, EDGE_VALUE_TYPE extends Writable> {
- private final VERTEX_ID destinationVertexID;
- private final EDGE_VALUE_TYPE cost;
+
+ private VERTEX_ID destinationVertexID;
+ private EDGE_VALUE_TYPE cost;
+
+ public Edge() {
+ }
public Edge(VERTEX_ID sourceVertexID, EDGE_VALUE_TYPE cost) {
this.destinationVertexID = sourceVertexID;
@@ -45,6 +49,18 @@ public EDGE_VALUE_TYPE getValue() {
return cost;
}
+ public EDGE_VALUE_TYPE getCost() {
+ return cost;
+ }
+
+ void setCost(EDGE_VALUE_TYPE cost) {
+ this.cost = cost;
+ }
+
+ void setDestinationVertexID(VERTEX_ID destinationVertexID) {
+ this.destinationVertexID = destinationVertexID;
+ }
+
@Override
public String toString() {
return this.destinationVertexID + ":" + this.getValue();
diff --git a/graph/src/main/java/org/apache/hama/graph/GraphJob.java b/graph/src/main/java/org/apache/hama/graph/GraphJob.java
index 6af4943d5..bfe501954 100644
--- a/graph/src/main/java/org/apache/hama/graph/GraphJob.java
+++ b/graph/src/main/java/org/apache/hama/graph/GraphJob.java
@@ -30,6 +30,9 @@
import org.apache.hama.bsp.HashPartitioner;
import org.apache.hama.bsp.Partitioner;
import org.apache.hama.bsp.PartitioningRunner.RecordConverter;
+import org.apache.hama.bsp.message.MessageManager;
+import org.apache.hama.bsp.message.queue.MessageQueue;
+import org.apache.hama.bsp.message.queue.SortedMessageQueue;
import com.google.common.base.Preconditions;
@@ -134,8 +137,8 @@ public void setVertexInputReaderClass(
}
@Override
- public void setPartitioner(@SuppressWarnings("rawtypes")
- Class<? extends Partitioner> theClass) {
+ public void setPartitioner(
+ @SuppressWarnings("rawtypes") Class<? extends Partitioner> theClass) {
super.setPartitioner(theClass);
conf.setBoolean(Constants.ENABLE_RUNTIME_PARTITIONING, true);
}
@@ -177,6 +180,10 @@ public void submit() throws IOException, InterruptedException {
Constants.RUNTIME_PARTITION_RECORDCONVERTER) != null,
"Please provide a converter class for your vertex by using GraphJob#setVertexInputReaderClass!");
+ // add the default message queue to the sorted one
+ this.getConfiguration().setClass(MessageManager.QUEUE_TYPE_CLASS,
+ SortedMessageQueue.class, MessageQueue.class);
+
super.submit();
}
diff --git a/graph/src/main/java/org/apache/hama/graph/GraphJobMessage.java b/graph/src/main/java/org/apache/hama/graph/GraphJobMessage.java
index b9a41b52d..073313767 100644
--- a/graph/src/main/java/org/apache/hama/graph/GraphJobMessage.java
+++ b/graph/src/main/java/org/apache/hama/graph/GraphJobMessage.java
@@ -20,8 +20,6 @@
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.MapWritable;
@@ -34,21 +32,20 @@
* real message (vertex ID and value). It can be extended by adding flags, for
* example for a graph repair call.
*/
-public final class GraphJobMessage implements Writable {
+public final class GraphJobMessage implements
+ WritableComparable<GraphJobMessage> {
public static final int MAP_FLAG = 0x01;
public static final int VERTEX_FLAG = 0x02;
- public static final int REPAIR_FLAG = 0x04;
- public static final int PARTITION_FLAG = 0x08;
- public static final int VERTICES_SIZE_FLAG = 0x10;
+ public static final int VERTICES_SIZE_FLAG = 0x04;
// default flag to -1 "unknown"
private int flag = -1;
private MapWritable map;
- private Writable vertexId;
+ @SuppressWarnings("rawtypes")
+ private WritableComparable vertexId;
private Writable vertexValue;
- private Vertex<?, ?, ?> vertex;
- private IntWritable vertices_size;
+ private IntWritable verticesSize;
public GraphJobMessage() {
}
@@ -58,25 +55,15 @@ public GraphJobMessage(MapWritable map) {
this.map = map;
}
- public GraphJobMessage(Writable vertexId) {
- this.flag = REPAIR_FLAG;
- this.vertexId = vertexId;
- }
-
- public GraphJobMessage(Writable vertexId, Writable vertexValue) {
+ public GraphJobMessage(WritableComparable<?> vertexId, Writable vertexValue) {
this.flag = VERTEX_FLAG;
this.vertexId = vertexId;
this.vertexValue = vertexValue;
}
- public GraphJobMessage(Vertex<?, ?, ?> vertex) {
- this.flag = PARTITION_FLAG;
- this.vertex = vertex;
- }
-
public GraphJobMessage(IntWritable size) {
this.flag = VERTICES_SIZE_FLAG;
- this.vertices_size = size;
+ this.verticesSize = size;
}
@Override
@@ -89,28 +76,8 @@ public void write(DataOutput out) throws IOException {
vertexValue.write(out);
} else if (isMapMessage()) {
map.write(out);
- } else if (isPartitioningMessage()) {
- vertex.getVertexID().write(out);
- if (vertex.getValue() != null) {
- out.writeBoolean(true);
- vertex.getValue().write(out);
- } else {
- out.writeBoolean(false);
- }
- List<?> outEdges = vertex.getEdges();
- out.writeInt(outEdges.size());
- for (Object e : outEdges) {
- Edge<?, ?> edge = (Edge<?, ?>) e;
- edge.getDestinationVertexID().write(out);
- if (edge.getValue() != null) {
- out.writeBoolean(true);
- edge.getValue().write(out);
- } else {
- out.writeBoolean(false);
- }
- }
} else if (isVerticesSizeMessage()) {
- vertices_size.write(out);
+ verticesSize.write(out);
} else {
vertexId.write(out);
}
@@ -128,39 +95,9 @@ public void readFields(DataInput in) throws IOException {
} else if (isMapMessage()) {
map = new MapWritable();
map.readFields(in);
- } else if (isPartitioningMessage()) {
- Vertex<WritableComparable<Writable>, Writable, Writable> vertex = GraphJobRunner
- .newVertexInstance(GraphJobRunner.VERTEX_CLASS);
- WritableComparable<Writable> vertexId = GraphJobRunner
- .createVertexIDObject();
- vertexId.readFields(in);
- vertex.setVertexID(vertexId);
- if (in.readBoolean()) {
- Writable vertexValue = GraphJobRunner.createVertexValue();
- vertexValue.readFields(in);
- vertex.setValue(vertexValue);
- }
- int size = in.readInt();
- vertex
- .setEdges(new ArrayList<Edge<WritableComparable<Writable>, Writable>>(
- size));
- for (int i = 0; i < size; i++) {
- WritableComparable<Writable> edgeVertexID = GraphJobRunner
- .createVertexIDObject();
- edgeVertexID.readFields(in);
- Writable edgeValue = null;
- if (in.readBoolean()) {
- edgeValue = GraphJobRunner.createEdgeCostObject();
- edgeValue.readFields(in);
- }
- vertex.getEdges().add(
- new Edge<WritableComparable<Writable>, Writable>(edgeVertexID,
- edgeValue));
- }
- this.vertex = vertex;
} else if (isVerticesSizeMessage()) {
- vertices_size = new IntWritable();
- vertices_size.readFields(in);
+ verticesSize = new IntWritable();
+ verticesSize.readFields(in);
} else {
vertexId = ReflectionUtils.newInstance(GraphJobRunner.VERTEX_ID_CLASS,
null);
@@ -168,6 +105,21 @@ public void readFields(DataInput in) throws IOException {
}
}
+ @SuppressWarnings("unchecked")
+ @Override
+ public int compareTo(GraphJobMessage that) {
+ if (this.flag != that.flag) {
+ return (this.flag - that.flag);
+ } else {
+ if (this.isVertexMessage()) {
+ return this.vertexId.compareTo(that.vertexId);
+ } else if (this.isMapMessage()) {
+ return Integer.MIN_VALUE;
+ }
+ }
+ return 0;
+ }
+
public MapWritable getMap() {
return map;
}
@@ -180,12 +132,8 @@ public Writable getVertexValue() {
return vertexValue;
}
- public Vertex<?, ?, ?> getVertex() {
- return vertex;
- }
-
public IntWritable getVerticesSize() {
- return vertices_size;
+ return verticesSize;
}
public boolean isMapMessage() {
@@ -196,23 +144,22 @@ public boolean isVertexMessage() {
return flag == VERTEX_FLAG;
}
- public boolean isRepairMessage() {
- return flag == REPAIR_FLAG;
- }
-
- public boolean isPartitioningMessage() {
- return flag == PARTITION_FLAG;
- }
-
public boolean isVerticesSizeMessage() {
return flag == VERTICES_SIZE_FLAG;
}
@Override
public String toString() {
- return "GraphJobMessage [flag=" + flag + ", map=" + map + ", vertexId="
- + vertexId + ", vertexValue=" + vertexValue + ", vertex=" + vertex
- + "]";
+ if (isVertexMessage()) {
+ return "ID: " + vertexId + " Val: " + vertexValue;
+ } else if (isMapMessage()) {
+ return "Map: " + map;
+ } else if (isVerticesSizeMessage()) {
+ return "#Vertices: " + verticesSize;
+ } else {
+ return "GraphJobMessage [flag=" + flag + ", map=" + map + ", vertexId="
+ + vertexId + ", vertexValue=" + vertexValue + "]";
+ }
}
}
diff --git a/graph/src/main/java/org/apache/hama/graph/GraphJobRunner.java b/graph/src/main/java/org/apache/hama/graph/GraphJobRunner.java
index a2b07a109..c6c3130b0 100644
--- a/graph/src/main/java/org/apache/hama/graph/GraphJobRunner.java
+++ b/graph/src/main/java/org/apache/hama/graph/GraphJobRunner.java
@@ -18,11 +18,7 @@
package org.apache.hama.graph;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
@@ -30,6 +26,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.MapWritable;
+import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
@@ -39,7 +36,7 @@
import org.apache.hama.bsp.HashPartitioner;
import org.apache.hama.bsp.Partitioner;
import org.apache.hama.bsp.sync.SyncException;
-import org.apache.hama.util.KeyValuePair;
+import org.apache.hama.graph.IDSkippingIterator.Strategy;
import org.apache.hama.util.ReflectionUtils;
/**
@@ -49,7 +46,7 @@
* @param <E> the value type of an edge.
* @param <M> the value type of a vertex.
*/
-public final class GraphJobRunner<V extends WritableComparable<V>, E extends Writable, M extends Writable>
+public final class GraphJobRunner<V extends WritableComparable<? super V>, E extends Writable, M extends Writable>
extends BSP<Writable, Writable, Writable, Writable, GraphJobMessage> {
public static enum GraphJobCounter {
@@ -77,7 +74,7 @@ public static enum GraphJobCounter {
public static Class<? extends Writable> EDGE_VALUE_CLASS;
public static Class<Vertex<?, ?, ?>> vertexClass;
- private IVerticesInfo<V, E, M> vertices;
+ private VerticesInfo<V, E, M> vertices;
private boolean updated = true;
private int globalUpdateCounts = 0;
@@ -119,15 +116,16 @@ public final void bsp(
peer.sync();
// note that the messages must be parsed here
- final Map<V, List<M>> messages = parseMessages(peer);
- // master needs to update
- doMasterUpdates(peer);
- // if aggregators say we don't have updates anymore, break
- if (!aggregationRunner.receiveAggregatedValues(peer, iteration)) {
+ GraphJobMessage firstVertexMessage = parseMessages(peer);
+ // master/slaves needs to update
+ firstVertexMessage = doAggregationUpdates(firstVertexMessage, peer);
+ // check if updated changed by our aggregators
+ if (!updated) {
break;
}
+
// loop over vertices and do their computation
- doSuperstep(messages, peer);
+ doSuperstep(firstVertexMessage, peer);
if (isMasterTask(peer)) {
peer.getCounter(GraphJobCounter.ITERATIONS).increment(1);
@@ -144,9 +142,12 @@ public final void bsp(
public final void cleanup(
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
throws IOException {
- for (Vertex<V, E, M> e : vertices) {
+ IDSkippingIterator<V, E, M> skippingIterator = vertices.skippingIterator();
+ while (skippingIterator.hasNext()) {
+ Vertex<V, E, M> e = skippingIterator.next();
peer.write(e.getVertexID(), e.getValue());
}
+ vertices.cleanup(conf, peer.getTaskId());
}
/**
@@ -154,9 +155,12 @@ public final void cleanup(
* master aggregation. In case of no aggregators defined, we save a sync by
* reading multiple typed messages.
*/
- private void doMasterUpdates(
+ private GraphJobMessage doAggregationUpdates(
+ GraphJobMessage firstVertexMessage,
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
- throws IOException {
+ throws IOException, SyncException, InterruptedException {
+
+ // this is only done in every second iteration
if (isMasterTask(peer) && iteration > 1) {
MapWritable updatedCnt = new MapWritable();
// exit if there's no update made
@@ -165,50 +169,125 @@ private void doMasterUpdates(
} else {
aggregationRunner.doMasterAggregation(updatedCnt);
}
- // send the updates from the mater tasks back to the slaves
+ // send the updates from the master tasks back to the slaves
for (String peerName : peer.getAllPeerNames()) {
peer.send(peerName, new GraphJobMessage(updatedCnt));
}
}
+ if (aggregationRunner.isEnabled() && iteration > 1) {
+ // in case we need to sync, we need to replay the messages that already
+ // are added to the queue. This prevents loosing messages when using
+ // aggregators.
+ if (firstVertexMessage != null) {
+ peer.send(peer.getPeerName(), firstVertexMessage);
+ }
+ GraphJobMessage msg = null;
+ while ((msg = peer.getCurrentMessage()) != null) {
+ peer.send(peer.getPeerName(), msg);
+ }
+ // now sync
+ peer.sync();
+ // now the map message must be read that might be send from the master
+ updated = aggregationRunner.receiveAggregatedValues(peer
+ .getCurrentMessage().getMap(), iteration);
+ // set the first vertex message back to the message it had before sync
+ firstVertexMessage = peer.getCurrentMessage();
+ }
+ return firstVertexMessage;
}
/**
* Do the main logic of a superstep, namely checking if vertices are active,
* feeding compute with messages and controlling combiners/aggregators.
*/
- private void doSuperstep(Map<V, List<M>> messages,
+ @SuppressWarnings("unchecked")
+ private void doSuperstep(GraphJobMessage currentMessage,
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
throws IOException {
int activeVertices = 0;
- for (Vertex<V, E, M> vertex : vertices) {
- List<M> msgs = messages.get(vertex.getVertexID());
- // If there are newly received messages, restart.
- if (vertex.isHalted() && msgs != null) {
- vertex.setActive();
+ vertices.startSuperstep();
+ /*
+ * We iterate over our messages and vertices in sorted order. That means
+ * that we need to seek the first vertex that has the same ID as the
+ * currentMessage or the first vertex that is active.
+ */
+ IDSkippingIterator<V, E, M> iterator = vertices.skippingIterator();
+ // note that can't skip inactive vertices because we have to rewrite the
+ // complete vertex file in each iteration
+ while (iterator.hasNext(
+ currentMessage == null ? null : (V) currentMessage.getVertexId(),
+ Strategy.ALL)) {
+
+ Vertex<V, E, M> vertex = iterator.next();
+ VertexMessageIterable<V, M> iterable = null;
+ if (currentMessage != null) {
+ iterable = iterate(currentMessage, (V) currentMessage.getVertexId(),
+ vertex, peer);
}
- if (msgs == null) {
- msgs = Collections.emptyList();
+ if (iterable != null && vertex.isHalted()) {
+ vertex.setActive();
}
-
if (!vertex.isHalted()) {
- if (combiner != null) {
- M combined = combiner.combine(msgs);
- msgs = new ArrayList<M>();
- msgs.add(combined);
- }
M lastValue = vertex.getValue();
- vertex.compute(msgs.iterator());
+ if (iterable == null) {
+ vertex.compute(Collections.<M> emptyList());
+ } else {
+ if (combiner != null) {
+ M combined = combiner.combine(iterable);
+ vertex.compute(Collections.singleton(combined));
+ } else {
+ vertex.compute(iterable);
+ }
+ currentMessage = iterable.getOverflowMessage();
+ }
aggregationRunner.aggregateVertex(lastValue, vertex);
+ // check for halt again after computation
if (!vertex.isHalted()) {
activeVertices++;
}
}
+
+ // note that we even need to rewrite the vertex if it is halted for
+ // consistency reasons
+ vertices.finishVertexComputation(vertex);
}
+ vertices.finishSuperstep();
aggregationRunner.sendAggregatorValues(peer, activeVertices);
iteration++;
}
+ /**
+ * Iterating utility that ensures following things: <br/>
+ * - if vertex is active, but the given message does not match the vertexID,
+ * return null. <br/>
+ * - if vertex is inactive, but received a message that matches the ID, build
+ * an iterator that can be iterated until the next vertex has been reached
+ * (not buffer in memory) and set the vertex active <br/>
+ * - if vertex is active, and the given message does match the vertexID,
+ * return an iterator that can be iterated until the next vertex has been
+ * reached. <br/>
+ * - if vertex is inactive, and received no message, return null.
+ */
+ private VertexMessageIterable<V, M> iterate(GraphJobMessage currentMessage,
+ V firstMessageId, Vertex<V, E, M> vertex,
+ BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer) {
+ int comparision = firstMessageId.compareTo(vertex.getVertexID());
+ if (comparision < 0) {
+ throw new IllegalArgumentException(
+ "Messages must never be behind the vertex in ID! Current Message ID: "
+ + firstMessageId + " vs. " + vertex.getVertexID());
+ } else if (comparision == 0) {
+ // vertex id matches with the vertex, return an iterator with newest
+ // message
+ return new VertexMessageIterable<V, M>(currentMessage,
+ vertex.getVertexID(), peer);
+ } else {
+ // return null
+ return null;
+ }
+ }
+
/**
* Seed the vertices first with their own values in compute. This is the first
* superstep after the vertices have been loaded.
@@ -216,19 +295,24 @@ private void doSuperstep(Map<V, List<M>> messages,
private void doInitialSuperstep(
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
throws IOException {
- for (Vertex<V, E, M> vertex : vertices) {
- List<M> singletonList = Collections.singletonList(vertex.getValue());
+ vertices.startSuperstep();
+ IDSkippingIterator<V, E, M> skippingIterator = vertices.skippingIterator();
+ while (skippingIterator.hasNext()) {
+ Vertex<V, E, M> vertex = skippingIterator.next();
M lastValue = vertex.getValue();
- vertex.compute(singletonList.iterator());
+ vertex.compute(Collections.singleton(vertex.getValue()));
aggregationRunner.aggregateVertex(lastValue, vertex);
+ vertices.finishVertexComputation(vertex);
}
+ vertices.finishSuperstep();
aggregationRunner.sendAggregatorValues(peer, 1);
iteration++;
}
@SuppressWarnings("unchecked")
private void setupFields(
- BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer) {
+ BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
+ throws IOException {
this.peer = peer;
this.conf = peer.getConfiguration();
maxIteration = peer.getConfiguration().getInt("hama.graph.max.iteration",
@@ -253,7 +337,8 @@ private void setupFields(
aggregationRunner = new AggregationRunner<V, E, M>();
aggregationRunner.setupAggregators(peer);
- vertices = new ListVerticesInfo<V, E, M>();
+ vertices = new DiskVerticesInfo<V, E, M>();
+ vertices.init(this, conf, peer.getTaskId());
}
@SuppressWarnings("unchecked")
@@ -279,33 +364,31 @@ public static <V extends WritableComparable<? super V>, E extends Writable, M ex
/**
* Loads vertices into memory of each peer.
*/
- @SuppressWarnings("unchecked")
private void loadVertices(
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
throws IOException, SyncException, InterruptedException {
final boolean selfReference = conf.getBoolean("hama.graph.self.ref", false);
- if (LOG.isDebugEnabled())
- LOG.debug("Vertex class: " + vertexClass);
+ LOG.debug("Vertex class: " + vertexClass);
- KeyValuePair<Writable, Writable> next;
- // our VertexInputReader ensures that the incoming vertices are sorted by
- // ID.
- while ((next = peer.readNext()) != null) {
- Vertex<V, E, M> vertex = (Vertex<V, E, M>) next.getKey();
- vertex.runner = this;
+ // our VertexInputReader ensures incoming vertices are sorted by their ID
+ Vertex<V, E, M> vertex = GraphJobRunner
+ .<V, E, M> newVertexInstance(VERTEX_CLASS);
+ vertex.runner = this;
+ while (peer.readNext(vertex, NullWritable.get())) {
vertex.setup(conf);
if (selfReference) {
vertex.addEdge(new Edge<V, E>(vertex.getVertexID(), null));
}
vertices.addVertex(vertex);
}
+ vertices.finishAdditions();
+ // finish the "superstep" because we have written a new file here
+ vertices.finishSuperstep();
LOG.info(vertices.size() + " vertices are loaded into "
+ peer.getPeerName());
-
- if (LOG.isDebugEnabled())
- LOG.debug("Starting Vertex processing!");
+ LOG.debug("Starting Vertex processing!");
}
/**
@@ -337,26 +420,21 @@ private void countGlobalVertexCount(
* Parses the messages in every superstep and does actions according to flags
* in the messages.
*
- * @return a map that contains messages pro vertex.
+ * @return the first vertex message, null if none received.
*/
@SuppressWarnings("unchecked")
- private Map<V, List<M>> parseMessages(
+ private GraphJobMessage parseMessages(
BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer)
- throws IOException {
- GraphJobMessage msg;
- final Map<V, List<M>> msgMap = new HashMap<V, List<M>>();
+ throws IOException, SyncException, InterruptedException {
+ GraphJobMessage msg = null;
while ((msg = peer.getCurrentMessage()) != null) {
// either this is a vertex message or a directive that must be read
// as map
if (msg.isVertexMessage()) {
- final V vertexID = (V) msg.getVertexId();
- final M value = (M) msg.getVertexValue();
- List<M> msgs = msgMap.get(vertexID);
- if (msgs == null) {
- msgs = new ArrayList<M>();
- msgMap.put(vertexID, msgs);
- }
- msgs.add(value);
+ // if we found a vertex message (ordering defines they come after map
+ // messages, we return that as the first message so the outward process
+ // can join them correctly with the VerticesInfo.
+ break;
} else if (msg.isMapMessage()) {
for (Entry<Writable, Writable> e : msg.getMap().entrySet()) {
Text vertexID = (Text) e.getKey();
@@ -376,12 +454,13 @@ private Map<V, List<M>> parseMessages(
(M) e.getValue());
}
}
+
} else {
throw new UnsupportedOperationException("Unknown message type: " + msg);
}
}
- return msgMap;
+ return msg;
}
/**
diff --git a/graph/src/main/java/org/apache/hama/graph/IDSkippingIterator.java b/graph/src/main/java/org/apache/hama/graph/IDSkippingIterator.java
new file mode 100644
index 000000000..8e267eb47
--- /dev/null
+++ b/graph/src/main/java/org/apache/hama/graph/IDSkippingIterator.java
@@ -0,0 +1,72 @@
+/**
+ * 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.hama.graph;
+
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.WritableComparable;
+
+/**
+ * Iterator that allows skipping of items on disk based on some given stategy.
+ */
+public abstract class IDSkippingIterator<V extends WritableComparable<? super V>, E extends Writable, M extends Writable> {
+
+ enum Strategy {
+ ALL, ACTIVE, ACTIVE_AND_MESSAGES, INACTIVE;
+
+ // WritableComparable is really sucking in this type constellation
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public boolean accept(Vertex v, WritableComparable msgId) {
+ switch (this) {
+ case ACTIVE_AND_MESSAGES:
+ if (msgId != null) {
+ return !v.isHalted() || v.getVertexID().compareTo(msgId) == 0;
+ }
+ // fallthrough to activeness if we don't have a message anymore
+ case ACTIVE:
+ return !v.isHalted();
+ case INACTIVE:
+ return v.isHalted();
+ case ALL:
+ // fall through intended
+ default:
+ return true;
+ }
+ }
+ }
+
+ /**
+ * Skips nothing, accepts everything.
+ *
+ * @return true if the strategy found a new item, false if not.
+ */
+ public boolean hasNext() {
+ return hasNext(null, Strategy.ALL);
+ }
+
+ /**
+ * Skips until the given strategy is satisfied.
+ *
+ * @return true if the strategy found a new item, false if not.
+ */
+ public abstract boolean hasNext(V e, Strategy strat);
+
+ /**
+ * @return a found vertex that can be read safely.
+ */
+ public abstract Vertex<V, E, M> next();
+}
diff --git a/graph/src/main/java/org/apache/hama/graph/IVerticesInfo.java b/graph/src/main/java/org/apache/hama/graph/IVerticesInfo.java
deleted file mode 100644
index 68c0b53d1..000000000
--- a/graph/src/main/java/org/apache/hama/graph/IVerticesInfo.java
+++ /dev/null
@@ -1,56 +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.hama.graph;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.util.Iterator;
-
-import org.apache.hadoop.io.Writable;
-import org.apache.hadoop.io.WritableComparable;
-
-/**
- * VerticesInfo interface encapsulates the storage of vertices in a BSP Task.
- *
- * @param <V> Vertex ID object type
- * @param <E> Edge cost object type
- * @param <M> Vertex value object type
- */
-public interface IVerticesInfo<V extends WritableComparable<V>, E extends Writable, M extends Writable>
- extends Iterable<Vertex<V, E, M>> {
-
- /**
- * Add a vertex to the underlying structure.
- */
- public void addVertex(Vertex<V, E, M> vertex);
-
- /**
- * @return the number of vertices added to the underlying structure.
- * Implementations should take care this is a constant time operation.
- */
- public int size();
-
- @Override
- public Iterator<Vertex<V, E, M>> iterator();
-
- // to be added and documented soon
- public void recoverState(DataInput in);
-
- public void saveState(DataOutput out);
-
-}
diff --git a/graph/src/main/java/org/apache/hama/graph/ListVerticesInfo.java b/graph/src/main/java/org/apache/hama/graph/ListVerticesInfo.java
index cc0524d15..87f9a4470 100644
--- a/graph/src/main/java/org/apache/hama/graph/ListVerticesInfo.java
+++ b/graph/src/main/java/org/apache/hama/graph/ListVerticesInfo.java
@@ -17,14 +17,14 @@
*/
package org.apache.hama.graph;
-import java.io.DataInput;
-import java.io.DataOutput;
+import java.io.IOException;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
+import org.apache.hama.bsp.TaskAttemptID;
/**
* VerticesInfo encapsulates the storage of vertices in a BSP Task.
@@ -34,16 +34,11 @@
* @param <M> Vertex value object type
*/
public final class ListVerticesInfo<V extends WritableComparable<V>, E extends Writable, M extends Writable>
- implements IVerticesInfo<V, E, M> {
+ implements VerticesInfo<V, E, M> {
private final List<Vertex<V, E, M>> vertices = new ArrayList<Vertex<V, E, M>>(
100);
- /*
- * (non-Javadoc)
- * @see
- * org.apache.hama.graph.IVerticesInfo#addVertex(org.apache.hama.graph.Vertex)
- */
@Override
public void addVertex(Vertex<V, E, M> vertex) {
vertices.add(vertex);
@@ -53,39 +48,74 @@ public void clear() {
vertices.clear();
}
- /*
- * (non-Javadoc)
- * @see org.apache.hama.graph.IVerticesInfo#size()
- */
@Override
public int size() {
return this.vertices.size();
}
- /*
- * (non-Javadoc)
- * @see org.apache.hama.graph.IVerticesInfo#iterator()
- */
@Override
- public Iterator<Vertex<V, E, M>> iterator() {
- return vertices.iterator();
+ public IDSkippingIterator<V, E, M> skippingIterator() {
+ return new IDSkippingIterator<V, E, M>() {
+ int currentIndex = 0;
+
+ @Override
+ public boolean hasNext(V e,
+ org.apache.hama.graph.IDSkippingIterator.Strategy strat) {
+ if (currentIndex < vertices.size()) {
+
+ while (!strat.accept(vertices.get(currentIndex), e)) {
+ currentIndex++;
+ }
+
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public Vertex<V, E, M> next() {
+ return vertices.get(currentIndex++);
+ }
+
+ };
}
- /*
- * (non-Javadoc)
- * @see org.apache.hama.graph.IVerticesInfo#recoverState(java.io.DataInput)
- */
@Override
- public void recoverState(DataInput in) {
+ public void finishVertexComputation(Vertex<V, E, M> vertex) {
}
- /*
- * (non-Javadoc)
- * @see org.apache.hama.graph.IVerticesInfo#saveState(java.io.DataOutput)
- */
@Override
- public void saveState(DataOutput out) {
+ public void finishAdditions() {
}
+
+ @Override
+ public boolean isFinishedAdditions() {
+ return false;
+ }
+
+ @Override
+ public void finishSuperstep() {
+
+ }
+
+ @Override
+ public void cleanup(Configuration conf, TaskAttemptID attempt)
+ throws IOException {
+
+ }
+
+ @Override
+ public void startSuperstep() throws IOException {
+
+ }
+
+ @Override
+ public void init(GraphJobRunner<V, E, M> runner, Configuration conf,
+ TaskAttemptID attempt) throws IOException {
+
+ }
+
}
diff --git a/graph/src/main/java/org/apache/hama/graph/Vertex.java b/graph/src/main/java/org/apache/hama/graph/Vertex.java
index 2c0ad3391..301a035c2 100644
--- a/graph/src/main/java/org/apache/hama/graph/Vertex.java
+++ b/graph/src/main/java/org/apache/hama/graph/Vertex.java
@@ -212,6 +212,10 @@ public boolean isHalted() {
return votedToHalt;
}
+ void setVotedToHalt(boolean votedToHalt) {
+ this.votedToHalt = votedToHalt;
+ }
+
@Override
public int hashCode() {
return ((vertexID == null) ? 0 : vertexID.hashCode());
@@ -236,8 +240,8 @@ public boolean equals(Object obj) {
@Override
public String toString() {
- return getVertexID() + (getValue() != null ? " = " + getValue() : "")
- + " // " + edges;
+ return "Active: " + !votedToHalt + " -> ID: " + getVertexID()
+ + (getValue() != null ? " = " + getValue() : "") + " // " + edges;
}
@Override
diff --git a/graph/src/main/java/org/apache/hama/graph/VertexInterface.java b/graph/src/main/java/org/apache/hama/graph/VertexInterface.java
index 9c52da672..5eda1eea0 100644
--- a/graph/src/main/java/org/apache/hama/graph/VertexInterface.java
+++ b/graph/src/main/java/org/apache/hama/graph/VertexInterface.java
@@ -18,7 +18,6 @@
package org.apache.hama.graph;
import java.io.IOException;
-import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
@@ -55,7 +54,7 @@ public interface VertexInterface<V extends WritableComparable<? super V>, E exte
/**
* The user-defined function
*/
- public void compute(Iterator<M> messages) throws IOException;
+ public void compute(Iterable<M> messages) throws IOException;
/**
* @return a list of outgoing edges of this vertex in the input graph.
diff --git a/graph/src/main/java/org/apache/hama/graph/VertexMessageIterable.java b/graph/src/main/java/org/apache/hama/graph/VertexMessageIterable.java
new file mode 100644
index 000000000..0b8e920dc
--- /dev/null
+++ b/graph/src/main/java/org/apache/hama/graph/VertexMessageIterable.java
@@ -0,0 +1,95 @@
+/**
+ * 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.hama.graph;
+
+import java.io.IOException;
+import java.util.Iterator;
+
+import org.apache.hadoop.io.Writable;
+import org.apache.hama.bsp.BSPPeer;
+
+import com.google.common.collect.AbstractIterator;
+
+/**
+ * The rationale behind this class is that it polls messages if they are
+ * requested and once it finds a message that is not dedicated for this vertex,
+ * it breaks the iteration. The message that was polled and doesn't belong to
+ * the vertex is returned by {@link #getOverflowMessage()}.
+ */
+public final class VertexMessageIterable<V, T> implements Iterable<T> {
+
+ private final V vertexID;
+ private final BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer;
+
+ private GraphJobMessage overflow;
+ private GraphJobMessage currentMessage;
+
+ private Iterator<T> currentIterator;
+
+ public VertexMessageIterable(GraphJobMessage currentMessage, V vertexID,
+ BSPPeer<Writable, Writable, Writable, Writable, GraphJobMessage> peer) {
+ this.currentMessage = currentMessage;
+ this.vertexID = vertexID;
+ this.peer = peer;
+ setupIterator();
+ }
+
+ private void setupIterator() {
+ currentIterator = new AbstractIterator<T>() {
+ @SuppressWarnings("unchecked")
+ @Override
+ protected T computeNext() {
+ // spool back the current message
+ if (currentMessage != null) {
+ GraphJobMessage tmp = currentMessage;
+ // set it to null, so we don't send it over and over again
+ currentMessage = null;
+ return (T) tmp.getVertexValue();
+ }
+
+ try {
+ GraphJobMessage msg = peer.getCurrentMessage();
+ if (msg != null) {
+ if (msg.getVertexId().equals(vertexID)) {
+ return (T) msg.getVertexValue();
+ } else {
+ overflow = msg;
+ }
+ }
+ return endOfData();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ }
+
+ public GraphJobMessage getOverflowMessage() {
+ // check if iterable was completely consumed
+ while (currentIterator.hasNext()) {
+ currentIterator.next();
+ }
+ return overflow;
+ }
+
+ @Override
+ public Iterator<T> iterator() {
+ return currentIterator;
+ }
+
+}
diff --git a/graph/src/main/java/org/apache/hama/graph/VerticesInfo.java b/graph/src/main/java/org/apache/hama/graph/VerticesInfo.java
new file mode 100644
index 000000000..4c9db69b2
--- /dev/null
+++ b/graph/src/main/java/org/apache/hama/graph/VerticesInfo.java
@@ -0,0 +1,89 @@
+/**
+ * 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.hama.graph;
+
+import java.io.IOException;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.io.WritableComparable;
+import org.apache.hama.bsp.TaskAttemptID;
+
+/**
+ * VerticesInfo interface encapsulates the storage of vertices in a BSP Task.
+ *
+ * @param <V> Vertex ID object type
+ * @param <E> Edge cost object type
+ * @param <M> Vertex value object type
+ */
+public interface VerticesInfo<V extends WritableComparable<? super V>, E extends Writable, M extends Writable> {
+
+ /**
+ * Initialization of internal structures.
+ */
+ public void init(GraphJobRunner<V, E, M> runner, Configuration conf,
+ TaskAttemptID attempt) throws IOException;
+
+ /**
+ * Cleanup of internal structures.
+ */
+ public void cleanup(Configuration conf, TaskAttemptID attempt)
+ throws IOException;
+
+ /**
+ * Add a vertex to the underlying structure.
+ */
+ public void addVertex(Vertex<V, E, M> vertex) throws IOException;
+
+ /**
+ * Finish the additions, from this point on the implementations should close
+ * the adds and throw exceptions in case something is added after this call.
+ */
+ public void finishAdditions();
+
+ /**
+ * Called once a superstep starts.
+ */
+ public void startSuperstep() throws IOException;
+
+ /**
+ * Called once completed a superstep.
+ */
+ public void finishSuperstep() throws IOException;
+
+ /**
+ * Must be called once a vertex is guaranteed not to change any more and can
+ * safely be persisted to a secondary storage.
+ */
+ public void finishVertexComputation(Vertex<V, E, M> vertex)
+ throws IOException;
+
+ /**
+ * @return true of all vertices are added.
+ */
+ public boolean isFinishedAdditions();
+
+ /**
+ * @return the number of vertices added to the underlying structure.
+ * Implementations should take care this is a constant time operation.
+ */
+ public int size();
+
+ public IDSkippingIterator<V, E, M> skippingIterator();
+
+}
diff --git a/graph/src/test/java/org/apache/hama/graph/TestAbsDiffAggregator.java b/graph/src/test/java/org/apache/hama/graph/TestAbsDiffAggregator.java
new file mode 100644
index 000000000..0b9a4a01e
--- /dev/null
+++ b/graph/src/test/java/org/apache/hama/graph/TestAbsDiffAggregator.java
@@ -0,0 +1,40 @@
+/**
+ * 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.hama.graph;
+
+import junit.framework.TestCase;
+
+import org.apache.hadoop.io.DoubleWritable;
+import org.junit.Test;
+
+public class TestAbsDiffAggregator extends TestCase {
+
+ @Test
+ public void testAggregator() {
+ AbsDiffAggregator diff = new AbsDiffAggregator();
+ diff.aggregate(null, new DoubleWritable(5), new DoubleWritable(2));
+ diff.aggregate(null, new DoubleWritable(5), new DoubleWritable(2));
+ diff.aggregate(null, null, new DoubleWritable(5));
+
+ // 0, because this is totally worthless for diffs
+ assertEquals(0, diff.getTimesAggregated().get());
+ assertEquals(6, (int) diff.getValue().get());
+
+ }
+
+}
diff --git a/graph/src/test/java/org/apache/hama/graph/TestAverageAggregator.java b/graph/src/test/java/org/apache/hama/graph/TestAverageAggregator.java
new file mode 100644
index 000000000..5018d0b1b
--- /dev/null
+++ b/graph/src/test/java/org/apache/hama/graph/TestAverageAggregator.java
@@ -0,0 +1,43 @@
+/**
+ * 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.hama.graph;
+
+import junit.framework.TestCase;
+
+import org.apache.hadoop.io.DoubleWritable;
+import org.junit.Test;
+
+public class TestAverageAggregator extends TestCase {
+
+ @Test
+ public void testAggregator() {
+ AverageAggregator diff = new AverageAggregator();
+ diff.aggregate(null, new DoubleWritable(5), new DoubleWritable(2));
+ diff.aggregateInternal();
+ diff.aggregate(null, new DoubleWritable(5), new DoubleWritable(2));
+ diff.aggregateInternal();
+ diff.aggregate(null, null, new DoubleWritable(5));
+ diff.aggregateInternal();
+
+ assertEquals(3, diff.getTimesAggregated().get());
+ DoubleWritable x = diff.finalizeAggregation();
+ assertEquals(2, (int) x.get());
+
+ }
+
+}
diff --git a/graph/src/test/java/org/apache/hama/graph/TestDiskVerticesInfo.java b/graph/src/test/java/org/apache/hama/graph/TestDiskVerticesInfo.java
new file mode 100644
index 000000000..dbc286bd7
--- /dev/null
+++ b/graph/src/test/java/org/apache/hama/graph/TestDiskVerticesInfo.java
@@ -0,0 +1,141 @@
+/**
+ * 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.hama.graph;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.io.DoubleWritable;
+import org.apache.hadoop.io.NullWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hama.bsp.TaskAttemptID;
+import org.apache.hama.graph.example.PageRank;
+import org.apache.hama.graph.example.PageRank.PageRankVertex;
+import org.junit.Test;
+
+public class TestDiskVerticesInfo extends TestCase {
+
+ @Test
+ public void testDiskVerticesInfoLifeCycle() throws Exception {
+ DiskVerticesInfo<Text, NullWritable, DoubleWritable> info = new DiskVerticesInfo<Text, NullWritable, DoubleWritable>();
+ Configuration conf = new Configuration();
+ conf.set(GraphJob.VERTEX_CLASS_ATTR, PageRankVertex.class.getName());
+ conf.set(GraphJob.VERTEX_EDGE_VALUE_CLASS_ATTR,
+ NullWritable.class.getName());
+ conf.set(GraphJob.VERTEX_ID_CLASS_ATTR, Text.class.getName());
+ conf.set(GraphJob.VERTEX_VALUE_CLASS_ATTR, DoubleWritable.class.getName());
+ GraphJobRunner.<Text, NullWritable, DoubleWritable> initClasses(conf);
+ TaskAttemptID attempt = new TaskAttemptID("omg", 1, 1, 0);
+ try {
+ ArrayList<PageRankVertex> list = new ArrayList<PageRankVertex>();
+
+ for (int i = 0; i < 10; i++) {
+ PageRankVertex v = new PageRank.PageRankVertex();
+ v.setVertexID(new Text(i + ""));
+ if (i % 2 == 0) {
+ v.setValue(new DoubleWritable(i * 2));
+ }
+ v.addEdge(new Edge<Text, NullWritable>(new Text((10 - i) + ""), null));
+
+ list.add(v);
+ }
+
+ info.init(null, conf, attempt);
+ for (PageRankVertex v : list) {
+ info.addVertex(v);
+ }
+
+ info.finishAdditions();
+
+ assertEquals(10, info.size());
+ // no we want to iterate and check if the result can properly be obtained
+
+ int index = 0;
+ IDSkippingIterator<Text, NullWritable, DoubleWritable> iterator = info
+ .skippingIterator();
+ while (iterator.hasNext()) {
+ Vertex<Text, NullWritable, DoubleWritable> next = iterator.next();
+ PageRankVertex pageRankVertex = list.get(index);
+ assertEquals(pageRankVertex.getVertexID().toString(), next
+ .getVertexID().toString());
+ if (index % 2 == 0) {
+ assertEquals((int) next.getValue().get(), index * 2);
+ } else {
+ assertNull(next.getValue());
+ }
+ assertEquals(next.isHalted(), false);
+ // check edges
+ List<Edge<Text, NullWritable>> edges = next.getEdges();
+ assertEquals(1, edges.size());
+ Edge<Text, NullWritable> edge = edges.get(0);
+ assertEquals(pageRankVertex.getEdges().get(0).getDestinationVertexID()
+ .toString(), edge.getDestinationVertexID().toString());
+ assertNull(edge.getValue());
+
+ index++;
+ }
+ assertEquals(index, list.size());
+ info.finishSuperstep();
+ // iterate again and compute so vertices change internally
+ iterator = info.skippingIterator();
+ info.startSuperstep();
+ while (iterator.hasNext()) {
+ Vertex<Text, NullWritable, DoubleWritable> next = iterator.next();
+ // override everything with constant 2
+ next.setValue(new DoubleWritable(2));
+ if (Integer.parseInt(next.getVertexID().toString()) == 3) {
+ next.voteToHalt();
+ }
+ info.finishVertexComputation(next);
+ }
+ info.finishSuperstep();
+
+ index = 0;
+ // now reread
+ info.startSuperstep();
+ iterator = info.skippingIterator();
+ while (iterator.hasNext()) {
+ Vertex<Text, NullWritable, DoubleWritable> next = iterator.next();
+ PageRankVertex pageRankVertex = list.get(index);
+ assertEquals(pageRankVertex.getVertexID().toString(), next
+ .getVertexID().toString());
+ assertEquals((int) next.getValue().get(), 2);
+ // check edges
+ List<Edge<Text, NullWritable>> edges = next.getEdges();
+ assertEquals(1, edges.size());
+ Edge<Text, NullWritable> edge = edges.get(0);
+ assertEquals(pageRankVertex.getEdges().get(0).getDestinationVertexID()
+ .toString(), edge.getDestinationVertexID().toString());
+ assertNull(edge.getValue());
+ if (index == 3) {
+ assertEquals(true, next.isHalted());
+ }
+
+ index++;
+ }
+ assertEquals(index, list.size());
+
+ } finally {
+ info.cleanup(conf, attempt);
+ }
+
+ }
+}
diff --git a/graph/src/test/java/org/apache/hama/graph/TestGraphJobMessage.java b/graph/src/test/java/org/apache/hama/graph/TestGraphJobMessage.java
new file mode 100644
index 000000000..041695b6f
--- /dev/null
+++ b/graph/src/test/java/org/apache/hama/graph/TestGraphJobMessage.java
@@ -0,0 +1,50 @@
+package org.apache.hama.graph;
+
+import java.util.List;
+import java.util.PriorityQueue;
+
+import junit.framework.TestCase;
+
+import org.apache.hadoop.io.IntWritable;
+import org.apache.hadoop.io.MapWritable;
+import org.apache.hadoop.io.Text;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+
+public class TestGraphJobMessage extends TestCase {
+
+ @Test
+ public void testPriorityQueue() {
+ PriorityQueue<GraphJobMessage> prio = new PriorityQueue<GraphJobMessage>();
+ prio.addAll(getMessages());
+
+ GraphJobMessage poll = prio.poll();
+ assertEquals(true, poll.isMapMessage());
+ poll = prio.poll();
+ assertEquals(true, poll.isVertexMessage());
+ assertEquals("1", poll.getVertexId().toString());
+
+ poll = prio.poll();
+ assertEquals(true, poll.isVertexMessage());
+ assertEquals("2", poll.getVertexId().toString());
+
+ poll = prio.poll();
+ assertEquals(true, poll.isVertexMessage());
+ assertEquals("3", poll.getVertexId().toString());
+
+ assertTrue(prio.isEmpty());
+ }
+
+ public List<GraphJobMessage> getMessages() {
+ GraphJobMessage mapMsg = new GraphJobMessage(new MapWritable());
+ GraphJobMessage vertexMsg1 = new GraphJobMessage(new Text("1"),
+ new IntWritable());
+ GraphJobMessage vertexMsg2 = new GraphJobMessage(new Text("2"),
+ new IntWritable());
+ GraphJobMessage vertexMsg3 = new GraphJobMessage(new Text("3"),
+ new IntWritable());
+ return Lists.newArrayList(mapMsg, vertexMsg1, vertexMsg2, vertexMsg3);
+ }
+
+}
diff --git a/graph/src/test/java/org/apache/hama/graph/TestMinMaxAggregator.java b/graph/src/test/java/org/apache/hama/graph/TestMinMaxAggregator.java
new file mode 100644
index 000000000..7610cc98d
--- /dev/null
+++ b/graph/src/test/java/org/apache/hama/graph/TestMinMaxAggregator.java
@@ -0,0 +1,44 @@
+/**
+ * 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.hama.graph;
+
+import junit.framework.TestCase;
+
+import org.apache.hadoop.io.IntWritable;
+import org.junit.Test;
+
+public class TestMinMaxAggregator extends TestCase {
+
+ @Test
+ public void testMinAggregator() {
+ MinAggregator diff = new MinAggregator();
+ diff.aggregate(null, new IntWritable(5));
+ diff.aggregate(null, new IntWritable(25));
+ assertEquals(5, diff.getValue().get());
+
+ }
+
+ @Test
+ public void testMaxAggregator() {
+ MaxAggregator diff = new MaxAggregator();
+ diff.aggregate(null, new IntWritable(5));
+ diff.aggregate(null, new IntWritable(25));
+ assertEquals(25, diff.getValue().get());
+ }
+
+}
diff --git a/graph/src/test/java/org/apache/hama/graph/TestSubmitGraphJob.java b/graph/src/test/java/org/apache/hama/graph/TestSubmitGraphJob.java
index f5be758be..2d73985b6 100644
--- a/graph/src/test/java/org/apache/hama/graph/TestSubmitGraphJob.java
+++ b/graph/src/test/java/org/apache/hama/graph/TestSubmitGraphJob.java
@@ -44,12 +44,11 @@ public class TestSubmitGraphJob extends TestBSPMasterGroomServer {
"yahoo.com\tnasa.gov\tstackoverflow.com",
"twitter.com\tgoogle.com\tfacebook.com",
"nasa.gov\tyahoo.com\tstackoverflow.com",
- "youtube.com\tgoogle.com\tyahoo.com" };
+ "youtube.com\tgoogle.com\tyahoo.com", "google.com" };
private static String INPUT = "/tmp/pagerank/real-tmp.seq";
private static String OUTPUT = "/tmp/pagerank/real-out";
- @SuppressWarnings("unchecked")
@Override
public void testSubmitJob() throws Exception {
@@ -60,6 +59,7 @@ public void testSubmitJob() throws Exception {
bsp.setOutputPath(new Path(OUTPUT));
BSPJobClient jobClient = new BSPJobClient(configuration);
configuration.setInt(Constants.ZOOKEEPER_SESSION_TIMEOUT, 6000);
+ configuration.set("hama.graph.self.ref", "true");
ClusterStatus cluster = jobClient.getClusterStatus(false);
assertEquals(this.numOfGroom, cluster.getGroomServers());
LOG.info("Client finishes execution job.");
@@ -67,11 +67,8 @@ public void testSubmitJob() throws Exception {
bsp.setVertexClass(PageRank.PageRankVertex.class);
// set the defaults
bsp.setMaxIteration(30);
- // FIXME why is the sum correct when 1-ALPHA instead of ALPHA itself?
- bsp.set("hama.pagerank.alpha", "0.25");
- bsp.setAggregatorClass(AverageAggregator.class,
- PageRank.DanglingNodeAggregator.class);
+ bsp.setAggregatorClass(AverageAggregator.class);
bsp.setInputFormat(SequenceFileInputFormat.class);
bsp.setInputKeyClass(Text.class);
diff --git a/graph/src/test/java/org/apache/hama/graph/TestSumAggregator.java b/graph/src/test/java/org/apache/hama/graph/TestSumAggregator.java
new file mode 100644
index 000000000..2023a38a3
--- /dev/null
+++ b/graph/src/test/java/org/apache/hama/graph/TestSumAggregator.java
@@ -0,0 +1,36 @@
+/**
+ * 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.hama.graph;
+
+import junit.framework.TestCase;
+
+import org.apache.hadoop.io.DoubleWritable;
+import org.junit.Test;
+
+public class TestSumAggregator extends TestCase {
+
+ @Test
+ public void testAggregator() {
+ SumAggregator diff = new SumAggregator();
+ diff.aggregate(null, new DoubleWritable(5));
+ diff.aggregate(null, new DoubleWritable(5));
+ assertEquals(10, (int) diff.getValue().get());
+
+ }
+
+}
diff --git a/graph/src/test/java/org/apache/hama/graph/example/PageRank.java b/graph/src/test/java/org/apache/hama/graph/example/PageRank.java
index cfce90f26..26d2c73f4 100644
--- a/graph/src/test/java/org/apache/hama/graph/example/PageRank.java
+++ b/graph/src/test/java/org/apache/hama/graph/example/PageRank.java
@@ -18,7 +18,6 @@
package org.apache.hama.graph.example;
import java.io.IOException;
-import java.util.Iterator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
@@ -31,7 +30,6 @@
import org.apache.hama.bsp.SequenceFileInputFormat;
import org.apache.hama.bsp.TextArrayWritable;
import org.apache.hama.bsp.TextOutputFormat;
-import org.apache.hama.graph.AbstractAggregator;
import org.apache.hama.graph.AverageAggregator;
import org.apache.hama.graph.Edge;
import org.apache.hama.graph.GraphJob;
@@ -49,8 +47,6 @@ public static class PageRankVertex extends
static double DAMPING_FACTOR = 0.85;
static double MAXIMUM_CONVERGENCE_ERROR = 0.001;
- int numEdges;
-
@Override
public void setup(Configuration conf) {
String val = conf.get("hama.pagerank.alpha");
@@ -61,30 +57,20 @@ public void setup(Configuration conf) {
if (val != null) {
MAXIMUM_CONVERGENCE_ERROR = Double.parseDouble(val);
}
- numEdges = this.getEdges().size();
}
@Override
- public void compute(Iterator<DoubleWritable> messages) throws IOException {
+ public void compute(Iterable<DoubleWritable> messages) throws IOException {
// initialize this vertex to 1 / count of global vertices in this graph
if (this.getSuperstepCount() == 0) {
this.setValue(new DoubleWritable(1.0 / this.getNumVertices()));
} else if (this.getSuperstepCount() >= 1) {
- DoubleWritable danglingNodeContribution = getLastAggregatedValue(1);
double sum = 0;
- while (messages.hasNext()) {
- DoubleWritable msg = messages.next();
+ for (DoubleWritable msg : messages) {
sum += msg.get();
}
- if (danglingNodeContribution == null) {
- double alpha = (1.0d - DAMPING_FACTOR) / this.getNumVertices();
- this.setValue(new DoubleWritable(alpha + (DAMPING_FACTOR * sum)));
- } else {
- double alpha = (1.0d - DAMPING_FACTOR) / this.getNumVertices();
- this.setValue(new DoubleWritable(alpha
- + (DAMPING_FACTOR * (sum + danglingNodeContribution.get()
- / this.getNumVertices()))));
- }
+ double alpha = (1.0d - DAMPING_FACTOR) / this.getNumVertices();
+ this.setValue(new DoubleWritable(alpha + (sum * DAMPING_FACTOR)));
}
// if we have not reached our global error yet, then proceed.
@@ -94,34 +80,10 @@ public void compute(Iterator<DoubleWritable> messages) throws IOException {
voteToHalt();
return;
}
+
// in each superstep we are going to send a new rank to our neighbours
sendMessageToNeighbors(new DoubleWritable(this.getValue().get()
- / numEdges));
- }
-
- }
-
- public static class DanglingNodeAggregator
- extends
- AbstractAggregator<DoubleWritable, Vertex<Text, NullWritable, DoubleWritable>> {
-
- double danglingNodeSum;
-
- @Override
- public void aggregate(Vertex<Text, NullWritable, DoubleWritable> vertex,
- DoubleWritable value) {
- if (vertex != null) {
- if (vertex.getEdges().size() == 0) {
- danglingNodeSum += value.get();
- }
- } else {
- danglingNodeSum += value.get();
- }
- }
-
- @Override
- public DoubleWritable getValue() {
- return new DoubleWritable(danglingNodeSum);
+ / this.getEdges().size()));
}
}
@@ -142,7 +104,6 @@ public boolean parseVertex(Text key, TextArrayWritable value,
}
}
- @SuppressWarnings("unchecked")
public static GraphJob createJob(String[] args, HamaConfiguration conf)
throws IOException {
GraphJob pageJob = new GraphJob(conf, PageRank.class);
@@ -155,15 +116,17 @@ public static GraphJob createJob(String[] args, HamaConfiguration conf)
// set the defaults
pageJob.setMaxIteration(30);
pageJob.set("hama.pagerank.alpha", "0.85");
+ // reference vertices to itself, because we don't have a dangling node
+ // contribution here
+ pageJob.set("hama.graph.self.ref", "true");
pageJob.set("hama.graph.max.convergence.error", "0.001");
if (args.length == 3) {
pageJob.setNumBspTask(Integer.parseInt(args[2]));
}
- // error, dangling node probability sum
- pageJob.setAggregatorClass(AverageAggregator.class,
- DanglingNodeAggregator.class);
+ // error
+ pageJob.setAggregatorClass(AverageAggregator.class);
// Vertex reader
pageJob.setVertexInputReaderClass(PagerankSeqReader.class);
|
626a84a93585cdde6719875ffd0fdc6d3e02af6f
|
kotlin
|
reimplemented extension literal definition and- calls to comply with jquery conventions--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/translator/src/org/jetbrains/k2js/translate/context/StandardClasses.java b/translator/src/org/jetbrains/k2js/translate/context/StandardClasses.java
index 2f831318824c2..fe520679c4283 100644
--- a/translator/src/org/jetbrains/k2js/translate/context/StandardClasses.java
+++ b/translator/src/org/jetbrains/k2js/translate/context/StandardClasses.java
@@ -103,8 +103,9 @@ public static StandardClasses bindImplementations(@NotNull JsScope kotlinObjectS
private static void declareJQuery(@NotNull StandardClasses standardClasses) {
standardClasses.declare().forFQ("jquery.JQuery").externalClass("jQuery")
- .methods("addClass", "attr", "hasClass", "append");
+ .methods("addClass", "attr", "hasClass", "append", "text", "ready");
standardClasses.declare().forFQ("jquery.jq").externalFunction("jQuery");
+ standardClasses.declare().forFQ("jquery.get-document").externalObject("document");
}
//TODO: test all the methods
@@ -142,6 +143,8 @@ private static void declareJetObjects(@NotNull StandardClasses standardClasses)
standardClasses.declare().forFQ("jet.String").kotlinClass("String").
properties("length");
+
+ standardClasses.declare().forFQ("jet.Any.toString").kotlinFunction("toString");
}
private static void declareTopLevelFunctions(@NotNull StandardClasses standardClasses) {
diff --git a/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java b/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java
index 1760c73ffaf3a..77a370b169f9a 100644
--- a/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java
+++ b/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java
@@ -1,5 +1,6 @@
package org.jetbrains.k2js.translate.expression;
+
import com.google.dart.compiler.backend.js.ast.*;
import com.google.dart.compiler.util.AstUtil;
import org.jetbrains.annotations.NotNull;
@@ -195,7 +196,7 @@ private void mayBeAddThisParameterForExtensionFunction(@NotNull List<JsParameter
}
private boolean isExtensionFunction() {
- return DescriptorUtils.isExtensionFunction(descriptor);
+ return DescriptorUtils.isExtensionFunction(descriptor) && !isLiteral();
}
private boolean isLiteral() {
diff --git a/translator/src/org/jetbrains/k2js/translate/reference/CallTranslator.java b/translator/src/org/jetbrains/k2js/translate/reference/CallTranslator.java
index c89fe93decab1..f0973d2906e6f 100644
--- a/translator/src/org/jetbrains/k2js/translate/reference/CallTranslator.java
+++ b/translator/src/org/jetbrains/k2js/translate/reference/CallTranslator.java
@@ -2,6 +2,7 @@
import com.google.dart.compiler.backend.js.ast.JsExpression;
import com.google.dart.compiler.backend.js.ast.JsInvocation;
+import com.google.dart.compiler.backend.js.ast.JsNameRef;
import com.google.dart.compiler.backend.js.ast.JsNew;
import com.google.dart.compiler.util.AstUtil;
import org.jetbrains.annotations.NotNull;
@@ -129,7 +130,6 @@ private static JetExpression getActualArgument(
public static JsExpression translate(@Nullable JsExpression receiver,
@NotNull CallableDescriptor descriptor,
@NotNull TranslationContext context) {
- //TODO: HACK!
return translate(receiver, Collections.<JsExpression>emptyList(),
ResolvedCallImpl.create(descriptor), null, context);
}
@@ -224,12 +224,37 @@ private JsExpression translate() {
if (isConstructor()) {
return constructorCall();
}
+ if (isExtensionFunctionLiteral()) {
+ return extensionFunctionLiteralCall();
+ }
if (isExtensionFunction()) {
return extensionFunctionCall();
}
return methodCall();
}
+ @NotNull
+ private JsExpression extensionFunctionLiteralCall() {
+
+ List<JsExpression> callArguments = new ArrayList<JsExpression>();
+ assert receiver != null;
+ callArguments.add(thisObject());
+ callArguments.addAll(arguments);
+ receiver = null;
+ JsNameRef callMethodNameRef = AstUtil.newQualifiedNameRef("call");
+ JsInvocation callMethodInvocation = new JsInvocation();
+ callMethodInvocation.setQualifier(callMethodNameRef);
+ AstUtil.setQualifier(callMethodInvocation, calleeReference());
+ callMethodInvocation.setArguments(callArguments);
+ return callMethodInvocation;
+ }
+
+ private boolean isExtensionFunctionLiteral() {
+ boolean isLiteral = descriptor instanceof VariableAsFunctionDescriptor
+ || descriptor instanceof ExpressionAsFunctionDescriptor;
+ return isExtensionFunction() && isLiteral;
+ }
+
@NotNull
private JsExpression extensionFunctionCall() {
receiver = getExtensionFunctionCallReceiver();
@@ -257,8 +282,10 @@ private JsExpression getExtensionFunctionCallReceiver() {
return getThisObject(context(), expectedReceiverDescriptor);
}
+ @SuppressWarnings("UnnecessaryLocalVariable")
private boolean isExtensionFunction() {
- return resolvedCall.getReceiverArgument().exists();
+ boolean hasReceiver = resolvedCall.getReceiverArgument().exists();
+ return hasReceiver;
}
@NotNull
diff --git a/translator/src/org/jetbrains/k2js/utils/JetFileUtils.java b/translator/src/org/jetbrains/k2js/utils/JetFileUtils.java
index 119592566fb64..e06a7e9e1774f 100644
--- a/translator/src/org/jetbrains/k2js/utils/JetFileUtils.java
+++ b/translator/src/org/jetbrains/k2js/utils/JetFileUtils.java
@@ -1,5 +1,6 @@
package org.jetbrains.k2js.utils;
+import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
@@ -10,6 +11,7 @@
import com.intellij.testFramework.LightVirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import org.jetbrains.jet.compiler.JetCoreEnvironment;
import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.plugin.JetLanguage;
@@ -21,13 +23,13 @@
*/
public final class JetFileUtils {
-// @NotNull
-// private static JetCoreEnvironment testOnlyEnvironment = new JetCoreEnvironment(new Disposable() {
-//
-// @Override
-// public void dispose() {
-// }
-// });
+ @NotNull
+ private static JetCoreEnvironment testOnlyEnvironment = new JetCoreEnvironment(new Disposable() {
+
+ @Override
+ public void dispose() {
+ }
+ });
@NotNull
public static String loadFile(@NotNull String path) throws IOException {
@@ -63,7 +65,8 @@ private static PsiFile createFile(@NotNull String name, @NotNull String text, @N
virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET);
Project realProject = project;
if (realProject == null) {
- throw new RuntimeException();
+ realProject = testOnlyEnvironment.getProject();
+ //throw new RuntimeException();
}
PsiFile result = ((PsiFileFactoryImpl) PsiFileFactory.getInstance(realProject))
.trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false);
diff --git a/translator/testFiles/kotlin_lib.js b/translator/testFiles/kotlin_lib.js
index 2eff88d9e4489..242b721c62bd8 100644
--- a/translator/testFiles/kotlin_lib.js
+++ b/translator/testFiles/kotlin_lib.js
@@ -902,6 +902,9 @@ Kotlin.StringBuilder = Kotlin.Class.create(
}
);
+Kotlin.toString = function(obj) {
+ return obj.toString();
+};
/**
* Copyright 2010 Tim Down.
|
4392b61d4c96820571ccc1c2cb9914e18f4fd7e3
|
Vala
|
vapigen: support setting array_length_type for parameters
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vala/valacodewriter.vala b/vala/valacodewriter.vala
index cb9c70cf55..a2bb0f9912 100644
--- a/vala/valacodewriter.vala
+++ b/vala/valacodewriter.vala
@@ -765,6 +765,10 @@ public class Vala.CodeWriter : CodeVisitor {
ccode_params.append_printf ("%sarray_length = false", separator);
separator = ", ";
}
+ if (param.array_length_type != null && param.parameter_type is ArrayType) {
+ ccode_params.append_printf ("%sarray_length_type = \"%s\"", separator, param.array_length_type);
+ separator = ", ";
+ }
if (!float_equal (param.carray_length_parameter_position, i + 0.1)) {
ccode_params.append_printf ("%sarray_length_pos = %g", separator, param.carray_length_parameter_position);
separator = ", ";
diff --git a/vapigen/valagidlparser.vala b/vapigen/valagidlparser.vala
index 85e861b61b..16b79013b2 100644
--- a/vapigen/valagidlparser.vala
+++ b/vapigen/valagidlparser.vala
@@ -1803,6 +1803,8 @@ public class Vala.GIdlParser : CodeVisitor {
if (eval (nv[1]) == "1") {
p.no_array_length = true;
}
+ } else if (nv[0] == "array_length_type") {
+ p.array_length_type = eval (nv[1]);
} else if (nv[0] == "array_null_terminated") {
if (eval (nv[1]) == "1") {
p.no_array_length = true;
|
8b57c2d95e39d7c08e42bb5b074969f076a321d8
|
intellij-community
|
[vcs-log] make BekLinearGraph testable--
|
p
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/BekBaseController.java b/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/BekBaseController.java
index 573d1f7dffc92..0e941ce5a1838 100644
--- a/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/BekBaseController.java
+++ b/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/BekBaseController.java
@@ -25,6 +25,7 @@
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo;
import com.intellij.vcs.log.graph.impl.facade.bek.BekChecker;
import com.intellij.vcs.log.graph.impl.facade.bek.BekIntMap;
+import com.intellij.vcs.log.graph.impl.permanent.PermanentLinearGraphImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -39,9 +40,9 @@ public class BekBaseController extends CascadeController {
public BekBaseController(@NotNull PermanentGraphInfo permanentGraphInfo, @NotNull BekIntMap bekIntMap) {
super(null, permanentGraphInfo);
myBekIntMap = bekIntMap;
- myBekGraph = new BekLinearGraph();
+ myBekGraph = new BekLinearGraph(myBekIntMap, myPermanentGraphInfo.getPermanentLinearGraph());
- assert BekChecker.checkLinearGraph(myBekGraph); // todo drop later
+ BekChecker.checkLinearGraph(myBekGraph);
}
@NotNull
@@ -85,16 +86,18 @@ public LinearGraph getCompiledGraph() {
return myBekGraph;
}
- private class BekLinearGraph implements LinearGraph {
- @NotNull private final LinearGraph myPermanentGraph;
+ public static class BekLinearGraph implements LinearGraph {
+ @NotNull private final LinearGraph myLinearGraph;
+ @NotNull private final BekIntMap myBekIntMap;
- private BekLinearGraph() {
- myPermanentGraph = myPermanentGraphInfo.getPermanentLinearGraph();
+ public BekLinearGraph(@NotNull BekIntMap bekIntMap, @NotNull LinearGraph linearGraph) {
+ myLinearGraph = linearGraph;
+ myBekIntMap = bekIntMap;
}
@Override
public int nodesCount() {
- return myPermanentGraph.nodesCount();
+ return myLinearGraph.nodesCount();
}
@Nullable
@@ -107,7 +110,7 @@ private Integer getNodeIndex(@Nullable Integer nodeId) {
@NotNull
@Override
public List<GraphEdge> getAdjacentEdges(int nodeIndex, @NotNull EdgeFilter filter) {
- return map(myPermanentGraph.getAdjacentEdges(myBekIntMap.getUsualIndex(nodeIndex), filter), new Function<GraphEdge, GraphEdge>() {
+ return map(myLinearGraph.getAdjacentEdges(myBekIntMap.getUsualIndex(nodeIndex), filter), new Function<GraphEdge, GraphEdge>() {
@Override
public GraphEdge fun(GraphEdge edge) {
return new GraphEdge(getNodeIndex(edge.getUpNodeIndex()), getNodeIndex(edge.getDownNodeIndex()), edge.getTargetId(),
diff --git a/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/bek/BekChecker.java b/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/bek/BekChecker.java
index b1dcc6a9bdd90..6e6cd7e0316ab 100644
--- a/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/bek/BekChecker.java
+++ b/platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/bek/BekChecker.java
@@ -16,8 +16,10 @@
package com.intellij.vcs.log.graph.impl.facade.bek;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.Pair;
import com.intellij.vcs.log.graph.api.LinearGraph;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import static com.intellij.vcs.log.graph.utils.LinearGraphUtils.getDownNodes;
import static com.intellij.vcs.log.graph.utils.LinearGraphUtils.getUpNodes;
@@ -25,17 +27,29 @@
public class BekChecker {
private final static Logger LOG = Logger.getInstance("#com.intellij.vcs.log.graph.impl.facade.bek.BekChecker");
- public static boolean checkLinearGraph(@NotNull LinearGraph linearGraph) {
+ public static void checkLinearGraph(@NotNull LinearGraph linearGraph) {
+ Pair<Integer, Integer> reversedEdge = findReversedEdge(linearGraph);
+ if (reversedEdge != null) {
+ LOG.error("Illegal edge: up node " + reversedEdge.first + ", downNode " + reversedEdge.second);
+ }
+ }
+
+ @Nullable
+ public static Pair<Integer, Integer> findReversedEdge(@NotNull LinearGraph linearGraph) {
for (int i = 0; i < linearGraph.nodesCount(); i++) {
for (int downNode : getDownNodes(linearGraph, i)) {
- if (downNode <= i) LOG.error("Illegal node: " + i + ", with downNode: " + downNode);
+ if (downNode <= i) {
+ return Pair.create(i, downNode);
+ }
}
for (int upNode : getUpNodes(linearGraph, i)) {
- if (upNode >= i) LOG.error("Illegal node: " + i + ", with upNode: " + upNode);
+ if (upNode >= i) {
+ return Pair.create(upNode, i);
+ }
}
}
- return true;
+ return null;
}
}
|
575b48a63e55b5216bf78ecf48621ac8f9f80729
|
drools
|
[DROOLS-820] reuse PomModel if already available--
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java
index bd16aa3b148..b710d0ffb6f 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java
@@ -91,6 +91,8 @@ public class KieBuilderImpl
private ClassLoader classLoader;
+ private PomModel pomModel;
+
public KieBuilderImpl(File file) {
this.srcMfs = new DiskResourceReader( file );
}
@@ -127,7 +129,7 @@ private PomModel init() {
// if pomXML is null it will generate a default, using default ReleaseId
// if pomXml is invalid, it assign pomModel to null
- PomModel pomModel = buildPomModel();
+ PomModel pomModel = getPomModel();
// if kModuleModelXML is null it will generate a default kModule, with a default kbase name
// if kModuleModelXML is invalid, it will kModule to null
@@ -283,6 +285,7 @@ private ResourceType getResourceType(String fileName) {
}
void cloneKieModuleForIncrementalCompilation() {
+ pomModel = null;
trgMfs = trgMfs.clone();
init();
kModule = kModule.cloneForIncrementalCompilation( releaseId, kModuleModel, trgMfs );
@@ -412,6 +415,20 @@ public static boolean setDefaultsforEmptyKieModule(KieModuleModel kModuleModel)
return false;
}
+ public PomModel getPomModel() {
+ if (pomModel == null) {
+ pomModel = buildPomModel();
+ }
+ return pomModel;
+ }
+
+ /**
+ * This can be used for performance reason to avoid the recomputation of the pomModel when it is already available
+ */
+ public void setPomModel( PomModel pomModel ) {
+ this.pomModel = pomModel;
+ }
+
private PomModel buildPomModel() {
pomXml = getOrGeneratePomXml( srcMfs );
if ( pomXml == null ) {
diff --git a/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java b/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java
index ff5b94cc5ef..3c0145ddff3 100644
--- a/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java
+++ b/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java
@@ -15,19 +15,16 @@
package org.kie.scanner;
+import org.drools.compiler.kie.builder.impl.InternalKieModule;
+import org.drools.compiler.kproject.models.KieModuleModelImpl;
import org.drools.core.common.ProjectClassLoader;
import org.drools.core.rule.KieModuleMetaInfo;
-import org.drools.compiler.kproject.ReleaseIdImpl;
-import org.drools.compiler.kproject.models.KieModuleModelImpl;
import org.drools.core.rule.TypeMetaInfo;
-import org.kie.api.builder.ReleaseId;
-import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.eclipse.aether.artifact.Artifact;
+import org.kie.api.builder.ReleaseId;
-import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
@@ -78,10 +75,8 @@ public KieModuleMetaDataImpl(File pomFile) {
}
public KieModuleMetaDataImpl(InternalKieModule kieModule) {
- String pomXmlPath = ((ReleaseIdImpl)kieModule.getReleaseId()).getPomXmlPath();
- InputStream pomStream = new ByteArrayInputStream(kieModule.getBytes(pomXmlPath));
- this.artifactResolver = getResolverFor(pomStream);
this.kieModule = kieModule;
+ this.artifactResolver = getResolverFor( kieModule.getPomModel() );
for (String file : kieModule.getFileNames()) {
if (!indexClass(file)) {
if (file.endsWith(KieModuleModelImpl.KMODULE_INFO_JAR_PATH)) {
@@ -148,9 +143,16 @@ private void init() {
if (releaseId != null) {
addArtifact(artifactResolver.resolveArtifact(releaseId));
}
- for (DependencyDescriptor dep : artifactResolver.getAllDependecies()) {
- addArtifact(artifactResolver.resolveArtifact(dep.getReleaseId()));
+ if ( kieModule != null ) {
+ for ( ReleaseId releaseId : kieModule.getPomModel().getDependencies() ) {
+ addArtifact( artifactResolver.resolveArtifact( releaseId ) );
+ }
+ } else {
+ for ( DependencyDescriptor dep : artifactResolver.getAllDependecies() ) {
+ addArtifact( artifactResolver.resolveArtifact( dep.getReleaseId() ) );
+ }
}
+
packages.addAll(classes.keySet());
packages.addAll(rulesByPackage.keySet());
}
|
e15a795130250de68c4ea9bf3205c58865732869
|
Vala
|
codegen: Support "foo is G"
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valaccodebasemodule.vala b/codegen/valaccodebasemodule.vala
index 4f049c1e67..488d434b1a 100644
--- a/codegen/valaccodebasemodule.vala
+++ b/codegen/valaccodebasemodule.vala
@@ -5349,13 +5349,13 @@ public abstract class Vala.CCodeBaseModule : CodeGenerator {
var type_domain = new CCodeIdentifier (get_ccode_upper_case_name (et.error_domain));
return new CCodeBinaryExpression (CCodeBinaryOperator.EQUALITY, instance_domain, type_domain);
} else {
- string type_id = get_ccode_type_id (type.data_type);
- if (type_id == "") {
+ var type_id = get_type_id_expression (type);
+ if (type_id == null) {
return new CCodeInvalidExpression ();
}
var ccheck = new CCodeFunctionCall (new CCodeIdentifier ("G_TYPE_CHECK_INSTANCE_TYPE"));
ccheck.add_argument ((CCodeExpression) ccodenode);
- ccheck.add_argument (new CCodeIdentifier (type_id));
+ ccheck.add_argument (type_id);
return ccheck;
}
}
diff --git a/tests/methods/generics.vala b/tests/methods/generics.vala
index b4655239a3..27e9cc16e2 100644
--- a/tests/methods/generics.vala
+++ b/tests/methods/generics.vala
@@ -4,6 +4,9 @@ interface Foo : Object {
}
}
+class Bar {
+}
+
class Baz : Object, Foo {
}
@@ -11,6 +14,11 @@ void foo<T> (owned T bar) {
bar = null;
}
+bool is_check<G> () {
+ var o = new Bar ();
+ return o is G;
+}
+
void main () {
var bar = new Object ();
foo<Object> (bar);
@@ -19,4 +27,7 @@ void main () {
var baz = new Baz ();
baz.foo<Object> (bar);
assert (baz.ref_count == 1);
+
+ assert (is_check<Bar> ());
+ assert (!is_check<Baz> ());
}
|
4155741f7f486537d4a5f7193d79098d523a6ae8
|
elasticsearch
|
BytesStreamOutput default size should be 2k- instead of 32k We changed the default of BytesStreamOutput (used in various- places in ES) to 32k from 1k with the assumption that most stream tend to be- large. This doesn't hold for example when indexing small documents and adding- them using XContentBuilder (which will have a large overhead).--Default the buffer size to 2k now
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/common/io/stream/BytesStreamOutput.java b/src/main/java/org/elasticsearch/common/io/stream/BytesStreamOutput.java
index 378a5fecb7ac8..52756377b5a3e 100644
--- a/src/main/java/org/elasticsearch/common/io/stream/BytesStreamOutput.java
+++ b/src/main/java/org/elasticsearch/common/io/stream/BytesStreamOutput.java
@@ -31,7 +31,9 @@
*/
public class BytesStreamOutput extends StreamOutput implements BytesStream {
- public static final int DEFAULT_SIZE = 32 * 1024;
+ public static final int DEFAULT_SIZE = 2 * 1024;
+
+ public static final int OVERSIZE_LIMIT = 256 * 1024;
/**
* The buffer where data is stored.
@@ -73,7 +75,7 @@ public void seek(long position) throws IOException {
public void writeByte(byte b) throws IOException {
int newcount = count + 1;
if (newcount > buf.length) {
- buf = ArrayUtil.grow(buf, newcount);
+ buf = grow(newcount);
}
buf[count] = b;
count = newcount;
@@ -82,7 +84,7 @@ public void writeByte(byte b) throws IOException {
public void skip(int length) {
int newcount = count + length;
if (newcount > buf.length) {
- buf = ArrayUtil.grow(buf, newcount);
+ buf = grow(newcount);
}
count = newcount;
}
@@ -94,12 +96,20 @@ public void writeBytes(byte[] b, int offset, int length) throws IOException {
}
int newcount = count + length;
if (newcount > buf.length) {
- buf = ArrayUtil.grow(buf, newcount);
+ buf = grow(newcount);
}
System.arraycopy(b, offset, buf, count, length);
count = newcount;
}
+ private byte[] grow(int newCount) {
+ // try and grow faster while we are small...
+ if (newCount < OVERSIZE_LIMIT) {
+ newCount = Math.max(buf.length << 1, newCount);
+ }
+ return ArrayUtil.grow(buf, newCount);
+ }
+
public void seek(int seekTo) {
count = seekTo;
}
@@ -108,6 +118,10 @@ public void reset() {
count = 0;
}
+ public int bufferSize() {
+ return buf.length;
+ }
+
@Override
public void flush() throws IOException {
// nothing to do there
diff --git a/src/test/java/org/elasticsearch/test/unit/common/io/streams/BytesStreamsTests.java b/src/test/java/org/elasticsearch/test/unit/common/io/streams/BytesStreamsTests.java
index c1f4dc450e30c..d4ee4fff5351f 100644
--- a/src/test/java/org/elasticsearch/test/unit/common/io/streams/BytesStreamsTests.java
+++ b/src/test/java/org/elasticsearch/test/unit/common/io/streams/BytesStreamsTests.java
@@ -60,4 +60,17 @@ public void testSimpleStreams() throws Exception {
assertThat(in.readString(), equalTo("hello"));
assertThat(in.readString(), equalTo("goodbye"));
}
+
+ @Test
+ public void testGrowLogic() throws Exception {
+ BytesStreamOutput out = new BytesStreamOutput();
+ out.writeBytes(new byte[BytesStreamOutput.DEFAULT_SIZE - 5]);
+ assertThat(out.bufferSize(), equalTo(2048)); // remains the default
+ out.writeBytes(new byte[1 * 1024]);
+ assertThat(out.bufferSize(), equalTo(4608));
+ out.writeBytes(new byte[32 * 1024]);
+ assertThat(out.bufferSize(), equalTo(40320));
+ out.writeBytes(new byte[32 * 1024]);
+ assertThat(out.bufferSize(), equalTo(90720));
+ }
}
|
80f75e3b338955c6f977a32a6de460682eb34034
|
tapiji
|
Updates license headers.
|
p
|
https://github.com/tapiji/tapiji
|
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 850a5a44..b8873ceb 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
@@ -6,7 +6,7 @@
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
- * Martin Reiterer - initial API and implementation
+ * Michael Gasser - initial API and implementation
******************************************************************************/
package org.eclipse.babel.tapiji.tools.core.util;
@@ -14,11 +14,6 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
-/**
- *
- * @author mgasser
- *
- */
public class RBFileUtils extends Action {
public static final String PROPERTIES_EXT = "properties";
|
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;
}
|
74b5e8ad3b43949f122e6430fe576ebdd44cf04a
|
Vala
|
vapigen: add support for type_parameters attribute
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapigen/valagidlparser.vala b/vapigen/valagidlparser.vala
index 727f57378d..771146fe42 100644
--- a/vapigen/valagidlparser.vala
+++ b/vapigen/valagidlparser.vala
@@ -525,6 +525,10 @@ public class Vala.GIdlParser : CodeVisitor {
if (eval (nv[1]) == "1") {
ref_function_void = true;
}
+ } else if (nv[0] == "type_parameters") {
+ foreach (string type_param_name in eval (nv[1]).split (",")) {
+ cl.add_type_parameter (new TypeParameter (type_param_name, current_source_reference));
+ }
}
}
}
|
37a9214ecf57b5c85c866a90a5e1a52cc3092e8e
|
intellij-community
|
symlink support in vfs & SOE protection--
|
a
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/platform-api/src/com/intellij/openapi/roots/impl/FileIndexImplUtil.java b/platform/platform-api/src/com/intellij/openapi/roots/impl/FileIndexImplUtil.java
index 94c2485a5f38f..c922e2388dfb6 100644
--- a/platform/platform-api/src/com/intellij/openapi/roots/impl/FileIndexImplUtil.java
+++ b/platform/platform-api/src/com/intellij/openapi/roots/impl/FileIndexImplUtil.java
@@ -33,7 +33,7 @@ public static boolean iterateRecursively(@NotNull final VirtualFile root, @NotNu
VfsUtilCore.visitChildrenRecursively(root, new VirtualFileVisitor() {
@Override
public boolean visitFile(VirtualFile file) {
- if (!file.isValid() || !filter.accept(file)) return true;
+ if (!file.isValid() || !filter.accept(file)) return false;
if (!iterator.processFile(file)) throw new StopItException();
return true;
|
5b91442a260b42e3d47ef91a53015f2d0958a683
|
Delta Spike
|
remove unused private field
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/cdictrl/impl-weld/src/main/java/org/apache/deltaspike/cdise/weld/ContextController.java b/deltaspike/cdictrl/impl-weld/src/main/java/org/apache/deltaspike/cdise/weld/ContextController.java
index 85f05c692..64c1df062 100644
--- a/deltaspike/cdictrl/impl-weld/src/main/java/org/apache/deltaspike/cdise/weld/ContextController.java
+++ b/deltaspike/cdictrl/impl-weld/src/main/java/org/apache/deltaspike/cdise/weld/ContextController.java
@@ -55,8 +55,6 @@ public class ContextController
private Map<String, Object> requestMap;
- private boolean applicationScopeStarted;
-
private boolean singletonScopeStarted;
void startApplicationScope()
|
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);
+ }
+}
|
bdf572331bcca90f192d50cb79d97ca67ac43d90
|
Vala
|
codegen: Zero length of arrays when transferring ownership
This allows var data = (owned) aGenericArray.data;
without later setting data.len = 0 manually.
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/codegen/valaccodebasemodule.vala b/codegen/valaccodebasemodule.vala
index 1d7a5715ff..bc7411aad5 100644
--- a/codegen/valaccodebasemodule.vala
+++ b/codegen/valaccodebasemodule.vala
@@ -5139,9 +5139,19 @@ public abstract class Vala.CCodeBaseModule : CodeGenerator {
if (target_destroy_notify != null) {
ccode.add_assignment (target_destroy_notify, new CCodeConstant ("NULL"));
}
+ } else if (expr.inner.value_type is ArrayType) {
+ var array_type = (ArrayType) expr.inner.value_type;
+ var glib_value = (GLibValue) expr.inner.target_value;
+
+ ccode.add_assignment (get_cvalue (expr.inner), new CCodeConstant ("NULL"));
+ if (glib_value.array_length_cvalues != null) {
+ for (int dim = 1; dim <= array_type.rank; dim++) {
+ ccode.add_assignment (get_array_length_cvalue (glib_value, dim), new CCodeConstant ("0"));
+ }
+ }
} else {
ccode.add_assignment (get_cvalue (expr.inner), new CCodeConstant ("NULL"));
- }
+ }
}
public override void visit_binary_expression (BinaryExpression expr) {
diff --git a/tests/basic-types/arrays.vala b/tests/basic-types/arrays.vala
index be0ca236f0..4a6a006ec9 100644
--- a/tests/basic-types/arrays.vala
+++ b/tests/basic-types/arrays.vala
@@ -96,6 +96,10 @@ void test_static_array () {
void test_reference_transfer () {
var baz = (owned) foo;
baz = (owned) bar;
+
+ var data = new string[]{"foo"};
+ var data2 = (owned) data;
+ assert (data.length == 0);
}
void test_length_assignment () {
@@ -121,4 +125,3 @@ void main () {
test_length_assignment ();
test_inline_array ();
}
-
|
edc59a680a0c147a19b0f5f216db8553b6e7dc57
|
drools
|
- fixed an issue where a comment in a work item- definition file results in a null work item definition object
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/RuleBaseConfiguration.java b/drools-core/src/main/java/org/drools/RuleBaseConfiguration.java
index 3b490a1b18d..bcbf3aa832e 100755
--- a/drools-core/src/main/java/org/drools/RuleBaseConfiguration.java
+++ b/drools-core/src/main/java/org/drools/RuleBaseConfiguration.java
@@ -812,31 +812,33 @@ private void loadWorkItems(String location) {
List<Map<String, Object>> workDefinitionsMap = (List<Map<String, Object>>) MVEL.eval( content,
new HashMap() );
for ( Map<String, Object> workDefinitionMap : workDefinitionsMap ) {
- WorkDefinitionExtensionImpl workDefinition = new WorkDefinitionExtensionImpl();
- workDefinition.setName( (String) workDefinitionMap.get( "name" ) );
- workDefinition.setDisplayName( (String) workDefinitionMap.get( "displayName" ) );
- workDefinition.setIcon( (String) workDefinitionMap.get( "icon" ) );
- workDefinition.setCustomEditor( (String) workDefinitionMap.get( "customEditor" ) );
- Set<ParameterDefinition> parameters = new HashSet<ParameterDefinition>();
- Map<String, DataType> parameterMap = (Map<String, DataType>) workDefinitionMap.get( "parameters" );
- if ( parameterMap != null ) {
- for ( Map.Entry<String, DataType> entry : parameterMap.entrySet() ) {
- parameters.add( new ParameterDefinitionImpl( entry.getKey(),
- entry.getValue() ) );
- }
- }
- workDefinition.setParameters( parameters );
- Set<ParameterDefinition> results = new HashSet<ParameterDefinition>();
- Map<String, DataType> resultMap = (Map<String, DataType>) workDefinitionMap.get( "results" );
- if ( resultMap != null ) {
- for ( Map.Entry<String, DataType> entry : resultMap.entrySet() ) {
- results.add( new ParameterDefinitionImpl( entry.getKey(),
- entry.getValue() ) );
- }
- }
- workDefinition.setResults( results );
- this.workDefinitions.put( workDefinition.getName(),
- workDefinition );
+ if (workDefinitionMap != null) {
+ WorkDefinitionExtensionImpl workDefinition = new WorkDefinitionExtensionImpl();
+ workDefinition.setName( (String) workDefinitionMap.get( "name" ) );
+ workDefinition.setDisplayName( (String) workDefinitionMap.get( "displayName" ) );
+ workDefinition.setIcon( (String) workDefinitionMap.get( "icon" ) );
+ workDefinition.setCustomEditor( (String) workDefinitionMap.get( "customEditor" ) );
+ Set<ParameterDefinition> parameters = new HashSet<ParameterDefinition>();
+ Map<String, DataType> parameterMap = (Map<String, DataType>) workDefinitionMap.get( "parameters" );
+ if ( parameterMap != null ) {
+ for ( Map.Entry<String, DataType> entry : parameterMap.entrySet() ) {
+ parameters.add( new ParameterDefinitionImpl( entry.getKey(),
+ entry.getValue() ) );
+ }
+ }
+ workDefinition.setParameters( parameters );
+ Set<ParameterDefinition> results = new HashSet<ParameterDefinition>();
+ Map<String, DataType> resultMap = (Map<String, DataType>) workDefinitionMap.get( "results" );
+ if ( resultMap != null ) {
+ for ( Map.Entry<String, DataType> entry : resultMap.entrySet() ) {
+ results.add( new ParameterDefinitionImpl( entry.getKey(),
+ entry.getValue() ) );
+ }
+ }
+ workDefinition.setResults( results );
+ this.workDefinitions.put( workDefinition.getName(),
+ workDefinition );
+ }
}
} catch ( Throwable t ) {
System.err.println( "Error occured while loading work definitions " + location );
|
3fd458ad88808e542b211461a49728138c1ebe79
|
hbase
|
HBASE-6427 Pluggable compaction and scan policies- via coprocessors--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1367361 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/BaseRegionObserver.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/BaseRegionObserver.java
index feb9aa391877..3607e7dbe178 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/BaseRegionObserver.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/BaseRegionObserver.java
@@ -17,7 +17,7 @@
package org.apache.hadoop.hbase.coprocessor;
import java.util.List;
-import java.util.Map;
+import java.util.NavigableSet;
import com.google.common.collect.ImmutableList;
@@ -37,7 +37,9 @@
import org.apache.hadoop.hbase.filter.WritableByteArrayComparable;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.InternalScanner;
+import org.apache.hadoop.hbase.regionserver.KeyValueScanner;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
+import org.apache.hadoop.hbase.regionserver.ScanType;
import org.apache.hadoop.hbase.regionserver.Store;
import org.apache.hadoop.hbase.regionserver.StoreFile;
import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
@@ -74,6 +76,13 @@ public void preClose(ObserverContext<RegionCoprocessorEnvironment> e,
public void postClose(ObserverContext<RegionCoprocessorEnvironment> e,
boolean abortRequested) { }
+ @Override
+ public InternalScanner preFlushScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ final Store store, final KeyValueScanner memstoreScanner, final InternalScanner s)
+ throws IOException {
+ return null;
+ }
+
@Override
public void preFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
}
@@ -82,6 +91,17 @@ public void preFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOE
public void postFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
}
+ @Override
+ public InternalScanner preFlush(ObserverContext<RegionCoprocessorEnvironment> e, Store store,
+ InternalScanner scanner) throws IOException {
+ return scanner;
+ }
+
+ @Override
+ public void postFlush(ObserverContext<RegionCoprocessorEnvironment> e, Store store,
+ StoreFile resultFile) throws IOException {
+ }
+
@Override
public void preSplit(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
}
@@ -105,6 +125,13 @@ public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment>
return scanner;
}
+ @Override
+ public InternalScanner preCompactScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ final Store store, List<? extends KeyValueScanner> scanners, final ScanType scanType,
+ final long earliestPutTs, final InternalScanner s) throws IOException {
+ return null;
+ }
+
@Override
public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e, final Store store,
final StoreFile resultFile) throws IOException {
@@ -241,6 +268,13 @@ public RegionScanner preScannerOpen(final ObserverContext<RegionCoprocessorEnvir
return s;
}
+ @Override
+ public KeyValueScanner preStoreScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ final Store store, final Scan scan, final NavigableSet<byte[]> targetCols,
+ final KeyValueScanner s) throws IOException {
+ return null;
+ }
+
@Override
public RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> e,
final Scan scan, final RegionScanner s) throws IOException {
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/RegionObserver.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/RegionObserver.java
index c5b858eaca86..c3cfa097bbb7 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/RegionObserver.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/coprocessor/RegionObserver.java
@@ -18,6 +18,7 @@
import java.io.IOException;
import java.util.List;
+import java.util.NavigableSet;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
@@ -35,9 +36,12 @@
import org.apache.hadoop.hbase.filter.WritableByteArrayComparable;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.InternalScanner;
+import org.apache.hadoop.hbase.regionserver.KeyValueScanner;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
+import org.apache.hadoop.hbase.regionserver.ScanType;
import org.apache.hadoop.hbase.regionserver.Store;
import org.apache.hadoop.hbase.regionserver.StoreFile;
+import org.apache.hadoop.hbase.regionserver.StoreFileScanner;
import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
@@ -64,20 +68,63 @@ public interface RegionObserver extends Coprocessor {
*/
void postOpen(final ObserverContext<RegionCoprocessorEnvironment> c);
+ /**
+ * Called before a memstore is flushed to disk and prior to creating the scanner to read from
+ * the memstore. To override or modify how a memstore is flushed,
+ * implementing classes can return a new scanner to provide the KeyValues to be
+ * stored into the new {@code StoreFile} or null to perform the default processing.
+ * Calling {@link org.apache.hadoop.hbase.coprocessor.ObserverContext#bypass()} has no
+ * effect in this hook.
+ * @param c the environment provided by the region server
+ * @param store the store being flushed
+ * @param memstoreScanner the scanner for the memstore that is flushed
+ * @param s the base scanner, if not {@code null}, from previous RegionObserver in the chain
+ * @return the scanner to use during the flush. {@code null} if the default implementation
+ * is to be used.
+ * @throws IOException if an error occurred on the coprocessor
+ */
+ InternalScanner preFlushScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ final Store store, final KeyValueScanner memstoreScanner, final InternalScanner s)
+ throws IOException;
+
/**
* Called before the memstore is flushed to disk.
* @param c the environment provided by the region server
* @throws IOException if an error occurred on the coprocessor
+ * @deprecated use {@link #preFlush(ObserverContext, Store, InternalScanner)} instead
*/
void preFlush(final ObserverContext<RegionCoprocessorEnvironment> c) throws IOException;
+ /**
+ * Called before a Store's memstore is flushed to disk.
+ * @param c the environment provided by the region server
+ * @param store the store where compaction is being requested
+ * @param scanner the scanner over existing data used in the store file
+ * @return the scanner to use during compaction. Should not be {@code null}
+ * unless the implementation is writing new store files on its own.
+ * @throws IOException if an error occurred on the coprocessor
+ */
+ InternalScanner preFlush(final ObserverContext<RegionCoprocessorEnvironment> c, final Store store,
+ final InternalScanner scanner) throws IOException;
+
/**
* Called after the memstore is flushed to disk.
* @param c the environment provided by the region server
* @throws IOException if an error occurred on the coprocessor
+ * @deprecated use {@link #preFlush(ObserverContext, Store, InternalScanner)} instead.
*/
void postFlush(final ObserverContext<RegionCoprocessorEnvironment> c) throws IOException;
+ /**
+ * Called after a Store's memstore is flushed to disk.
+ * @param c the environment provided by the region server
+ * @param store the store being flushed
+ * @param resultFile the new store file written out during compaction
+ * @throws IOException if an error occurred on the coprocessor
+ */
+ void postFlush(final ObserverContext<RegionCoprocessorEnvironment> c, final Store store,
+ final StoreFile resultFile) throws IOException;
+
/**
* Called prior to selecting the {@link StoreFile}s to compact from the list
* of available candidates. To alter the files used for compaction, you may
@@ -127,6 +174,29 @@ void postCompactSelection(final ObserverContext<RegionCoprocessorEnvironment> c,
InternalScanner preCompact(final ObserverContext<RegionCoprocessorEnvironment> c,
final Store store, final InternalScanner scanner) throws IOException;
+ /**
+ * Called prior to writing the {@link StoreFile}s selected for compaction into
+ * a new {@code StoreFile} and prior to creating the scanner used to read the
+ * input files. To override or modify the compaction process,
+ * implementing classes can return a new scanner to provide the KeyValues to be
+ * stored into the new {@code StoreFile} or null to perform the default processing.
+ * Calling {@link org.apache.hadoop.hbase.coprocessor.ObserverContext#bypass()} has no
+ * effect in this hook.
+ * @param c the environment provided by the region server
+ * @param store the store being compacted
+ * @param scanners the list {@link StoreFileScanner}s to be read from
+ * @param scantype the {@link ScanType} indicating whether this is a major or minor compaction
+ * @param earliestPutTs timestamp of the earliest put that was found in any of the involved
+ * store files
+ * @param s the base scanner, if not {@code null}, from previous RegionObserver in the chain
+ * @return the scanner to use during compaction. {@code null} if the default implementation
+ * is to be used.
+ * @throws IOException if an error occurred on the coprocessor
+ */
+ InternalScanner preCompactScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ final Store store, List<? extends KeyValueScanner> scanners, final ScanType scanType,
+ final long earliestPutTs, final InternalScanner s) throws IOException;
+
/**
* Called after compaction has completed and the new store file has been
* moved in to place.
@@ -549,6 +619,30 @@ RegionScanner preScannerOpen(final ObserverContext<RegionCoprocessorEnvironment>
final Scan scan, final RegionScanner s)
throws IOException;
+ /**
+ * Called before a store opens a new scanner.
+ * This hook is called when a "user" scanner is opened.
+ * <p>
+ * See {@link #preFlushScannerOpen(ObserverContext, Store, KeyValueScanner, InternalScanner)}
+ * and {@link #preCompactScannerOpen(ObserverContext, Store, List, ScanType, long, InternalScanner)}
+ * to override scanners created for flushes or compactions, resp.
+ * <p>
+ * Call CoprocessorEnvironment#complete to skip any subsequent chained
+ * coprocessors.
+ * Calling {@link org.apache.hadoop.hbase.coprocessor.ObserverContext#bypass()} has no
+ * effect in this hook.
+ * @param c the environment provided by the region server
+ * @param store the store being scanned
+ * @param scan the Scan specification
+ * @param targetCols columns to be used in the scanner
+ * @param s the base scanner, if not {@code null}, from previous RegionObserver in the chain
+ * @return a KeyValueScanner instance to use or {@code null} to use the default implementation
+ * @throws IOException if an error occurred on the coprocessor
+ */
+ KeyValueScanner preStoreScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ final Store store, final Scan scan, final NavigableSet<byte[]> targetCols,
+ final KeyValueScanner s) throws IOException;
+
/**
* Called after the client opens a new scanner.
* <p>
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Compactor.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Compactor.java
index 9ed051f8be3e..b606458e6e1d 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Compactor.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Compactor.java
@@ -32,7 +32,6 @@
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.hfile.Compression;
-import org.apache.hadoop.hbase.regionserver.StoreScanner.ScanType;
import org.apache.hadoop.hbase.regionserver.compactions.CompactionProgress;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.util.StringUtils;
@@ -127,12 +126,21 @@ StoreFile.Writer compact(final Store store,
try {
InternalScanner scanner = null;
try {
- Scan scan = new Scan();
- scan.setMaxVersions(store.getFamily().getMaxVersions());
- /* Include deletes, unless we are doing a major compaction */
- scanner = new StoreScanner(store, scan, scanners,
- majorCompaction? ScanType.MAJOR_COMPACT : ScanType.MINOR_COMPACT,
- smallestReadPoint, earliestPutTs);
+ if (store.getHRegion().getCoprocessorHost() != null) {
+ scanner = store
+ .getHRegion()
+ .getCoprocessorHost()
+ .preCompactScannerOpen(store, scanners,
+ majorCompaction ? ScanType.MAJOR_COMPACT : ScanType.MINOR_COMPACT, earliestPutTs);
+ }
+ if (scanner == null) {
+ Scan scan = new Scan();
+ scan.setMaxVersions(store.getFamily().getMaxVersions());
+ /* Include deletes, unless we are doing a major compaction */
+ scanner = new StoreScanner(store, store.scanInfo, scan, scanners,
+ majorCompaction? ScanType.MAJOR_COMPACT : ScanType.MINOR_COMPACT,
+ smallestReadPoint, earliestPutTs);
+ }
if (store.getHRegion().getCoprocessorHost() != null) {
InternalScanner cpScanner =
store.getHRegion().getCoprocessorHost().preCompact(store, scanner);
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java
index 7df5e72d26d3..36d6bacd070f 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java
@@ -1216,7 +1216,7 @@ void triggerMajorCompaction() {
* @param majorCompaction True to force a major compaction regardless of thresholds
* @throws IOException e
*/
- void compactStores(final boolean majorCompaction)
+ public void compactStores(final boolean majorCompaction)
throws IOException {
if (majorCompaction) {
this.triggerMajorCompaction();
@@ -3469,7 +3469,7 @@ public HRegionInfo getRegionInfo() {
for (Map.Entry<byte[], NavigableSet<byte[]>> entry :
scan.getFamilyMap().entrySet()) {
Store store = stores.get(entry.getKey());
- StoreScanner scanner = store.getScanner(scan, entry.getValue());
+ KeyValueScanner scanner = store.getScanner(scan, entry.getValue());
scanners.add(scanner);
}
this.storeHeap = new KeyValueHeap(scanners, comparator);
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionCoprocessorHost.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionCoprocessorHost.java
index 58afaf439b9f..f6efea5b1b23 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionCoprocessorHost.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/RegionCoprocessorHost.java
@@ -303,6 +303,31 @@ public void postClose(boolean abortRequested) {
}
}
+ /**
+ * See
+ * {@link RegionObserver#preCompactScannerOpen(ObserverContext, Store, List, ScanType, long, InternalScanner)}
+ */
+ public InternalScanner preCompactScannerOpen(Store store, List<StoreFileScanner> scanners,
+ ScanType scanType, long earliestPutTs) throws IOException {
+ ObserverContext<RegionCoprocessorEnvironment> ctx = null;
+ InternalScanner s = null;
+ for (RegionEnvironment env: coprocessors) {
+ if (env.getInstance() instanceof RegionObserver) {
+ ctx = ObserverContext.createAndPrepare(env, ctx);
+ try {
+ s = ((RegionObserver) env.getInstance()).preCompactScannerOpen(ctx, store, scanners,
+ scanType, earliestPutTs, s);
+ } catch (Throwable e) {
+ handleCoprocessorThrowable(env,e);
+ }
+ if (ctx.shouldComplete()) {
+ break;
+ }
+ }
+ }
+ return s;
+ }
+
/**
* Called prior to selecting the {@link StoreFile}s for compaction from
* the list of currently available candidates.
@@ -389,7 +414,7 @@ public InternalScanner preCompact(Store store, InternalScanner scanner) throws I
* Called after the store compaction has completed.
* @param store the store being compacted
* @param resultFile the new store file written during compaction
- * @throws IOException
+ * @throws IOException
*/
public void postCompact(Store store, StoreFile resultFile) throws IOException {
ObserverContext<RegionCoprocessorEnvironment> ctx = null;
@@ -408,6 +433,31 @@ public void postCompact(Store store, StoreFile resultFile) throws IOException {
}
}
+ /**
+ * Invoked before a memstore flush
+ * @throws IOException
+ */
+ public InternalScanner preFlush(Store store, InternalScanner scanner) throws IOException {
+ ObserverContext<RegionCoprocessorEnvironment> ctx = null;
+ boolean bypass = false;
+ for (RegionEnvironment env: coprocessors) {
+ if (env.getInstance() instanceof RegionObserver) {
+ ctx = ObserverContext.createAndPrepare(env, ctx);
+ try {
+ scanner = ((RegionObserver)env.getInstance()).preFlush(
+ ctx, store, scanner);
+ } catch (Throwable e) {
+ handleCoprocessorThrowable(env,e);
+ }
+ bypass |= ctx.shouldBypass();
+ if (ctx.shouldComplete()) {
+ break;
+ }
+ }
+ }
+ return bypass ? null : scanner;
+ }
+
/**
* Invoked before a memstore flush
* @throws IOException
@@ -429,9 +479,32 @@ public void preFlush() throws IOException {
}
}
+ /**
+ * See
+ * {@link RegionObserver#preFlush(ObserverContext, Store, KeyValueScanner)}
+ */
+ public InternalScanner preFlushScannerOpen(Store store, KeyValueScanner memstoreScanner) throws IOException {
+ ObserverContext<RegionCoprocessorEnvironment> ctx = null;
+ InternalScanner s = null;
+ for (RegionEnvironment env : coprocessors) {
+ if (env.getInstance() instanceof RegionObserver) {
+ ctx = ObserverContext.createAndPrepare(env, ctx);
+ try {
+ s = ((RegionObserver) env.getInstance()).preFlushScannerOpen(ctx, store, memstoreScanner, s);
+ } catch (Throwable e) {
+ handleCoprocessorThrowable(env, e);
+ }
+ if (ctx.shouldComplete()) {
+ break;
+ }
+ }
+ }
+ return s;
+ }
+
/**
* Invoked after a memstore flush
- * @throws IOException
+ * @throws IOException
*/
public void postFlush() throws IOException {
ObserverContext<RegionCoprocessorEnvironment> ctx = null;
@@ -450,9 +523,30 @@ public void postFlush() throws IOException {
}
}
+ /**
+ * Invoked after a memstore flush
+ * @throws IOException
+ */
+ public void postFlush(final Store store, final StoreFile storeFile) throws IOException {
+ ObserverContext<RegionCoprocessorEnvironment> ctx = null;
+ for (RegionEnvironment env: coprocessors) {
+ if (env.getInstance() instanceof RegionObserver) {
+ ctx = ObserverContext.createAndPrepare(env, ctx);
+ try {
+ ((RegionObserver)env.getInstance()).postFlush(ctx, store, storeFile);
+ } catch (Throwable e) {
+ handleCoprocessorThrowable(env, e);
+ }
+ if (ctx.shouldComplete()) {
+ break;
+ }
+ }
+ }
+ }
+
/**
* Invoked just before a split
- * @throws IOException
+ * @throws IOException
*/
public void preSplit() throws IOException {
ObserverContext<RegionCoprocessorEnvironment> ctx = null;
@@ -1088,6 +1182,31 @@ public RegionScanner preScannerOpen(Scan scan) throws IOException {
return bypass ? s : null;
}
+ /**
+ * See
+ * {@link RegionObserver#preStoreScannerOpen(ObserverContext, Store, Scan, NavigableSet, KeyValueScanner)}
+ */
+ public KeyValueScanner preStoreScannerOpen(Store store, Scan scan,
+ final NavigableSet<byte[]> targetCols) throws IOException {
+ KeyValueScanner s = null;
+ ObserverContext<RegionCoprocessorEnvironment> ctx = null;
+ for (RegionEnvironment env: coprocessors) {
+ if (env.getInstance() instanceof RegionObserver) {
+ ctx = ObserverContext.createAndPrepare(env, ctx);
+ try {
+ s = ((RegionObserver) env.getInstance()).preStoreScannerOpen(ctx, store, scan,
+ targetCols, s);
+ } catch (Throwable e) {
+ handleCoprocessorThrowable(env, e);
+ }
+ if (ctx.shouldComplete()) {
+ break;
+ }
+ }
+ }
+ return s;
+ }
+
/**
* @param scan the Scan specification
* @param s the scanner
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java
index 20e297864851..f02afd7171b1 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java
@@ -34,8 +34,6 @@
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
-import org.apache.hadoop.hbase.regionserver.StoreScanner.ScanType;
-
/**
* A query matcher that is specifically designed for the scan case.
*/
@@ -138,7 +136,7 @@ public class ScanQueryMatcher {
* based on TTL
*/
public ScanQueryMatcher(Scan scan, Store.ScanInfo scanInfo,
- NavigableSet<byte[]> columns, StoreScanner.ScanType scanType,
+ NavigableSet<byte[]> columns, ScanType scanType,
long readPointToUse, long earliestPutTs, long oldestUnexpiredTS) {
this.tr = scan.getTimeRange();
this.rowComparator = scanInfo.getComparator().getRawComparator();
@@ -185,7 +183,7 @@ public ScanQueryMatcher(Scan scan, Store.ScanInfo scanInfo,
*/
ScanQueryMatcher(Scan scan, Store.ScanInfo scanInfo,
NavigableSet<byte[]> columns, long oldestUnexpiredTS) {
- this(scan, scanInfo, columns, StoreScanner.ScanType.USER_SCAN,
+ this(scan, scanInfo, columns, ScanType.USER_SCAN,
Long.MAX_VALUE, /* max Readpoint to track versions */
HConstants.LATEST_TIMESTAMP, oldestUnexpiredTS);
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanType.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanType.java
new file mode 100644
index 000000000000..7b075120cbee
--- /dev/null
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/ScanType.java
@@ -0,0 +1,30 @@
+/*
+ * 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.hbase.regionserver;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+
+/**
+ * Enum to distinguish general scan types.
+ */
[email protected]
+public enum ScanType {
+ MAJOR_COMPACT,
+ MINOR_COMPACT,
+ USER_SCAN
+}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java
index 3f5d76c06037..87a1c13f88d9 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java
@@ -63,7 +63,6 @@
import org.apache.hadoop.hbase.io.hfile.InvalidHFileException;
import org.apache.hadoop.hbase.io.hfile.NoOpDataBlockEncoder;
import org.apache.hadoop.hbase.monitoring.MonitoredTask;
-import org.apache.hadoop.hbase.regionserver.StoreScanner.ScanType;
import org.apache.hadoop.hbase.regionserver.compactions.CompactSelection;
import org.apache.hadoop.hbase.regionserver.compactions.CompactionProgress;
import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;
@@ -212,9 +211,7 @@ protected Store(Path basedir, HRegion region, HColumnDescriptor family,
"ms in store " + this);
// Why not just pass a HColumnDescriptor in here altogether? Even if have
// to clone it?
- scanInfo = new ScanInfo(family.getName(), family.getMinVersions(),
- family.getMaxVersions(), ttl, family.getKeepDeletedCells(),
- timeToPurgeDeletes, this.comparator);
+ scanInfo = new ScanInfo(family, ttl, timeToPurgeDeletes, this.comparator);
this.memstore = new MemStore(conf, this.comparator);
// By default, compact if storefile.count >= minFilesToCompact
@@ -728,15 +725,30 @@ private Path internalFlushCache(final SortedSet<KeyValue> set,
if (set.size() == 0) {
return null;
}
- Scan scan = new Scan();
- scan.setMaxVersions(scanInfo.getMaxVersions());
// Use a store scanner to find which rows to flush.
// Note that we need to retain deletes, hence
// treat this as a minor compaction.
- InternalScanner scanner = new StoreScanner(this, scan, Collections
- .singletonList(new CollectionBackedScanner(set, this.comparator)),
- ScanType.MINOR_COMPACT, this.region.getSmallestReadPoint(),
- HConstants.OLDEST_TIMESTAMP);
+ InternalScanner scanner = null;
+ KeyValueScanner memstoreScanner = new CollectionBackedScanner(set, this.comparator);
+ if (getHRegion().getCoprocessorHost() != null) {
+ scanner = getHRegion().getCoprocessorHost().preFlushScannerOpen(this, memstoreScanner);
+ }
+ if (scanner == null) {
+ Scan scan = new Scan();
+ scan.setMaxVersions(scanInfo.getMaxVersions());
+ scanner = new StoreScanner(this, scanInfo, scan, Collections.singletonList(new CollectionBackedScanner(
+ set, this.comparator)), ScanType.MINOR_COMPACT, this.region.getSmallestReadPoint(),
+ HConstants.OLDEST_TIMESTAMP);
+ }
+ if (getHRegion().getCoprocessorHost() != null) {
+ InternalScanner cpScanner =
+ getHRegion().getCoprocessorHost().preFlush(this, scanner);
+ // NULL scanner returned from coprocessor hooks means skip normal processing
+ if (cpScanner == null) {
+ return null;
+ }
+ scanner = cpScanner;
+ }
try {
// TODO: We can fail in the below block before we complete adding this
// flush to list of store files. Add cleanup of anything put on filesystem
@@ -1941,11 +1953,18 @@ boolean getForceMajorCompaction() {
* are not in a compaction.
* @throws IOException
*/
- public StoreScanner getScanner(Scan scan,
+ public KeyValueScanner getScanner(Scan scan,
final NavigableSet<byte []> targetCols) throws IOException {
lock.readLock().lock();
try {
- return new StoreScanner(this, scan, targetCols);
+ KeyValueScanner scanner = null;
+ if (getHRegion().getCoprocessorHost() != null) {
+ scanner = getHRegion().getCoprocessorHost().preStoreScannerOpen(this, scan, targetCols);
+ }
+ if (scanner == null) {
+ scanner = new StoreScanner(this, getScanInfo(), scan, targetCols);
+ }
+ return scanner;
} finally {
lock.readLock().unlock();
}
@@ -2065,7 +2084,7 @@ boolean throttleCompaction(long compactionSize) {
return compactionSize > throttlePoint;
}
- HRegion getHRegion() {
+ public HRegion getHRegion() {
return this.region;
}
@@ -2168,6 +2187,12 @@ public boolean commit(MonitoredTask status) throws IOException {
}
storeFile = Store.this.commitFile(storeFilePath, cacheFlushId,
snapshotTimeRangeTracker, flushedSize, status);
+ if (Store.this.getHRegion().getCoprocessorHost() != null) {
+ Store.this.getHRegion()
+ .getCoprocessorHost()
+ .postFlush(Store.this, storeFile);
+ }
+
// Add new file to store files. Clear snapshot too while we have
// the Store write lock.
return Store.this.updateStorefiles(storeFile, snapshot);
@@ -2210,6 +2235,10 @@ public KeyValue.KVComparator getComparator() {
return comparator;
}
+ public ScanInfo getScanInfo() {
+ return scanInfo;
+ }
+
/**
* Immutable information for scans over a store.
*/
@@ -2226,6 +2255,17 @@ public static class ScanInfo {
+ (2 * ClassSize.REFERENCE) + (2 * Bytes.SIZEOF_INT)
+ Bytes.SIZEOF_LONG + Bytes.SIZEOF_BOOLEAN);
+ /**
+ * @param family {@link HColumnDescriptor} describing the column family
+ * @param ttl Store's TTL (in ms)
+ * @param timeToPurgeDeletes duration in ms after which a delete marker can
+ * be purged during a major compaction.
+ * @param comparator The store's comparator
+ */
+ public ScanInfo(HColumnDescriptor family, long ttl, long timeToPurgeDeletes, KVComparator comparator) {
+ this(family.getName(), family.getMinVersions(), family.getMaxVersions(), ttl, family
+ .getKeepDeletedCells(), timeToPurgeDeletes, comparator);
+ }
/**
* @param family Name of this store's column family
* @param minVersions Store's MIN_VERSIONS setting
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java
index a46cb72ab5e4..cad774130e92 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java
@@ -33,6 +33,7 @@
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.Filter;
+import org.apache.hadoop.hbase.regionserver.Store.ScanInfo;
import org.apache.hadoop.hbase.regionserver.metrics.RegionMetricsStorage;
import org.apache.hadoop.hbase.regionserver.metrics.SchemaMetrics;
import org.apache.hadoop.hbase.util.Bytes;
@@ -43,7 +44,7 @@
* into List<KeyValue> for a single row.
*/
@InterfaceAudience.Private
-class StoreScanner extends NonLazyKeyValueScanner
+public class StoreScanner extends NonLazyKeyValueScanner
implements KeyValueScanner, InternalScanner, ChangedReadersObserver {
static final Log LOG = LogFactory.getLog(StoreScanner.class);
private Store store;
@@ -106,16 +107,16 @@ private StoreScanner(Store store, boolean cacheBlocks, Scan scan,
* @param columns which columns we are scanning
* @throws IOException
*/
- StoreScanner(Store store, Scan scan, final NavigableSet<byte[]> columns)
+ public StoreScanner(Store store, ScanInfo scanInfo, Scan scan, final NavigableSet<byte[]> columns)
throws IOException {
- this(store, scan.getCacheBlocks(), scan, columns, store.scanInfo.getTtl(),
- store.scanInfo.getMinVersions());
+ this(store, scan.getCacheBlocks(), scan, columns, scanInfo.getTtl(),
+ scanInfo.getMinVersions());
initializeMetricNames();
if (columns != null && scan.isRaw()) {
throw new DoNotRetryIOException(
"Cannot specify any column for a raw scan");
}
- matcher = new ScanQueryMatcher(scan, store.scanInfo, columns,
+ matcher = new ScanQueryMatcher(scan, scanInfo, columns,
ScanType.USER_SCAN, Long.MAX_VALUE, HConstants.LATEST_TIMESTAMP,
oldestUnexpiredTS);
@@ -158,13 +159,13 @@ private StoreScanner(Store store, boolean cacheBlocks, Scan scan,
* @param smallestReadPoint the readPoint that we should use for tracking
* versions
*/
- StoreScanner(Store store, Scan scan,
+ public StoreScanner(Store store, ScanInfo scanInfo, Scan scan,
List<? extends KeyValueScanner> scanners, ScanType scanType,
long smallestReadPoint, long earliestPutTs) throws IOException {
- this(store, false, scan, null, store.scanInfo.getTtl(),
- store.scanInfo.getMinVersions());
+ this(store, false, scan, null, scanInfo.getTtl(),
+ scanInfo.getMinVersions());
initializeMetricNames();
- matcher = new ScanQueryMatcher(scan, store.scanInfo, null, scanType,
+ matcher = new ScanQueryMatcher(scan, scanInfo, null, scanType,
smallestReadPoint, earliestPutTs, oldestUnexpiredTS);
// Filter the list of scanners using Bloom filters, time range, TTL, etc.
@@ -181,7 +182,7 @@ private StoreScanner(Store store, boolean cacheBlocks, Scan scan,
/** Constructor for testing. */
StoreScanner(final Scan scan, Store.ScanInfo scanInfo,
- StoreScanner.ScanType scanType, final NavigableSet<byte[]> columns,
+ ScanType scanType, final NavigableSet<byte[]> columns,
final List<KeyValueScanner> scanners) throws IOException {
this(scan, scanInfo, scanType, columns, scanners,
HConstants.LATEST_TIMESTAMP);
@@ -189,7 +190,7 @@ private StoreScanner(Store store, boolean cacheBlocks, Scan scan,
// Constructor for testing.
StoreScanner(final Scan scan, Store.ScanInfo scanInfo,
- StoreScanner.ScanType scanType, final NavigableSet<byte[]> columns,
+ ScanType scanType, final NavigableSet<byte[]> columns,
final List<KeyValueScanner> scanners, long earliestPutTs)
throws IOException {
this(null, scan.getCacheBlocks(), scan, columns, scanInfo.getTtl(),
@@ -598,14 +599,5 @@ List<KeyValueScanner> getAllScannersForTesting() {
static void enableLazySeekGlobally(boolean enable) {
lazySeekEnabledGlobally = enable;
}
-
- /**
- * Enum to distinguish general scan types.
- */
- public static enum ScanType {
- MAJOR_COMPACT,
- MINOR_COMPACT,
- USER_SCAN
- }
}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
index fc4fe2e4f6f7..767202e11677 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
@@ -788,6 +788,22 @@ public void flush(byte [] tableName) throws IOException {
this.hbaseCluster.flushcache(tableName);
}
+ /**
+ * Compact all regions in the mini hbase cluster
+ * @throws IOException
+ */
+ public void compact(boolean major) throws IOException {
+ this.hbaseCluster.compact(major);
+ }
+
+ /**
+ * Compact all of a table's reagion in the mini hbase cluster
+ * @throws IOException
+ */
+ public void compact(byte [] tableName, boolean major) throws IOException {
+ this.hbaseCluster.compact(tableName, major);
+ }
+
/**
* Create a table.
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/MiniHBaseCluster.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/MiniHBaseCluster.java
index c7442ae57a29..e5743036730e 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/MiniHBaseCluster.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/MiniHBaseCluster.java
@@ -454,6 +454,34 @@ public void flushcache(byte [] tableName) throws IOException {
}
}
+ /**
+ * Call flushCache on all regions on all participating regionservers.
+ * @throws IOException
+ */
+ public void compact(boolean major) throws IOException {
+ for (JVMClusterUtil.RegionServerThread t:
+ this.hbaseCluster.getRegionServers()) {
+ for(HRegion r: t.getRegionServer().getOnlineRegionsLocalContext()) {
+ r.compactStores(major);
+ }
+ }
+ }
+
+ /**
+ * Call flushCache on all regions of the specified table.
+ * @throws IOException
+ */
+ public void compact(byte [] tableName, boolean major) throws IOException {
+ for (JVMClusterUtil.RegionServerThread t:
+ this.hbaseCluster.getRegionServers()) {
+ for(HRegion r: t.getRegionServer().getOnlineRegionsLocalContext()) {
+ if(Bytes.equals(r.getTableDesc().getName(), tableName)) {
+ r.compactStores(major);
+ }
+ }
+ }
+ }
+
/**
* @return List of region server threads.
*/
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
index 2dadc7c93f2b..2b67c5daabd2 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
@@ -90,12 +90,12 @@
@Category(LargeTests.class)
public class TestFromClientSide {
final Log LOG = LogFactory.getLog(getClass());
- private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
+ protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static byte [] ROW = Bytes.toBytes("testRow");
private static byte [] FAMILY = Bytes.toBytes("testFamily");
private static byte [] QUALIFIER = Bytes.toBytes("testQualifier");
private static byte [] VALUE = Bytes.toBytes("testValue");
- private static int SLAVES = 3;
+ protected static int SLAVES = 3;
/**
* @throws java.lang.Exception
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSideWithCoprocessor.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSideWithCoprocessor.java
new file mode 100644
index 000000000000..7b313dc67fac
--- /dev/null
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSideWithCoprocessor.java
@@ -0,0 +1,42 @@
+/*
+ * 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.hbase.client;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.LargeTests;
+import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
+import org.apache.hadoop.hbase.coprocessor.MultiRowMutationEndpoint;
+import org.apache.hadoop.hbase.regionserver.NoOpScanPolicyObserver;
+import org.junit.BeforeClass;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Test all client operations with a coprocessor that
+ * just implements the default flush/compact/scan policy
+ */
+@Category(LargeTests.class)
+public class TestFromClientSideWithCoprocessor extends TestFromClientSide {
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ Configuration conf = TEST_UTIL.getConfiguration();
+ conf.setStrings(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
+ MultiRowMutationEndpoint.class.getName(), NoOpScanPolicyObserver.class.getName());
+ // We need more than one region server in this test
+ TEST_UTIL.startMiniCluster(SLAVES);
+ }
+}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/SimpleRegionObserver.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/SimpleRegionObserver.java
index a691bacc4366..119a4878e985 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/SimpleRegionObserver.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/SimpleRegionObserver.java
@@ -29,6 +29,7 @@
import java.util.List;
import java.util.Map;
import java.util.Arrays;
+import java.util.NavigableSet;
import com.google.common.collect.ImmutableList;
import org.apache.commons.logging.Log;
@@ -42,7 +43,9 @@
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.InternalScanner;
+import org.apache.hadoop.hbase.regionserver.KeyValueScanner;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
+import org.apache.hadoop.hbase.regionserver.ScanType;
import org.apache.hadoop.hbase.regionserver.Store;
import org.apache.hadoop.hbase.regionserver.StoreFile;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
@@ -63,11 +66,13 @@ public class SimpleRegionObserver extends BaseRegionObserver {
boolean hadPreClose;
boolean hadPostClose;
boolean hadPreFlush;
+ boolean hadPreFlushScannerOpen;
boolean hadPostFlush;
boolean hadPreSplit;
boolean hadPostSplit;
boolean hadPreCompactSelect;
boolean hadPostCompactSelect;
+ boolean hadPreCompactScanner;
boolean hadPreCompact;
boolean hadPostCompact;
boolean hadPreGet = false;
@@ -87,6 +92,7 @@ public class SimpleRegionObserver extends BaseRegionObserver {
boolean hadPreScannerClose = false;
boolean hadPostScannerClose = false;
boolean hadPreScannerOpen = false;
+ boolean hadPreStoreScannerOpen = false;
boolean hadPostScannerOpen = false;
boolean hadPreBulkLoadHFile = false;
boolean hadPostBulkLoadHFile = false;
@@ -120,12 +126,20 @@ public boolean wasClosed() {
}
@Override
- public void preFlush(ObserverContext<RegionCoprocessorEnvironment> c) {
+ public InternalScanner preFlush(ObserverContext<RegionCoprocessorEnvironment> c, Store store, InternalScanner scanner) {
hadPreFlush = true;
+ return scanner;
}
@Override
- public void postFlush(ObserverContext<RegionCoprocessorEnvironment> c) {
+ public InternalScanner preFlushScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ Store store, KeyValueScanner memstoreScanner, InternalScanner s) throws IOException {
+ hadPreFlushScannerOpen = true;
+ return null;
+ }
+
+ @Override
+ public void postFlush(ObserverContext<RegionCoprocessorEnvironment> c, Store store, StoreFile resultFile) {
hadPostFlush = true;
}
@@ -166,6 +180,14 @@ public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment>
return scanner;
}
+ @Override
+ public InternalScanner preCompactScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ Store store, List<? extends KeyValueScanner> scanners, ScanType scanType, long earliestPutTs,
+ InternalScanner s) throws IOException {
+ hadPreCompactScanner = true;
+ return null;
+ }
+
@Override
public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e,
Store store, StoreFile resultFile) {
@@ -184,6 +206,14 @@ public RegionScanner preScannerOpen(final ObserverContext<RegionCoprocessorEnvir
return null;
}
+ @Override
+ public KeyValueScanner preStoreScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ final Store store, final Scan scan, final NavigableSet<byte[]> targetCols,
+ final KeyValueScanner s) throws IOException {
+ hadPreStoreScannerOpen = true;
+ return null;
+ }
+
@Override
public RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
final Scan scan, final RegionScanner s)
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/HFileReadWriteTest.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/HFileReadWriteTest.java
index ebc5373e2248..e6ff17305eca 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/HFileReadWriteTest.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/HFileReadWriteTest.java
@@ -61,7 +61,6 @@
import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoderImpl;
import org.apache.hadoop.hbase.io.hfile.HFilePrettyPrinter;
import org.apache.hadoop.hbase.io.hfile.NoOpDataBlockEncoder;
-import org.apache.hadoop.hbase.regionserver.StoreScanner.ScanType;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.LoadTestTool;
import org.apache.hadoop.hbase.util.MD5Hash;
@@ -408,7 +407,7 @@ private void performMerge(List<StoreFileScanner> scanners, Store store,
Scan scan = new Scan();
// Include deletes
- scanner = new StoreScanner(store, scan, scanners,
+ scanner = new StoreScanner(store, store.scanInfo, scan, scanners,
ScanType.MAJOR_COMPACT, Long.MIN_VALUE, Long.MIN_VALUE);
ArrayList<KeyValue> kvs = new ArrayList<KeyValue>();
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/NoOpScanPolicyObserver.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/NoOpScanPolicyObserver.java
new file mode 100644
index 000000000000..668c04372c20
--- /dev/null
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/NoOpScanPolicyObserver.java
@@ -0,0 +1,62 @@
+package org.apache.hadoop.hbase.regionserver;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.NavigableSet;
+
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.client.TestFromClientSideWithCoprocessor;
+import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
+import org.apache.hadoop.hbase.coprocessor.ObserverContext;
+import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
+
+/**
+ * RegionObserver that just reimplements the default behavior,
+ * in order to validate that all the necessary APIs for this are public
+ * This observer is also used in {@link TestFromClientSideWithCoprocessor} and
+ * {@link TestCompactionWithCoprocessor} to make sure that a wide range
+ * of functionality still behaves as expected.
+ */
+public class NoOpScanPolicyObserver extends BaseRegionObserver {
+ /**
+ * Reimplement the default behavior
+ */
+ @Override
+ public InternalScanner preFlushScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ Store store, KeyValueScanner memstoreScanner, InternalScanner s) throws IOException {
+ Store.ScanInfo oldSI = store.getScanInfo();
+ Store.ScanInfo scanInfo = new Store.ScanInfo(store.getFamily(), oldSI.getTtl(),
+ oldSI.getTimeToPurgeDeletes(), oldSI.getComparator());
+ Scan scan = new Scan();
+ scan.setMaxVersions(oldSI.getMaxVersions());
+ return new StoreScanner(store, scanInfo, scan, Collections.singletonList(memstoreScanner),
+ ScanType.MINOR_COMPACT, store.getHRegion().getSmallestReadPoint(),
+ HConstants.OLDEST_TIMESTAMP);
+ }
+
+ /**
+ * Reimplement the default behavior
+ */
+ @Override
+ public InternalScanner preCompactScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ Store store, List<? extends KeyValueScanner> scanners, ScanType scanType, long earliestPutTs,
+ InternalScanner s) throws IOException {
+ // this demonstrates how to override the scanners default behavior
+ Store.ScanInfo oldSI = store.getScanInfo();
+ Store.ScanInfo scanInfo = new Store.ScanInfo(store.getFamily(), oldSI.getTtl(),
+ oldSI.getTimeToPurgeDeletes(), oldSI.getComparator());
+ Scan scan = new Scan();
+ scan.setMaxVersions(oldSI.getMaxVersions());
+ return new StoreScanner(store, scanInfo, scan, scanners, scanType, store.getHRegion()
+ .getSmallestReadPoint(), earliestPutTs);
+ }
+
+ @Override
+ public KeyValueScanner preStoreScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ Store store, final Scan scan, final NavigableSet<byte[]> targetCols, KeyValueScanner s)
+ throws IOException {
+ return new StoreScanner(store, store.getScanInfo(), scan, targetCols);
+ }
+}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestCompactionWithCoprocessor.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestCompactionWithCoprocessor.java
new file mode 100644
index 000000000000..ba30a9fdf388
--- /dev/null
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestCompactionWithCoprocessor.java
@@ -0,0 +1,36 @@
+/*
+ * 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.hbase.regionserver;
+
+import org.apache.hadoop.hbase.MediumTests;
+import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
+import org.junit.experimental.categories.Category;
+
+/**
+ * Make sure all compaction tests still pass with the preFlush and preCompact
+ * overridden to implement the default behavior
+ */
+@Category(MediumTests.class)
+public class TestCompactionWithCoprocessor extends TestCompaction {
+ /** constructor */
+ public TestCompactionWithCoprocessor() throws Exception {
+ super();
+ conf.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
+ NoOpScanPolicyObserver.class.getName());
+ }
+}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestMemStore.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestMemStore.java
index 8e8ae45a5a7f..0da62dfc17c4 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestMemStore.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestMemStore.java
@@ -36,7 +36,6 @@
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.regionserver.Store.ScanInfo;
-import org.apache.hadoop.hbase.regionserver.StoreScanner.ScanType;
import org.apache.hadoop.hbase.regionserver.metrics.SchemaMetrics;
import org.apache.hadoop.hbase.util.Bytes;
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestStoreScanner.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestStoreScanner.java
index 3c582338e69b..01f0731549f2 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestStoreScanner.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestStoreScanner.java
@@ -38,7 +38,6 @@
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.regionserver.Store.ScanInfo;
-import org.apache.hadoop.hbase.regionserver.StoreScanner.ScanType;
import org.apache.hadoop.hbase.regionserver.metrics.SchemaMetrics;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdge;
@@ -559,7 +558,7 @@ public long currentTimeMillis() {
KeyValue.COMPARATOR);
StoreScanner scanner =
new StoreScanner(scan, scanInfo,
- StoreScanner.ScanType.MAJOR_COMPACT, null, scanners,
+ ScanType.MAJOR_COMPACT, null, scanners,
HConstants.OLDEST_TIMESTAMP);
List<KeyValue> results = new ArrayList<KeyValue>();
results = new ArrayList<KeyValue>();
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestCoprocessorScanPolicy.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestCoprocessorScanPolicy.java
new file mode 100644
index 000000000000..1915ca372762
--- /dev/null
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestCoprocessorScanPolicy.java
@@ -0,0 +1,262 @@
+/*
+ * 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.hbase.util;
+// this is deliberately not in the o.a.h.h.regionserver package
+// in order to make sure all required classes/method are available
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableSet;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HBaseTestingUtility;
+import org.apache.hadoop.hbase.HColumnDescriptor;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.MediumTests;
+import org.apache.hadoop.hbase.client.Get;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
+import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
+import org.apache.hadoop.hbase.coprocessor.ObserverContext;
+import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
+import org.apache.hadoop.hbase.regionserver.InternalScanner;
+import org.apache.hadoop.hbase.regionserver.KeyValueScanner;
+import org.apache.hadoop.hbase.regionserver.ScanType;
+import org.apache.hadoop.hbase.regionserver.Store;
+import org.apache.hadoop.hbase.regionserver.StoreScanner;
+import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.junit.Assert.*;
+
+@Category(MediumTests.class)
+public class TestCoprocessorScanPolicy {
+ final Log LOG = LogFactory.getLog(getClass());
+ protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
+ private static final byte[] F = Bytes.toBytes("fam");
+ private static final byte[] Q = Bytes.toBytes("qual");
+ private static final byte[] R = Bytes.toBytes("row");
+
+
+ @BeforeClass
+ public static void setUpBeforeClass() throws Exception {
+ Configuration conf = TEST_UTIL.getConfiguration();
+ conf.setStrings(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
+ ScanObserver.class.getName());
+ TEST_UTIL.startMiniCluster();
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ TEST_UTIL.shutdownMiniCluster();
+ }
+
+ @Test
+ public void testBaseCases() throws Exception {
+ byte[] tableName = Bytes.toBytes("baseCases");
+ HTable t = TEST_UTIL.createTable(tableName, F, 1);
+ // set the version override to 2
+ Put p = new Put(R);
+ p.setAttribute("versions", new byte[]{});
+ p.add(F, tableName, Bytes.toBytes(2));
+ t.put(p);
+
+ // insert 2 versions
+ p = new Put(R);
+ p.add(F, Q, Q);
+ t.put(p);
+ p = new Put(R);
+ p.add(F, Q, Q);
+ t.put(p);
+ Get g = new Get(R);
+ g.setMaxVersions(10);
+ Result r = t.get(g);
+ assertEquals(2, r.size());
+
+ TEST_UTIL.flush(tableName);
+ TEST_UTIL.compact(tableName, true);
+
+ // both version are still visible even after a flush/compaction
+ g = new Get(R);
+ g.setMaxVersions(10);
+ r = t.get(g);
+ assertEquals(2, r.size());
+
+ // insert a 3rd version
+ p = new Put(R);
+ p.add(F, Q, Q);
+ t.put(p);
+ g = new Get(R);
+ g.setMaxVersions(10);
+ r = t.get(g);
+ // still only two version visible
+ assertEquals(2, r.size());
+
+ t.close();
+ }
+
+ @Test
+ public void testTTL() throws Exception {
+ byte[] tableName = Bytes.toBytes("testTTL");
+ HTableDescriptor desc = new HTableDescriptor(tableName);
+ HColumnDescriptor hcd = new HColumnDescriptor(F)
+ .setMaxVersions(10)
+ .setTimeToLive(1);
+ desc.addFamily(hcd);
+ TEST_UTIL.getHBaseAdmin().createTable(desc);
+ HTable t = new HTable(new Configuration(TEST_UTIL.getConfiguration()), tableName);
+ long now = EnvironmentEdgeManager.currentTimeMillis();
+ ManualEnvironmentEdge me = new ManualEnvironmentEdge();
+ me.setValue(now);
+ EnvironmentEdgeManagerTestHelper.injectEdge(me);
+ // 2s in the past
+ long ts = now - 2000;
+ // Set the TTL override to 3s
+ Put p = new Put(R);
+ p.setAttribute("ttl", new byte[]{});
+ p.add(F, tableName, Bytes.toBytes(3000L));
+ t.put(p);
+
+ p = new Put(R);
+ p.add(F, Q, ts, Q);
+ t.put(p);
+ p = new Put(R);
+ p.add(F, Q, ts+1, Q);
+ t.put(p);
+
+ // these two should be expired but for the override
+ // (their ts was 2s in the past)
+ Get g = new Get(R);
+ g.setMaxVersions(10);
+ Result r = t.get(g);
+ // still there?
+ assertEquals(2, r.size());
+
+ TEST_UTIL.flush(tableName);
+ TEST_UTIL.compact(tableName, true);
+
+ g = new Get(R);
+ g.setMaxVersions(10);
+ r = t.get(g);
+ // still there?
+ assertEquals(2, r.size());
+
+ // roll time forward 2s.
+ me.setValue(now + 2000);
+ // now verify that data eventually does expire
+ g = new Get(R);
+ g.setMaxVersions(10);
+ r = t.get(g);
+ // should be gone now
+ assertEquals(0, r.size());
+ t.close();
+ }
+
+ public static class ScanObserver extends BaseRegionObserver {
+ private Map<String, Long> ttls = new HashMap<String,Long>();
+ private Map<String, Integer> versions = new HashMap<String,Integer>();
+
+ // lame way to communicate with the coprocessor,
+ // since it is loaded by a different class loader
+ @Override
+ public void prePut(final ObserverContext<RegionCoprocessorEnvironment> c, final Put put,
+ final WALEdit edit, final boolean writeToWAL) throws IOException {
+ if (put.getAttribute("ttl") != null) {
+ KeyValue kv = put.getFamilyMap().values().iterator().next().get(0);
+ ttls.put(Bytes.toString(kv.getQualifier()), Bytes.toLong(kv.getValue()));
+ c.bypass();
+ } else if (put.getAttribute("versions") != null) {
+ KeyValue kv = put.getFamilyMap().values().iterator().next().get(0);
+ versions.put(Bytes.toString(kv.getQualifier()), Bytes.toInt(kv.getValue()));
+ c.bypass();
+ }
+ }
+
+ @Override
+ public InternalScanner preFlushScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ Store store, KeyValueScanner memstoreScanner, InternalScanner s) throws IOException {
+ Long newTtl = ttls.get(store.getTableName());
+ if (newTtl != null) {
+ System.out.println("PreFlush:" + newTtl);
+ }
+ Integer newVersions = versions.get(store.getTableName());
+ Store.ScanInfo oldSI = store.getScanInfo();
+ HColumnDescriptor family = store.getFamily();
+ Store.ScanInfo scanInfo = new Store.ScanInfo(family.getName(), family.getMinVersions(),
+ newVersions == null ? family.getMaxVersions() : newVersions,
+ newTtl == null ? oldSI.getTtl() : newTtl, family.getKeepDeletedCells(),
+ oldSI.getTimeToPurgeDeletes(), oldSI.getComparator());
+ Scan scan = new Scan();
+ scan.setMaxVersions(newVersions == null ? oldSI.getMaxVersions() : newVersions);
+ return new StoreScanner(store, scanInfo, scan, Collections.singletonList(memstoreScanner),
+ ScanType.MINOR_COMPACT, store.getHRegion().getSmallestReadPoint(),
+ HConstants.OLDEST_TIMESTAMP);
+ }
+
+ @Override
+ public InternalScanner preCompactScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
+ Store store, List<? extends KeyValueScanner> scanners, ScanType scanType,
+ long earliestPutTs, InternalScanner s) throws IOException {
+ Long newTtl = ttls.get(store.getTableName());
+ Integer newVersions = versions.get(store.getTableName());
+ Store.ScanInfo oldSI = store.getScanInfo();
+ HColumnDescriptor family = store.getFamily();
+ Store.ScanInfo scanInfo = new Store.ScanInfo(family.getName(), family.getMinVersions(),
+ newVersions == null ? family.getMaxVersions() : newVersions,
+ newTtl == null ? oldSI.getTtl() : newTtl, family.getKeepDeletedCells(),
+ oldSI.getTimeToPurgeDeletes(), oldSI.getComparator());
+ Scan scan = new Scan();
+ scan.setMaxVersions(newVersions == null ? oldSI.getMaxVersions() : newVersions);
+ return new StoreScanner(store, scanInfo, scan, scanners, scanType, store.getHRegion()
+ .getSmallestReadPoint(), earliestPutTs);
+ }
+
+ @Override
+ public KeyValueScanner preStoreScannerOpen(
+ final ObserverContext<RegionCoprocessorEnvironment> c, Store store, final Scan scan,
+ final NavigableSet<byte[]> targetCols, KeyValueScanner s) throws IOException {
+ Long newTtl = ttls.get(store.getTableName());
+ Integer newVersions = versions.get(store.getTableName());
+ Store.ScanInfo oldSI = store.getScanInfo();
+ HColumnDescriptor family = store.getFamily();
+ Store.ScanInfo scanInfo = new Store.ScanInfo(family.getName(), family.getMinVersions(),
+ newVersions == null ? family.getMaxVersions() : newVersions,
+ newTtl == null ? oldSI.getTtl() : newTtl, family.getKeepDeletedCells(),
+ oldSI.getTimeToPurgeDeletes(), oldSI.getComparator());
+ return new StoreScanner(store, scanInfo, scan, targetCols);
+ }
+ }
+
+ @org.junit.Rule
+ public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu =
+ new org.apache.hadoop.hbase.ResourceCheckerJUnitRule();
+}
|
9e4c48a9368e640b1c26cf9b7affc403acabd8bf
|
Valadoc
|
basic doclet: Add "wiki-index-name"
Used by valadoc.org
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/html/basicdoclet.vala b/src/libvaladoc/html/basicdoclet.vala
index fceaf906c7..e048f7392b 100644
--- a/src/libvaladoc/html/basicdoclet.vala
+++ b/src/libvaladoc/html/basicdoclet.vala
@@ -36,6 +36,12 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
get;
}
+ public string wiki_index_name {
+ default = "index.valadoc";
+ protected set;
+ get;
+ }
+
protected Api.Tree tree;
protected HtmlRenderer _renderer;
protected Html.MarkupWriter writer;
@@ -233,7 +239,7 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
DirUtils.create (Path.build_filename (contentp, "img"), 0777);
foreach (WikiPage page in pages) {
- if (page.name != "index.valadoc") {
+ if (page.name != wiki_index_name) {
write_wiki_page (page, contentp, css_path_wiki, js_path_wiki, this.settings.pkg_name);
}
}
@@ -573,7 +579,7 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
WikiPage? wikiindex = (tree.wikitree == null)
? null
- : tree.wikitree.search ("index.valadoc");
+ : tree.wikitree.search (wiki_index_name);
if (wikiindex != null) {
_renderer.set_container (wikiindex);
_renderer.render (wikiindex.documentation);
@@ -1062,7 +1068,7 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
.end_tag ("h2");
- WikiPage? wikipage = (tree.wikitree == null)? null : tree.wikitree.search ("index.valadoc");
+ WikiPage? wikipage = (tree.wikitree == null)? null : tree.wikitree.search (wiki_index_name);
if (wikipage != null) {
_renderer.set_container (parent);
_renderer.render (wikipage.documentation);
|
cef0b916c546bf6178b493eafc1ea4adb0357e18
|
ReactiveX-RxJava
|
1.x: ConcatMapEager allow nulls from inner- Observables.--
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/src/main/java/rx/internal/operators/OperatorEagerConcatMap.java b/src/main/java/rx/internal/operators/OperatorEagerConcatMap.java
index 4df115b7ae..bbf2bcc48b 100644
--- a/src/main/java/rx/internal/operators/OperatorEagerConcatMap.java
+++ b/src/main/java/rx/internal/operators/OperatorEagerConcatMap.java
@@ -166,6 +166,7 @@ void drain() {
final AtomicLong requested = sharedProducer;
final Subscriber<? super R> actualSubscriber = this.actual;
+ final NotificationLite<R> nl = NotificationLite.instance();
for (;;) {
@@ -200,13 +201,13 @@ void drain() {
long emittedAmount = 0L;
boolean unbounded = requestedAmount == Long.MAX_VALUE;
- Queue<R> innerQueue = innerSubscriber.queue;
+ Queue<Object> innerQueue = innerSubscriber.queue;
boolean innerDone = false;
for (;;) {
outerDone = innerSubscriber.done;
- R v = innerQueue.peek();
+ Object v = innerQueue.peek();
empty = v == null;
if (outerDone) {
@@ -237,7 +238,7 @@ void drain() {
innerQueue.poll();
try {
- actualSubscriber.onNext(v);
+ actualSubscriber.onNext(nl.getValue(v));
} catch (Throwable ex) {
Exceptions.throwOrReport(ex, actualSubscriber, v);
return;
@@ -271,7 +272,8 @@ void drain() {
static final class EagerInnerSubscriber<T> extends Subscriber<T> {
final EagerOuterSubscriber<?, T> parent;
- final Queue<T> queue;
+ final Queue<Object> queue;
+ final NotificationLite<T> nl;
volatile boolean done;
Throwable error;
@@ -279,19 +281,20 @@ static final class EagerInnerSubscriber<T> extends Subscriber<T> {
public EagerInnerSubscriber(EagerOuterSubscriber<?, T> parent, int bufferSize) {
super();
this.parent = parent;
- Queue<T> q;
+ Queue<Object> q;
if (UnsafeAccess.isUnsafeAvailable()) {
- q = new SpscArrayQueue<T>(bufferSize);
+ q = new SpscArrayQueue<Object>(bufferSize);
} else {
- q = new SpscAtomicArrayQueue<T>(bufferSize);
+ q = new SpscAtomicArrayQueue<Object>(bufferSize);
}
this.queue = q;
+ this.nl = NotificationLite.instance();
request(bufferSize);
}
@Override
public void onNext(T t) {
- queue.offer(t);
+ queue.offer(nl.next(t));
parent.drain();
}
diff --git a/src/test/java/rx/internal/operators/OperatorEagerConcatMapTest.java b/src/test/java/rx/internal/operators/OperatorEagerConcatMapTest.java
index 8c7bd3d9e4..8d2d40bed4 100644
--- a/src/test/java/rx/internal/operators/OperatorEagerConcatMapTest.java
+++ b/src/test/java/rx/internal/operators/OperatorEagerConcatMapTest.java
@@ -394,4 +394,20 @@ public void call(Integer t) {
ts.assertNotCompleted();
Assert.assertEquals(RxRingBuffer.SIZE, count.get());
}
+
+ @Test
+ public void testInnerNull() {
+ TestSubscriber<Object> ts = TestSubscriber.create();
+
+ Observable.just(1).concatMapEager(new Func1<Integer, Observable<Integer>>() {
+ @Override
+ public Observable<Integer> call(Integer t) {
+ return Observable.just(null);
+ }
+ }).subscribe(ts);
+
+ ts.assertNoErrors();
+ ts.assertCompleted();
+ ts.assertValue(null);
+ }
}
|
1dc43f3412b46422dfa4c4a29bc520ff41a5601e
|
tapiji
|
Adapts babel core for supporting a Compiler compliance level of 1.5.
Revoves @Override annotation that lead to export errors with a configured compiler compliance level of 1.5.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroup.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroup.java
index ed6822d7..225ba05d 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroup.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/MessagesBundleGroup.java
@@ -421,7 +421,6 @@ public String getProjectName() {
return this.projectName;
}
-
/**
* Class listening for changes in underlying messages bundle and
* relays them to the listeners for MessagesBundleGroup.
@@ -481,8 +480,6 @@ public void propertyChange(PropertyChangeEvent evt) {
}
}
-
- @Override
public boolean hasPropertiesFileGroupStrategy() {
return groupStrategy instanceof PropertiesFileGroupStrategy;
}
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
index 4b5970a2..25e0e209 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java
@@ -23,7 +23,6 @@ public ResourceBundleDetectionVisitor(RBManager manager) {
this.manager = manager;
}
- @Override
public boolean visit(IResource resource) throws CoreException {
try {
if (isResourceBundleFile(resource)) {
@@ -41,7 +40,6 @@ public boolean visit(IResource resource) throws CoreException {
}
}
- @Override
public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/AbstractKeyTreeModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/AbstractKeyTreeModel.java
index aaf643ed..15073d5d 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/AbstractKeyTreeModel.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/AbstractKeyTreeModel.java
@@ -312,8 +312,6 @@ public interface IKeyTreeNodeLeafFilter {
boolean isFilteredLeaf(IKeyTreeNode leafNode);
}
-
- @Override
public IKeyTreeNode getChild(String key) {
return returnNodeWithKey(key, rootNode);
}
|
b657bdfa1a9467848cc1844b5c732087e5eae1ca
|
elasticsearch
|
Optimize aliases processing--Closes- 2832-
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java b/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java
index 09d607bf9d63b..47b1de66fd6d5 100644
--- a/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java
+++ b/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java
@@ -39,6 +39,7 @@
import org.elasticsearch.indices.InvalidAliasNameException;
import java.io.IOException;
+import java.util.Map;
import static org.elasticsearch.common.collect.MapBuilder.newMapBuilder;
@@ -67,10 +68,20 @@ public IndexAlias alias(String alias) {
return aliases.get(alias);
}
+ public IndexAlias create(String alias, @Nullable CompressedString filter) {
+ return new IndexAlias(alias, filter, parse(alias, filter));
+ }
+
public void add(String alias, @Nullable CompressedString filter) {
add(new IndexAlias(alias, filter, parse(alias, filter)));
}
+ public void addAll(Map<String, IndexAlias> aliases) {
+ synchronized (mutex) {
+ this.aliases = newMapBuilder(this.aliases).putAll(aliases).immutableMap();
+ }
+ }
+
/**
* Returns the filter associated with listed filtering aliases.
* <p/>
diff --git a/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java b/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java
index f7cbd4e12be14..d7ca96d866701 100644
--- a/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java
+++ b/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java
@@ -62,10 +62,13 @@
import org.elasticsearch.indices.recovery.StartRecoveryRequest;
import org.elasticsearch.threadpool.ThreadPool;
+import java.util.Collection;
+import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
+import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;
import static org.elasticsearch.ExceptionsHelper.detailedMessage;
@@ -433,9 +436,7 @@ private void applyAliases(ClusterChangedEvent event) {
String index = indexMetaData.index();
IndexService indexService = indicesService.indexService(index);
IndexAliasesService indexAliasesService = indexService.aliasesService();
- for (AliasMetaData aliasesMd : indexMetaData.aliases().values()) {
- processAlias(index, aliasesMd.alias(), aliasesMd.filter(), indexAliasesService);
- }
+ processAliases(index, indexMetaData.aliases().values(), indexAliasesService);
// go over and remove aliases
for (IndexAlias indexAlias : indexAliasesService) {
if (!indexMetaData.aliases().containsKey(indexAlias.alias())) {
@@ -450,26 +451,31 @@ private void applyAliases(ClusterChangedEvent event) {
}
}
- private void processAlias(String index, String alias, CompressedString filter, IndexAliasesService indexAliasesService) {
- try {
- if (!indexAliasesService.hasAlias(alias)) {
- if (logger.isDebugEnabled()) {
- logger.debug("[{}] adding alias [{}], filter [{}]", index, alias, filter);
- }
- indexAliasesService.add(alias, filter);
- } else {
- if ((filter == null && indexAliasesService.alias(alias).filter() != null) ||
- (filter != null && !filter.equals(indexAliasesService.alias(alias).filter()))) {
+ private void processAliases(String index, Collection<AliasMetaData> aliases, IndexAliasesService indexAliasesService) {
+ HashMap<String, IndexAlias> newAliases = newHashMap();
+ for (AliasMetaData aliasMd : aliases) {
+ String alias = aliasMd.alias();
+ CompressedString filter = aliasMd.filter();
+ try {
+ if (!indexAliasesService.hasAlias(alias)) {
if (logger.isDebugEnabled()) {
- logger.debug("[{}] updating alias [{}], filter [{}]", index, alias, filter);
+ logger.debug("[{}] adding alias [{}], filter [{}]", index, alias, filter);
+ }
+ newAliases.put(alias, indexAliasesService.create(alias, filter));
+ } else {
+ if ((filter == null && indexAliasesService.alias(alias).filter() != null) ||
+ (filter != null && !filter.equals(indexAliasesService.alias(alias).filter()))) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("[{}] updating alias [{}], filter [{}]", index, alias, filter);
+ }
+ newAliases.put(alias, indexAliasesService.create(alias, filter));
}
- indexAliasesService.add(alias, filter);
}
+ } catch (Exception e) {
+ logger.warn("[{}] failed to add alias [{}], filter [{}]", e, index, alias, filter);
}
- } catch (Exception e) {
- logger.warn("[{}] failed to add alias [{}], filter [{}]", e, index, alias, filter);
}
-
+ indexAliasesService.addAll(newAliases);
}
private void applyNewOrUpdatedShards(final ClusterChangedEvent event) throws ElasticSearchException {
|
0578ba96dfe44b8264b74329764137084f8b62c8
|
apache$maven-plugins
|
[MWAR-81] Request enhancement to pattern matching for packagingIncludes/packagingExcludes functionality (regular expressions?)
Submitted by: Nicolas Marcotte
Reviewed by: Dennis Lundberg
o Minor adjustments to code style
o Added a page to the site with examples
git-svn-id: https://svn.apache.org/repos/asf/maven/plugins/trunk@1203638 13f79535-47bb-0310-9956-ffa450edef68
|
p
|
https://github.com/apache/maven-plugins
|
diff --git a/maven-war-plugin/src/main/java/org/apache/maven/plugin/war/WarMojo.java b/maven-war-plugin/src/main/java/org/apache/maven/plugin/war/WarMojo.java
index 1d629accad..56d48e039d 100644
--- a/maven-war-plugin/src/main/java/org/apache/maven/plugin/war/WarMojo.java
+++ b/maven-war-plugin/src/main/java/org/apache/maven/plugin/war/WarMojo.java
@@ -75,7 +75,9 @@ public class WarMojo
/**
* The comma separated list of tokens to exclude from the WAR before
* packaging. This option may be used to implement the skinny WAR use
- * case.
+ * case. Note the you can use the Java Regular Expressions engine to
+ * include and exclude specific pattern using the expression %regex[].
+ * Hint: read the about (?!Pattern).
*
* @parameter
* @since 2.1-alpha-2
@@ -85,7 +87,9 @@ public class WarMojo
/**
* The comma separated list of tokens to include in the WAR before
* packaging. By default everything is included. This option may be used
- * to implement the skinny WAR use case.
+ * to implement the skinny WAR use case. Note the you can use the
+ * Java Regular Expressions engine to include and exclude specific pattern
+ * using the expression %regex[].
*
* @parameter
* @since 2.1-beta-1
diff --git a/maven-war-plugin/src/site/apt/examples/including-excluding-files-from-war.apt.vm b/maven-war-plugin/src/site/apt/examples/including-excluding-files-from-war.apt.vm
new file mode 100644
index 0000000000..c1d832d9f6
--- /dev/null
+++ b/maven-war-plugin/src/site/apt/examples/including-excluding-files-from-war.apt.vm
@@ -0,0 +1,82 @@
+ ------
+ Including and Excluding Files From the WAR
+ ------
+ Dennis Lundberg
+ ------
+ 2011-11-21
+ ------
+
+~~ 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.
+
+~~ NOTE: For help with the syntax of this file, see:
+~~ http://maven.apache.org/doxia/references/apt-format.html
+
+Including and Excluding Files From the WAR
+
+
+ It is possible to include or exclude certain files from the WAR file, by using the <<<\<packagingIncludes\>>>> and <<<\<packagingExcludes\>>>> configuration parameters. They each take a comma-separated list of Ant file set patterns. You can use wildcards such as <<<**>>> to indicate multiple directories and <<<*>>> to indicate an optional part of a file or directory name.
+
+ Here is an example where we exclude all JAR files from <<<WEB-INF/lib>>>:
+
++-----------------+
+<project>
+ ...
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-war-plugin</artifactId>
+ <version>${project.version}</version>
+ <configuration>
+ <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ ...
+</project>
++-----------------+
+
+ Sometimes even such wildcards are not enough. In these cases you can use regular expressions with the <<<%regex[]>>> syntax. Here is a real life use case in which this is used. In this example we want to exclude any commons-logging and log4j JARs, but we do not want to exclude the log4j-over-slf4j JAR. So we want to exclude <<<log4j-\<version\>.jar>>> but keep the <<<log4j-over-slf4j-\<version\>.jar>>>.
+
++-----------------+
+<project>
+ ...
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-war-plugin</artifactId>
+ <version>${project.version}</version>
+ <configuration>
+ <!--
+ Exclude JCL and LOG4J since all logging should go through SLF4J.
+ Note that we're excluding log4j-<version>.jar but keeping
+ log4j-over-slf4j-<version>.jar
+ -->
+ <packagingExcludes>
+ WEB-INF/lib/commons-logging-*.jar,
+ %regex[WEB-INF/lib/log4j-(?!over-slf4j).*.jar]
+ </packagingExcludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ ...
+</project>
++-----------------+
+
+ If you have more real life examples of using regular expressions, we'd like to know about them. Please file an issue in {{{../issue-tracking.html}our issue tracker}} with your configuration, so we can expand this page.
diff --git a/maven-war-plugin/src/site/apt/index.apt b/maven-war-plugin/src/site/apt/index.apt
index 61078ae81a..b51358e336 100644
--- a/maven-war-plugin/src/site/apt/index.apt
+++ b/maven-war-plugin/src/site/apt/index.apt
@@ -81,6 +81,8 @@ Maven WAR Plugin
* {{{./examples/skinny-wars.html}Creating Skinny WARs}}
+ * {{{./examples/including-excluding-files-from-war.html}Including and Excluding Files From the WAR}}
+
* {{{./examples/file-name-mapping.html}Using File Name Mapping}}
[]
diff --git a/maven-war-plugin/src/site/site.xml b/maven-war-plugin/src/site/site.xml
index f6f9aa7bfa..2244644cc9 100644
--- a/maven-war-plugin/src/site/site.xml
+++ b/maven-war-plugin/src/site/site.xml
@@ -38,6 +38,7 @@ under the License.
<item name="WAR Manifest Customization" href="examples/war-manifest-guide.html"/>
<item name="Rapid Testing Using the Jetty Plugin" href="examples/rapid-testing-jetty6-plugin.html"/>
<item name="Creating Skinny WARs" href="examples/skinny-wars.html"/>
+ <item name="Including and Excluding Files From the WAR" href="examples/including-excluding-files-from-war.html"/>
<item name="Using File Name Mapping" href="examples/file-name-mapping.html"/>
</menu>
</body>
diff --git a/maven-war-plugin/src/test/java/org/apache/maven/plugin/war/WarMojoTest.java b/maven-war-plugin/src/test/java/org/apache/maven/plugin/war/WarMojoTest.java
index c53c7c3cab..f590a19236 100644
--- a/maven-war-plugin/src/test/java/org/apache/maven/plugin/war/WarMojoTest.java
+++ b/maven-war-plugin/src/test/java/org/apache/maven/plugin/war/WarMojoTest.java
@@ -93,6 +93,38 @@ public void testSimpleWar()
new String[]{null, mojo.getWebXml().toString(), null, null, null, null} );
}
+ public void testSimpleWarPackagingExcludeWithIncludesRegEx()
+ throws Exception
+ {
+ String testId = "SimpleWarPackagingExcludeWithIncludesRegEx";
+ MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
+ String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
+ File webAppDirectory = new File( getTestDirectory(), testId );
+ WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
+ String warName = "simple";
+ File webAppSource = createWebAppSource( testId );
+ File classesDir = createClassesDir( testId, true );
+ File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
+
+ project.setArtifact( warArtifact );
+ this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
+ setVariableValueToObject( mojo, "outputDirectory", outputDir );
+ setVariableValueToObject( mojo, "warName", warName );
+ mojo.setWebXml( new File( xmlSource, "web.xml" ) );
+ setVariableValueToObject( mojo,"packagingIncludes","%regex[(.(?!exile))+]" );
+
+
+ mojo.execute();
+
+ //validate jar file
+ File expectedJarFile = new File( outputDir, "simple.war" );
+ assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "WEB-INF/web.xml", "pansit.jsp",
+ "META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
+ "META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"},
+ new String[]{null, mojo.getWebXml().toString(), null, null, null, },
+ new String[]{"org/web/app/last-exile.jsp"} );
+ }
+
public void testClassifier()
throws Exception
{
@@ -383,6 +415,12 @@ public void testAttachClassesWithCustomClassifier()
protected Map assertJarContent( final File expectedJarFile, final String[] files, final String[] filesContent )
throws IOException
+ {
+ return assertJarContent( expectedJarFile, files, filesContent, null );
+ }
+
+ protected Map assertJarContent( final File expectedJarFile, final String[] files, final String[] filesContent, final String[] mustNotBeInJar )
+ throws IOException
{
// Sanity check
assertEquals( "Could not test, files and filesContent lenght does not match", files.length,
@@ -404,6 +442,7 @@ protected Map assertJarContent( final File expectedJarFile, final String[] files
for ( int i = 0; i < files.length; i++ )
{
String file = files[i];
+
assertTrue( "File[" + file + "] not found in archive", jarContent.containsKey( file ) );
if ( filesContent[i] != null )
{
@@ -411,6 +450,16 @@ protected Map assertJarContent( final File expectedJarFile, final String[] files
IOUtil.toString( jarFile.getInputStream( (ZipEntry) jarContent.get( file ) ) ) );
}
}
+ if( mustNotBeInJar!=null )
+ {
+ for ( int i = 0; i < mustNotBeInJar.length; i++ )
+ {
+ String file = mustNotBeInJar[i];
+
+ assertFalse( "File[" + file + "] found in archive", jarContent.containsKey( file ) );
+
+ }
+ }
return jarContent;
}
|
b580f0706dc1dcded6d1a584c37a83dd1cb2ea2a
|
restlet-framework-java
|
- The simplified logging formatter (one line)- is now available only in the Java SE edition as it could cause- troubles with Java EE container and potentially GAE/Android as we- reconfigure the default log manager programmatically. Reported by- Kristoffer Gronowski and Bo Xing.--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt
index 9f9255ad31..44c46f7a7b 100644
--- a/build/tmpl/text/changes.txt
+++ b/build/tmpl/text/changes.txt
@@ -11,6 +11,10 @@ Changes log
500 status being returned to the client instead of the given status.
Reported by Avi Flax and Rhett Sutphin.
- Misc
+ - The simplified logging formatter (one line) is now available only in
+ the Java SE edition as it could cause troubles with Java EE container
+ and potentially GAE/Android as we reconfigure the default log manager
+ programmatically. Reported by Kristoffer Gronowski and Bo Xing.
- 2.1 Milestone 3 (03/31/2011)
- Breaking changes
diff --git a/modules/org.restlet/src/org/restlet/engine/Engine.java b/modules/org.restlet/src/org/restlet/engine/Engine.java
index 0d0aba0756..d3d0799f87 100644
--- a/modules/org.restlet/src/org/restlet/engine/Engine.java
+++ b/modules/org.restlet/src/org/restlet/engine/Engine.java
@@ -101,13 +101,15 @@ public class Engine {
/** The registered engine. */
private static volatile Engine instance = null;
+ // [ifdef jse] member
/** The org.restlet log level . */
private static volatile boolean logConfigured = false;
- // [ifndef gwt] member
+ // [ifdef jse] member
/** The general log formatter. */
private static volatile Class<? extends Formatter> logFormatter = org.restlet.engine.log.SimplestFormatter.class;
+ // [ifdef jse] member
/** The general log level . */
private static volatile Level logLevel = Level.INFO;
@@ -120,6 +122,7 @@ public class Engine {
/** Release number. */
public static final String RELEASE_NUMBER = "@release-type@@release-number@";
+ // [ifdef jse] member
/** The org.restlet log level . */
private static volatile Level restletLogLevel;
@@ -148,11 +151,11 @@ public static void clearThreadLocalVariables() {
org.restlet.Application.setCurrent(null);
}
+ // [ifdef jse] method
/**
* Updates the global log configuration of the JVM programmatically.
*/
public static void configureLog() {
- // [ifndef gwt]
if ((System.getProperty("java.util.logging.config.file") == null)
&& (System.getProperty("java.util.logging.config.class") == null)) {
StringBuilder sb = new StringBuilder();
@@ -188,13 +191,10 @@ public static void configureLog() {
CharacterSet.DEFAULT));
} catch (Exception e) {
e.printStackTrace();
- } finally {
- logConfigured = true;
}
}
- // [enddef]
- // [ifdef gwt] instruction uncomment
- // logConfigured = true;
+
+ logConfigured = true;
}
/**
@@ -222,7 +222,7 @@ public static synchronized Engine getInstance() {
return result;
}
- // [ifndef gwt] method
+ // [ifdef jse] method
/**
* Returns the general log formatter.
*
@@ -284,6 +284,7 @@ public static Logger getLogger(String loggerName) {
return getInstance().getLoggerFacade().getLogger(loggerName);
}
+ // [ifdef jse] method
/**
* Returns the general log level.
*
@@ -305,6 +306,7 @@ public static java.net.URL getResource(String name) {
return getInstance().getClassLoader().getResource(name);
}
+ // [ifdef jse] method
/**
* Returns the Restlet log level. For loggers with a name starting with
* "org.restlet".
@@ -346,10 +348,11 @@ public static synchronized Engine register() {
* @return The registered engine.
*/
public static synchronized Engine register(boolean discoverPlugins) {
+ // [ifdef jse]
if (!logConfigured) {
configureLog();
}
-
+ // [enddef]
Engine result = new Engine(discoverPlugins);
org.restlet.engine.Engine.setInstance(result);
return result;
@@ -368,7 +371,7 @@ public static synchronized void setInstance(Engine engine) {
instance = engine;
}
- // [ifndef gwt] method
+ // [ifdef jse] method
/**
* Sets the general log formatter.
*
@@ -380,6 +383,7 @@ public static void setLogFormatter(Class<? extends Formatter> logFormatter) {
configureLog();
}
+ // [ifdef jse] method
/**
* Sets the general log level. Modifies the global JVM's {@link LogManager}.
*
@@ -391,6 +395,7 @@ public static void setLogLevel(Level logLevel) {
configureLog();
}
+ // [ifdef jse] method
/**
* Sets the Restlet log level. For loggers with a name starting with
* "org.restlet".
|
ed77c8925d7126f9ea3c8d9cbb1e246ad61ce37c
|
hadoop
|
YARN-596. Use scheduling policies throughout the- queue hierarchy to decide which containers to preempt (Wei Yan via Sandy- Ryza)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1598198 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 6d2638927c350..2ca64fb4ea647 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -99,6 +99,9 @@ Release 2.5.0 - UNRELEASED
YARN-2107. Refactored timeline classes into o.a.h.y.s.timeline package. (Vinod
Kumar Vavilapalli via zjshen)
+ YARN-596. Use scheduling policies throughout the queue hierarchy to decide
+ which containers to preempt (Wei Yan via Sandy Ryza)
+
OPTIMIZATIONS
BUG FIXES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AppSchedulable.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AppSchedulable.java
index 9ed5179270a66..4dc0bf4ceb870 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AppSchedulable.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AppSchedulable.java
@@ -18,8 +18,10 @@
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;
+import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Comparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -31,8 +33,6 @@
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
-import org.apache.hadoop.yarn.factories.RecordFactory;
-import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType;
@@ -58,6 +58,8 @@ public class AppSchedulable extends Schedulable {
private Priority priority;
private ResourceWeights resourceWeights;
+ private RMContainerComparator comparator = new RMContainerComparator();
+
public AppSchedulable(FairScheduler scheduler, FSSchedulerApp app, FSLeafQueue queue) {
this.scheduler = scheduler;
this.app = app;
@@ -111,7 +113,10 @@ public long getStartTime() {
@Override
public Resource getResourceUsage() {
- return app.getCurrentConsumption();
+ // Here the getPreemptedResources() always return zero, except in
+ // a preemption round
+ return Resources.subtract(app.getCurrentConsumption(),
+ app.getPreemptedResources());
}
@@ -383,6 +388,27 @@ public Resource assignContainer(FSSchedulerNode node) {
return assignContainer(node, false);
}
+ /**
+ * Preempt a running container according to the priority
+ */
+ @Override
+ public RMContainer preemptContainer() {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("App " + getName() + " is going to preempt a running " +
+ "container");
+ }
+
+ RMContainer toBePreempted = null;
+ for (RMContainer container : app.getLiveContainers()) {
+ if (! app.getPreemptionContainers().contains(container) &&
+ (toBePreempted == null ||
+ comparator.compare(toBePreempted, container) > 0)) {
+ toBePreempted = container;
+ }
+ }
+ return toBePreempted;
+ }
+
/**
* Whether this app has containers requests that could be satisfied on the
* given node, if the node had full space.
@@ -407,4 +433,17 @@ public boolean hasContainerForNode(Priority prio, FSSchedulerNode node) {
Resources.lessThanOrEqual(RESOURCE_CALCULATOR, null,
anyRequest.getCapability(), node.getRMNode().getTotalCapability());
}
+
+ static class RMContainerComparator implements Comparator<RMContainer>,
+ Serializable {
+ @Override
+ public int compare(RMContainer c1, RMContainer c2) {
+ int ret = c1.getContainer().getPriority().compareTo(
+ c2.getContainer().getPriority());
+ if (ret == 0) {
+ return c2.getContainerId().compareTo(c1.getContainerId());
+ }
+ return ret;
+ }
+ }
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSLeafQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSLeafQueue.java
index e842a6a3557be..fe738da7d4611 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSLeafQueue.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSLeafQueue.java
@@ -33,10 +33,10 @@
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
import org.apache.hadoop.yarn.api.records.Resource;
+import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerAppUtils;
import org.apache.hadoop.yarn.util.resource.Resources;
-import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplication;
@Private
@Unstable
@@ -208,6 +208,36 @@ public Resource assignContainer(FSSchedulerNode node) {
return assigned;
}
+ @Override
+ public RMContainer preemptContainer() {
+ RMContainer toBePreempted = null;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Queue " + getName() + " is going to preempt a container " +
+ "from its applications.");
+ }
+
+ // If this queue is not over its fair share, reject
+ if (!preemptContainerPreCheck()) {
+ return toBePreempted;
+ }
+
+ // Choose the app that is most over fair share
+ Comparator<Schedulable> comparator = policy.getComparator();
+ AppSchedulable candidateSched = null;
+ for (AppSchedulable sched : runnableAppScheds) {
+ if (candidateSched == null ||
+ comparator.compare(sched, candidateSched) > 0) {
+ candidateSched = sched;
+ }
+ }
+
+ // Preempt from the selected app
+ if (candidateSched != null) {
+ toBePreempted = candidateSched.preemptContainer();
+ }
+ return toBePreempted;
+ }
+
@Override
public List<FSQueue> getChildQueues() {
return new ArrayList<FSQueue>(1);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java
index 427cb86457937..48db41496340c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java
@@ -21,6 +21,7 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
+import java.util.Comparator;
import java.util.List;
import org.apache.commons.logging.Log;
@@ -32,6 +33,7 @@
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
import org.apache.hadoop.yarn.api.records.Resource;
+import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
@@ -156,6 +158,32 @@ public Resource assignContainer(FSSchedulerNode node) {
return assigned;
}
+ @Override
+ public RMContainer preemptContainer() {
+ RMContainer toBePreempted = null;
+
+ // If this queue is not over its fair share, reject
+ if (!preemptContainerPreCheck()) {
+ return toBePreempted;
+ }
+
+ // Find the childQueue which is most over fair share
+ FSQueue candidateQueue = null;
+ Comparator<Schedulable> comparator = policy.getComparator();
+ for (FSQueue queue : childQueues) {
+ if (candidateQueue == null ||
+ comparator.compare(queue, candidateQueue) > 0) {
+ candidateQueue = queue;
+ }
+ }
+
+ // Let the selected queue choose which of its container to preempt
+ if (candidateQueue != null) {
+ toBePreempted = candidateQueue.preemptContainer();
+ }
+ return toBePreempted;
+ }
+
@Override
public List<FSQueue> getChildQueues() {
return childQueues;
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSQueue.java
index 1e94046100ac3..716e1ee687441 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSQueue.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSQueue.java
@@ -187,4 +187,17 @@ protected boolean assignContainerPreCheck(FSSchedulerNode node) {
}
return true;
}
+
+ /**
+ * Helper method to check if the queue should preempt containers
+ *
+ * @return true if check passes (can preempt) or false otherwise
+ */
+ protected boolean preemptContainerPreCheck() {
+ if (this == scheduler.getQueueManager().getRootQueue()) {
+ return true;
+ }
+ return parent.getPolicy()
+ .checkIfUsageOverFairShare(getResourceUsage(), getFairShare());
+ }
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSSchedulerApp.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSSchedulerApp.java
index adabfefaee184..63a29e4b099a0 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSSchedulerApp.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSSchedulerApp.java
@@ -59,6 +59,8 @@ public class FSSchedulerApp extends SchedulerApplicationAttempt {
private AppSchedulable appSchedulable;
final Map<RMContainer, Long> preemptionMap = new HashMap<RMContainer, Long>();
+
+ private Resource preemptedResources = Resources.createResource(0);
public FSSchedulerApp(ApplicationAttemptId applicationAttemptId,
String user, FSLeafQueue queue, ActiveUsersManager activeUsersManager,
@@ -316,6 +318,7 @@ public synchronized void resetAllowedLocalityLevel(Priority priority,
public void addPreemption(RMContainer container, long time) {
assert preemptionMap.get(container) == null;
preemptionMap.put(container, time);
+ Resources.addTo(preemptedResources, container.getAllocatedResource());
}
public Long getContainerPreemptionTime(RMContainer container) {
@@ -330,4 +333,20 @@ public Set<RMContainer> getPreemptionContainers() {
public FSLeafQueue getQueue() {
return (FSLeafQueue)super.getQueue();
}
+
+ public Resource getPreemptedResources() {
+ return preemptedResources;
+ }
+
+ public void resetPreemptedResources() {
+ preemptedResources = Resources.createResource(0);
+ for (RMContainer container : getPreemptionContainers()) {
+ Resources.addTo(preemptedResources, container.getAllocatedResource());
+ }
+ }
+
+ public void clearPreemptedResources() {
+ preemptedResources.setMemory(0);
+ preemptedResources.setVirtualCores(0);
+ }
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
index 830f6f7509903..6d71ea2fbb3a6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
@@ -20,14 +20,11 @@
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
-import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -337,94 +334,78 @@ protected synchronized void preemptTasksIfNecessary() {
}
if (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource, resToPreempt,
Resources.none())) {
- preemptResources(queueMgr.getLeafQueues(), resToPreempt);
+ preemptResources(resToPreempt);
}
}
/**
- * Preempt a quantity of resources from a list of QueueSchedulables. The
- * policy for this is to pick apps from queues that are over their fair share,
- * but make sure that no queue is placed below its fair share in the process.
- * We further prioritize preemption by choosing containers with lowest
- * priority to preempt.
+ * Preempt a quantity of resources. Each round, we start from the root queue,
+ * level-by-level, until choosing a candidate application.
+ * The policy for prioritizing preemption for each queue depends on its
+ * SchedulingPolicy: (1) fairshare/DRF, choose the ChildSchedulable that is
+ * most over its fair share; (2) FIFO, choose the childSchedulable that is
+ * latest launched.
+ * Inside each application, we further prioritize preemption by choosing
+ * containers with lowest priority to preempt.
+ * We make sure that no queue is placed below its fair share in the process.
*/
- protected void preemptResources(Collection<FSLeafQueue> scheds,
- Resource toPreempt) {
- if (scheds.isEmpty() || Resources.equals(toPreempt, Resources.none())) {
+ protected void preemptResources(Resource toPreempt) {
+ if (Resources.equals(toPreempt, Resources.none())) {
return;
}
- Map<RMContainer, FSSchedulerApp> apps =
- new HashMap<RMContainer, FSSchedulerApp>();
- Map<RMContainer, FSLeafQueue> queues =
- new HashMap<RMContainer, FSLeafQueue>();
-
- // Collect running containers from over-scheduled queues
- List<RMContainer> runningContainers = new ArrayList<RMContainer>();
- for (FSLeafQueue sched : scheds) {
- if (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource,
- sched.getResourceUsage(), sched.getFairShare())) {
- for (AppSchedulable as : sched.getRunnableAppSchedulables()) {
- for (RMContainer c : as.getApp().getLiveContainers()) {
- runningContainers.add(c);
- apps.put(c, as.getApp());
- queues.put(c, sched);
- }
- }
- }
- }
-
- // Sort containers into reverse order of priority
- Collections.sort(runningContainers, new Comparator<RMContainer>() {
- public int compare(RMContainer c1, RMContainer c2) {
- int ret = c1.getContainer().getPriority().compareTo(
- c2.getContainer().getPriority());
- if (ret == 0) {
- return c2.getContainerId().compareTo(c1.getContainerId());
- }
- return ret;
- }
- });
-
// Scan down the list of containers we've already warned and kill them
// if we need to. Remove any containers from the list that we don't need
// or that are no longer running.
Iterator<RMContainer> warnedIter = warnedContainers.iterator();
- Set<RMContainer> preemptedThisRound = new HashSet<RMContainer>();
while (warnedIter.hasNext()) {
RMContainer container = warnedIter.next();
- if (container.getState() == RMContainerState.RUNNING &&
+ if ((container.getState() == RMContainerState.RUNNING ||
+ container.getState() == RMContainerState.ALLOCATED) &&
Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource,
toPreempt, Resources.none())) {
- warnOrKillContainer(container, apps.get(container), queues.get(container));
- preemptedThisRound.add(container);
+ warnOrKillContainer(container);
Resources.subtractFrom(toPreempt, container.getContainer().getResource());
} else {
warnedIter.remove();
}
}
- // Scan down the rest of the containers until we've preempted enough, making
- // sure we don't preempt too many from any queue
- Iterator<RMContainer> runningIter = runningContainers.iterator();
- while (runningIter.hasNext() &&
- Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource,
- toPreempt, Resources.none())) {
- RMContainer container = runningIter.next();
- FSLeafQueue sched = queues.get(container);
- if (!preemptedThisRound.contains(container) &&
- Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource,
- sched.getResourceUsage(), sched.getFairShare())) {
- warnOrKillContainer(container, apps.get(container), sched);
-
- warnedContainers.add(container);
- Resources.subtractFrom(toPreempt, container.getContainer().getResource());
+ try {
+ // Reset preemptedResource for each app
+ for (FSLeafQueue queue : getQueueManager().getLeafQueues()) {
+ for (AppSchedulable app : queue.getRunnableAppSchedulables()) {
+ app.getApp().resetPreemptedResources();
+ }
+ }
+
+ while (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource,
+ toPreempt, Resources.none())) {
+ RMContainer container =
+ getQueueManager().getRootQueue().preemptContainer();
+ if (container == null) {
+ break;
+ } else {
+ warnOrKillContainer(container);
+ warnedContainers.add(container);
+ Resources.subtractFrom(
+ toPreempt, container.getContainer().getResource());
+ }
+ }
+ } finally {
+ // Clear preemptedResources for each app
+ for (FSLeafQueue queue : getQueueManager().getLeafQueues()) {
+ for (AppSchedulable app : queue.getRunnableAppSchedulables()) {
+ app.getApp().clearPreemptedResources();
+ }
}
}
}
- private void warnOrKillContainer(RMContainer container, FSSchedulerApp app,
- FSLeafQueue queue) {
+ private void warnOrKillContainer(RMContainer container) {
+ ApplicationAttemptId appAttemptId = container.getApplicationAttemptId();
+ FSSchedulerApp app = getSchedulerApp(appAttemptId);
+ FSLeafQueue queue = app.getQueue();
LOG.info("Preempting container (prio=" + container.getContainer().getPriority() +
"res=" + container.getContainer().getResource() +
") from queue " + queue.getName());
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/Schedulable.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/Schedulable.java
index 92b6d3e71eabc..4f8ac1e63744c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/Schedulable.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/Schedulable.java
@@ -23,6 +23,7 @@
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights;
+import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.util.resource.Resources;
/**
@@ -100,6 +101,11 @@ public abstract class Schedulable {
*/
public abstract Resource assignContainer(FSSchedulerNode node);
+ /**
+ * Preempt a container from this Schedulable if possible.
+ */
+ public abstract RMContainer preemptContainer();
+
/** Assign a fair share to this Schedulable. */
public void setFairShare(Resource fairShare) {
this.fairShare = fairShare;
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/SchedulingPolicy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/SchedulingPolicy.java
index 549b85c380f61..1d77a43ce7588 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/SchedulingPolicy.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/SchedulingPolicy.java
@@ -139,4 +139,14 @@ public static boolean isApplicableTo(SchedulingPolicy policy, byte depth) {
*/
public abstract void computeShares(
Collection<? extends Schedulable> schedulables, Resource totalResources);
+
+ /**
+ * Check if the resource usage is over the fair share under this policy
+ *
+ * @param usage {@link Resource} the resource usage
+ * @param fairShare {@link Resource} the fair share
+ * @return true if check passes (is over) or false otherwise
+ */
+ public abstract boolean checkIfUsageOverFairShare(
+ Resource usage, Resource fairShare);
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/DominantResourceFairnessPolicy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/DominantResourceFairnessPolicy.java
index f5b841772295a..4b663d95de8b9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/DominantResourceFairnessPolicy.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/DominantResourceFairnessPolicy.java
@@ -69,6 +69,11 @@ public void computeShares(Collection<? extends Schedulable> schedulables,
}
}
+ @Override
+ public boolean checkIfUsageOverFairShare(Resource usage, Resource fairShare) {
+ return !Resources.fitsIn(usage, fairShare);
+ }
+
@Override
public void initialize(Resource clusterCapacity) {
comparator.setClusterCapacity(clusterCapacity);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/FairSharePolicy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/FairSharePolicy.java
index fbad101267697..ca7297ff46c38 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/FairSharePolicy.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/FairSharePolicy.java
@@ -119,6 +119,11 @@ public void computeShares(Collection<? extends Schedulable> schedulables,
ComputeFairShares.computeShares(schedulables, totalResources, ResourceType.MEMORY);
}
+ @Override
+ public boolean checkIfUsageOverFairShare(Resource usage, Resource fairShare) {
+ return Resources.greaterThan(RESOURCE_CALCULATOR, null, usage, fairShare);
+ }
+
@Override
public byte getApplicableDepth() {
return SchedulingPolicy.DEPTH_ANY;
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/FifoPolicy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/FifoPolicy.java
index 3451cfea4c50b..d996944681157 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/FifoPolicy.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/policies/FifoPolicy.java
@@ -20,7 +20,6 @@
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
-import java.util.Iterator;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
@@ -88,6 +87,13 @@ public void computeShares(Collection<? extends Schedulable> schedulables,
earliest.setFairShare(Resources.clone(totalResources));
}
+ @Override
+ public boolean checkIfUsageOverFairShare(Resource usage, Resource fairShare) {
+ throw new UnsupportedOperationException(
+ "FifoPolicy doesn't support checkIfUsageOverFairshare operation, " +
+ "as FifoPolicy only works for FSLeafQueue.");
+ }
+
@Override
public byte getApplicableDepth() {
return SchedulingPolicy.DEPTH_LEAF;
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FakeSchedulable.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FakeSchedulable.java
index d0ba0d8e085f4..dcfc2d3aa2fc6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FakeSchedulable.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FakeSchedulable.java
@@ -21,6 +21,7 @@
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights;
+import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.util.Records;
import org.apache.hadoop.yarn.util.resource.Resources;
@@ -83,6 +84,11 @@ public Resource assignContainer(FSSchedulerNode node) {
return null;
}
+ @Override
+ public RMContainer preemptContainer() {
+ return null;
+ }
+
@Override
public Resource getDemand() {
return null;
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
index 2755ef081eae4..2de498f4f41a1 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
@@ -1029,13 +1029,13 @@ else if (p.getName().equals("root.queueB")) {
@Test (timeout = 5000)
/**
- * Make sure containers are chosen to be preempted in the correct order. Right
- * now this means decreasing order of priority.
+ * Make sure containers are chosen to be preempted in the correct order.
*/
public void testChoiceOfPreemptedContainers() throws Exception {
conf.setLong(FairSchedulerConfiguration.PREEMPTION_INTERVAL, 5000);
- conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000);
+ conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000);
conf.set(FairSchedulerConfiguration.ALLOCATION_FILE + ".allocation.file", ALLOC_FILE);
+ conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "false");
MockClock clock = new MockClock();
scheduler.setClock(clock);
@@ -1052,7 +1052,7 @@ public void testChoiceOfPreemptedContainers() throws Exception {
out.println("<queue name=\"queueC\">");
out.println("<weight>.25</weight>");
out.println("</queue>");
- out.println("<queue name=\"queueD\">");
+ out.println("<queue name=\"default\">");
out.println("<weight>.25</weight>");
out.println("</queue>");
out.println("</allocations>");
@@ -1060,133 +1060,132 @@ public void testChoiceOfPreemptedContainers() throws Exception {
scheduler.reinitialize(conf, resourceManager.getRMContext());
- // Create four nodes
+ // Create two nodes
RMNode node1 =
- MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 1,
+ MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 1,
"127.0.0.1");
NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
scheduler.handle(nodeEvent1);
RMNode node2 =
- MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 2,
+ MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 2,
"127.0.0.2");
NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
scheduler.handle(nodeEvent2);
- RMNode node3 =
- MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 3,
- "127.0.0.3");
- NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
- scheduler.handle(nodeEvent3);
-
-
- // Queue A and B each request three containers
+ // Queue A and B each request two applications
ApplicationAttemptId app1 =
- createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1);
+ createSchedulingRequest(1 * 1024, 1, "queueA", "user1", 1, 1);
+ createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app1);
ApplicationAttemptId app2 =
- createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 2);
- ApplicationAttemptId app3 =
- createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 3);
+ createSchedulingRequest(1 * 1024, 1, "queueA", "user1", 1, 3);
+ createSchedulingRequestExistingApplication(1 * 1024, 1, 4, app2);
+ ApplicationAttemptId app3 =
+ createSchedulingRequest(1 * 1024, 1, "queueB", "user1", 1, 1);
+ createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app3);
ApplicationAttemptId app4 =
- createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 1);
- ApplicationAttemptId app5 =
- createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 2);
- ApplicationAttemptId app6 =
- createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 3);
+ createSchedulingRequest(1 * 1024, 1, "queueB", "user1", 1, 3);
+ createSchedulingRequestExistingApplication(1 * 1024, 1, 4, app4);
scheduler.update();
+ scheduler.getQueueManager().getLeafQueue("queueA", true)
+ .setPolicy(SchedulingPolicy.parse("fifo"));
+ scheduler.getQueueManager().getLeafQueue("queueB", true)
+ .setPolicy(SchedulingPolicy.parse("fair"));
+
// Sufficient node check-ins to fully schedule containers
- for (int i = 0; i < 2; i++) {
- NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+ NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+ NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
+ for (int i = 0; i < 4; i++) {
scheduler.handle(nodeUpdate1);
-
- NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
scheduler.handle(nodeUpdate2);
-
- NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
- scheduler.handle(nodeUpdate3);
}
- assertEquals(1, scheduler.getSchedulerApp(app1).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app3).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app5).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app6).getLiveContainers().size());
-
- // Now new requests arrive from queues C and D
- ApplicationAttemptId app7 =
- createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1);
- ApplicationAttemptId app8 =
- createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2);
- ApplicationAttemptId app9 =
- createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3);
-
- ApplicationAttemptId app10 =
- createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 1);
- ApplicationAttemptId app11 =
- createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 2);
- ApplicationAttemptId app12 =
- createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 3);
+ assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+ assertEquals(2, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+ assertEquals(2, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+ assertEquals(2, scheduler.getSchedulerApp(app4).getLiveContainers().size());
+ // Now new requests arrive from queueC and default
+ createSchedulingRequest(1 * 1024, 1, "queueC", "user1", 1, 1);
+ createSchedulingRequest(1 * 1024, 1, "queueC", "user1", 1, 1);
+ createSchedulingRequest(1 * 1024, 1, "default", "user1", 1, 1);
+ createSchedulingRequest(1 * 1024, 1, "default", "user1", 1, 1);
scheduler.update();
- // We should be able to claw back one container from A and B each.
- // Make sure it is lowest priority container.
- scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
- Resources.createResource(2 * 1024));
- assertEquals(1, scheduler.getSchedulerApp(app1).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app5).getLiveContainers().size());
-
- // First verify we are adding containers to preemption list for the application
- assertTrue(!Collections.disjoint(scheduler.getSchedulerApp(app3).getLiveContainers(),
- scheduler.getSchedulerApp(app3).getPreemptionContainers()));
- assertTrue(!Collections.disjoint(scheduler.getSchedulerApp(app6).getLiveContainers(),
- scheduler.getSchedulerApp(app6).getPreemptionContainers()));
+ // We should be able to claw back one container from queueA and queueB each.
+ scheduler.preemptResources(Resources.createResource(2 * 1024));
+ assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+ assertEquals(2, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+
+ // First verify we are adding containers to preemption list for the app.
+ // For queueA (fifo), app2 is selected.
+ // For queueB (fair), app4 is selected.
+ assertTrue("App2 should have container to be preempted",
+ !Collections.disjoint(
+ scheduler.getSchedulerApp(app2).getLiveContainers(),
+ scheduler.getSchedulerApp(app2).getPreemptionContainers()));
+ assertTrue("App4 should have container to be preempted",
+ !Collections.disjoint(
+ scheduler.getSchedulerApp(app2).getLiveContainers(),
+ scheduler.getSchedulerApp(app2).getPreemptionContainers()));
// Pretend 15 seconds have passed
clock.tick(15);
// Trigger a kill by insisting we want containers back
- scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
- Resources.createResource(2 * 1024));
+ scheduler.preemptResources(Resources.createResource(2 * 1024));
// At this point the containers should have been killed (since we are not simulating AM)
- assertEquals(0, scheduler.getSchedulerApp(app6).getLiveContainers().size());
- assertEquals(0, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+ assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+ assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
+ // Inside each app, containers are sorted according to their priorities.
+ // Containers with priority 4 are preempted for app2 and app4.
+ Set<RMContainer> set = new HashSet<RMContainer>();
+ for (RMContainer container :
+ scheduler.getSchedulerApp(app2).getLiveContainers()) {
+ if (container.getAllocatedPriority().getPriority() == 4) {
+ set.add(container);
+ }
+ }
+ for (RMContainer container :
+ scheduler.getSchedulerApp(app4).getLiveContainers()) {
+ if (container.getAllocatedPriority().getPriority() == 4) {
+ set.add(container);
+ }
+ }
+ assertTrue("Containers with priority=4 in app2 and app4 should be " +
+ "preempted.", set.isEmpty());
// Trigger a kill by insisting we want containers back
- scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
- Resources.createResource(2 * 1024));
+ scheduler.preemptResources(Resources.createResource(2 * 1024));
// Pretend 15 seconds have passed
clock.tick(15);
// We should be able to claw back another container from A and B each.
- // Make sure it is lowest priority container.
- scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
- Resources.createResource(2 * 1024));
-
- assertEquals(1, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+ // For queueA (fifo), continue preempting from app2.
+ // For queueB (fair), even app4 has a lowest priority container with p=4, it
+ // still preempts from app3 as app3 is most over fair share.
+ scheduler.preemptResources(Resources.createResource(2 * 1024));
+
+ assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
assertEquals(0, scheduler.getSchedulerApp(app2).getLiveContainers().size());
- assertEquals(0, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+ assertEquals(1, scheduler.getSchedulerApp(app3).getLiveContainers().size());
assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
- assertEquals(0, scheduler.getSchedulerApp(app5).getLiveContainers().size());
- assertEquals(0, scheduler.getSchedulerApp(app6).getLiveContainers().size());
// Now A and B are below fair share, so preemption shouldn't do anything
- scheduler.preemptResources(scheduler.getQueueManager().getLeafQueues(),
- Resources.createResource(2 * 1024));
- assertEquals(1, scheduler.getSchedulerApp(app1).getLiveContainers().size());
- assertEquals(0, scheduler.getSchedulerApp(app2).getLiveContainers().size());
- assertEquals(0, scheduler.getSchedulerApp(app3).getLiveContainers().size());
- assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
- assertEquals(0, scheduler.getSchedulerApp(app5).getLiveContainers().size());
- assertEquals(0, scheduler.getSchedulerApp(app6).getLiveContainers().size());
+ scheduler.preemptResources(Resources.createResource(2 * 1024));
+ assertTrue("App1 should have no container to be preempted",
+ scheduler.getSchedulerApp(app1).getPreemptionContainers().isEmpty());
+ assertTrue("App2 should have no container to be preempted",
+ scheduler.getSchedulerApp(app2).getPreemptionContainers().isEmpty());
+ assertTrue("App3 should have no container to be preempted",
+ scheduler.getSchedulerApp(app3).getPreemptionContainers().isEmpty());
+ assertTrue("App4 should have no container to be preempted",
+ scheduler.getSchedulerApp(app4).getPreemptionContainers().isEmpty());
}
@Test (timeout = 5000)
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java
index b3ab299ea88ca..2098e1679b9e0 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java
@@ -35,10 +35,8 @@
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
-import java.util.Collection;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class TestFairSchedulerPreemption extends FairSchedulerTestBase {
@@ -51,8 +49,7 @@ private static class StubbedFairScheduler extends FairScheduler {
public int lastPreemptMemory = -1;
@Override
- protected void preemptResources(
- Collection<FSLeafQueue> scheds, Resource toPreempt) {
+ protected void preemptResources(Resource toPreempt) {
lastPreemptMemory = toPreempt.getMemory();
}
|
e4acb6c5129fcb2c7494bc206a82734c37383c1f
|
internetarchive$heritrix3
|
try very hard to start url consumer, and therefore bind the queue to the routing key, so that no messages are dropped, before crawling starts (should always work unless rabbitmq is down); some other tweaks for clarity and stability
|
p
|
https://github.com/internetarchive/heritrix3
|
diff --git a/contrib/src/main/java/org/archive/crawler/frontier/AMQPUrlReceiver.java b/contrib/src/main/java/org/archive/crawler/frontier/AMQPUrlReceiver.java
index ca10f2a1d..918913d7c 100644
--- a/contrib/src/main/java/org/archive/crawler/frontier/AMQPUrlReceiver.java
+++ b/contrib/src/main/java/org/archive/crawler/frontier/AMQPUrlReceiver.java
@@ -106,7 +106,7 @@ public void setQueueName(String queueName) {
public boolean isRunning() {
return isRunning;
}
-
+
/** Should be queues be marked as durable? */
private boolean durable = false;
public boolean isDurable() {
@@ -127,12 +127,10 @@ public void setAutoDelete(boolean autoDelete) {
private transient Lock lock = new ReentrantLock(true);
- private boolean pauseConsumer = true;
-
- private boolean isConsuming = false;
+ private transient boolean pauseConsumer = false;
+ private transient String consumerTag = null;
private class StarterRestarter extends Thread {
- private String consumerTag = null;
public StarterRestarter(String name) {
super(name);
@@ -143,31 +141,23 @@ public void run() {
while (!Thread.interrupted()) {
try {
lock.lockInterruptibly();
- logger.finest("Checking isConsuming=" + isConsuming + " and pauseConsumer=" + pauseConsumer);
+ logger.finest("Checking consumerTag=" + consumerTag + " and pauseConsumer=" + pauseConsumer);
try {
- if (!isConsuming && !pauseConsumer) {
+ if (consumerTag == null && !pauseConsumer) {
// start up again
try {
- Consumer consumer = new UrlConsumer(channel());
- channel().exchangeDeclare(getExchange(), "direct", true);
- channel().queueDeclare(getQueueName(), durable,
- false, autoDelete, null);
- channel().queueBind(getQueueName(), getExchange(), getQueueName());
- consumerTag = channel().basicConsume(getQueueName(), false, consumer);
- isConsuming = true;
- logger.info("started AMQP consumer uri=" + getAmqpUri() + " exchange=" + getExchange() + " queueName=" + getQueueName() + " consumerTag=" + consumerTag);
+ startConsumer();
} catch (IOException e) {
logger.log(Level.SEVERE, "problem starting AMQP consumer (will try again after 10 seconds)", e);
}
}
- if (isConsuming && pauseConsumer) {
+ if (consumerTag != null && pauseConsumer) {
try {
if (consumerTag != null) {
logger.info("Attempting to cancel URLConsumer with consumerTag=" + consumerTag);
channel().basicCancel(consumerTag);
consumerTag = null;
- isConsuming = false;
logger.info("Cancelled URLConsumer.");
}
} catch (IOException e) {
@@ -175,16 +165,27 @@ public void run() {
}
}
- Thread.sleep(10 * 1000);
} finally {
lock.unlock();
}
+
+ Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
return;
}
}
}
+
+ public void startConsumer() throws IOException {
+ Consumer consumer = new UrlConsumer(channel());
+ channel().exchangeDeclare(getExchange(), "direct", true);
+ channel().queueDeclare(getQueueName(), durable,
+ false, autoDelete, null);
+ channel().queueBind(getQueueName(), getExchange(), getQueueName());
+ consumerTag = channel().basicConsume(getQueueName(), false, consumer);
+ logger.info("started AMQP consumer uri=" + getAmqpUri() + " exchange=" + getExchange() + " queueName=" + getQueueName() + " consumerTag=" + consumerTag);
+ }
}
transient private StarterRestarter starterRestarter;
@@ -196,6 +197,13 @@ public void start() {
// spawn off a thread to start up the amqp consumer, and try to restart it if it dies
if (!isRunning) {
starterRestarter = new StarterRestarter(AMQPUrlReceiver.class.getSimpleName() + "-starter-restarter");
+ try {
+ // try to synchronously start the consumer right now, so
+ // that the queue is bound before crawling starts
+ starterRestarter.startConsumer();
+ } catch (IOException e) {
+ logger.log(Level.SEVERE, "problem starting AMQP consumer (will try again soon)", e);
+ }
starterRestarter.start();
}
isRunning = true;
@@ -209,13 +217,6 @@ public void stop() {
lock.lock();
try {
logger.info("shutting down");
- if (connection != null && connection.isOpen()) {
- try {
- connection.close();
- } catch (IOException e) {
- logger.log(Level.SEVERE, "problem closing AMQP connection", e);
- }
- }
if (starterRestarter != null && starterRestarter.isAlive()) {
starterRestarter.interrupt();
try {
@@ -224,6 +225,14 @@ public void stop() {
}
}
starterRestarter = null;
+
+ if (connection != null && connection.isOpen()) {
+ try {
+ connection.close();
+ } catch (IOException e) {
+ logger.log(Level.SEVERE, "problem closing AMQP connection", e);
+ }
+ }
connection = null;
channel = null;
isRunning = false;
@@ -298,7 +307,7 @@ public void handleDelivery(String consumerTag, Envelope envelope,
throw new RuntimeException(e); // can't happen
}
JSONObject jo = new JSONObject(decodedBody);
-
+
if ("GET".equals(jo.getString("method"))) {
CrawlURI curi;
try {
@@ -328,7 +337,7 @@ public void handleDelivery(String consumerTag, Envelope envelope,
this.getChannel().basicAck(envelope.getDeliveryTag(), false);
}
-
+
@Override
public void handleShutdownSignal(String consumerTag,
ShutdownSignalException sig) {
@@ -337,7 +346,7 @@ public void handleShutdownSignal(String consumerTag,
} else {
logger.info("amqp channel/connection shut down consumerTag=" + consumerTag);
}
- isConsuming = false;
+ AMQPUrlReceiver.this.consumerTag = null;
}
// {
@@ -362,7 +371,7 @@ protected CrawlURI makeCrawlUri(JSONObject jo) throws URIException,
String hopPath = parentHopPath + Hop.INFERRED.getHopString();
CrawlURI curi = new CrawlURI(uuri, hopPath, via, LinkContext.INFERRED_MISC);
-
+
// set the heritable data from the parent url, passed back to us via amqp
// XXX brittle, only goes one level deep, and only handles strings and arrays, the latter of which it converts to a Set.
// 'heritableData': {'source': 'https://facebook.com/whitehouse/', 'heritable': ['source', 'heritable']}
@@ -395,7 +404,7 @@ protected CrawlURI makeCrawlUri(JSONObject jo) throws URIException,
*/
curi.setSchedulingDirective(SchedulingConstants.HIGH);
curi.setPrecedence(1);
-
+
// optional forceFetch instruction:
if (jo.has("forceFetch")) {
boolean forceFetch = jo.getBoolean("forceFetch");
@@ -425,11 +434,8 @@ public void onApplicationEvent(CrawlStateEvent event) {
break;
case RUNNING:
- logger.info("Requesting restart of the URLConsumer...");
+ logger.info("Requesting unpause of the URLConsumer...");
this.pauseConsumer = false;
- if (starterRestarter == null || !starterRestarter.isAlive()) {
- start();
- }
break;
default:
|
8689c572f29745487f2f19a50f3162f7053b8d2c
|
drools
|
JBRULES-1730: Add support for other data types when- writing processes to XML - pluggable data types support--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@21496 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/xml/BaseAbstractHandler.java b/drools-compiler/src/main/java/org/drools/xml/BaseAbstractHandler.java
index c95ee7690c4..ba201d9c993 100644
--- a/drools-compiler/src/main/java/org/drools/xml/BaseAbstractHandler.java
+++ b/drools-compiler/src/main/java/org/drools/xml/BaseAbstractHandler.java
@@ -26,15 +26,15 @@
*
*/
public abstract class BaseAbstractHandler {
- protected Set validPeers;
- protected Set validParents;
+ protected Set<Class<?>> validPeers;
+ protected Set<Class<?>> validParents;
protected boolean allowNesting;
- public Set getValidParents() {
+ public Set<Class<?>> getValidParents() {
return this.validParents;
}
- public Set getValidPeers() {
+ public Set<Class<?>> getValidPeers() {
return this.validPeers;
}
diff --git a/drools-compiler/src/main/java/org/drools/xml/Handler.java b/drools-compiler/src/main/java/org/drools/xml/Handler.java
index 4b56ca50443..78045b2701c 100644
--- a/drools-compiler/src/main/java/org/drools/xml/Handler.java
+++ b/drools-compiler/src/main/java/org/drools/xml/Handler.java
@@ -36,11 +36,11 @@ Object end(String uri,
String localName,
ExtensibleXmlParser xmlPackageReader) throws SAXException;
- Set getValidParents();
+ Set<Class<?>> getValidParents();
- Set getValidPeers();
+ Set<Class<?>> getValidPeers();
boolean allowNesting();
- Class generateNodeFor();
+ Class<?> generateNodeFor();
}
\ No newline at end of file
diff --git a/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java b/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java
index ee57f068222..2c161e7c7a6 100644
--- a/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java
+++ b/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java
@@ -10,6 +10,7 @@
import org.drools.process.core.context.variable.Variable;
import org.drools.process.core.context.variable.VariableScope;
import org.drools.process.core.datatype.DataType;
+import org.drools.process.core.datatype.impl.type.ObjectDataType;
import org.drools.workflow.core.Connection;
import org.drools.workflow.core.Node;
import org.drools.workflow.core.WorkflowProcess;
@@ -116,7 +117,7 @@ private void visitVariables(List<Variable> variables, StringBuffer xmlDump) {
visitDataType(variable.getType(), xmlDump);
Object value = variable.getValue();
if (value != null) {
- visitValue(variable.getValue(), xmlDump);
+ visitValue(variable.getValue(), variable.getType(), xmlDump);
}
xmlDump.append(" </variable>" + EOL);
}
@@ -134,16 +135,17 @@ private void visitSwimlanes(Collection<Swimlane> swimlanes, StringBuffer xmlDump
}
}
- private void visitDataType(DataType dataType, StringBuffer xmlDump) {
- xmlDump.append(" <type name=\"" + dataType.getClass().getName() + "\" />" + EOL);
+ public static void visitDataType(DataType dataType, StringBuffer xmlDump) {
+ xmlDump.append(" <type name=\"" + dataType.getClass().getName() + "\" ");
+ // TODO make this pluggable so datatypes can write out other properties as well
+ if (dataType instanceof ObjectDataType) {
+ xmlDump.append("className=\"" + ((ObjectDataType) dataType).getClassName() + "\" ");
+ }
+ xmlDump.append("/>" + EOL);
}
- private void visitValue(Object value, StringBuffer xmlDump) {
- if (value instanceof String) {
- xmlDump.append(" <value>" + XmlDumper.replaceIllegalChars((String) value) + "</value>" + EOL);
- } else {
- throw new IllegalArgumentException("Unsupported value type: " + value);
- }
+ public static void visitValue(Object value, DataType dataType, StringBuffer xmlDump) {
+ xmlDump.append(" <value>" + XmlDumper.replaceIllegalChars(dataType.writeValue(value)) + "</value>" + EOL);
}
private void visitNodes(WorkflowProcess process, StringBuffer xmlDump, boolean includeMeta) {
diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/ParameterHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/ParameterHandler.java
index 6b97e927fb4..76b644bba54 100644
--- a/drools-compiler/src/main/java/org/drools/xml/processes/ParameterHandler.java
+++ b/drools-compiler/src/main/java/org/drools/xml/processes/ParameterHandler.java
@@ -1,111 +1,75 @@
package org.drools.xml.processes;
-import java.io.Serializable;
import java.util.HashSet;
import org.drools.process.core.ParameterDefinition;
+import org.drools.process.core.TypeObject;
+import org.drools.process.core.ValueObject;
import org.drools.process.core.Work;
import org.drools.process.core.datatype.DataType;
-import org.drools.process.core.datatype.impl.type.BooleanDataType;
-import org.drools.process.core.datatype.impl.type.FloatDataType;
-import org.drools.process.core.datatype.impl.type.IntegerDataType;
-import org.drools.process.core.datatype.impl.type.StringDataType;
import org.drools.process.core.impl.ParameterDefinitionImpl;
import org.drools.xml.BaseAbstractHandler;
import org.drools.xml.ExtensibleXmlParser;
import org.drools.xml.Handler;
-import org.w3c.dom.Element;
-import org.w3c.dom.Text;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-public class ParameterHandler extends BaseAbstractHandler
- implements
- Handler {
+public class ParameterHandler extends BaseAbstractHandler implements Handler {
+
public ParameterHandler() {
- if ( (this.validParents == null) && (this.validPeers == null) ) {
- this.validParents = new HashSet();
- this.validParents.add( Work.class );
-
- this.validPeers = new HashSet();
- this.validPeers.add( null );
-
+ if ((this.validParents == null) && (this.validPeers == null)) {
+ this.validParents = new HashSet<Class<?>>();
+ this.validParents.add(Work.class);
+ this.validPeers = new HashSet<Class<?>>();
+ this.validPeers.add(null);
this.allowNesting = false;
}
}
-
-
public Object start(final String uri,
final String localName,
final Attributes attrs,
final ExtensibleXmlParser parser) throws SAXException {
- parser.startElementBuilder( localName,
- attrs );
- return null;
+ parser.startElementBuilder(localName, attrs);
+ final String name = attrs.getValue("name");
+ emptyAttributeCheck(localName, "name", name, parser);
+ Work work = (Work) parser.getParent();
+ ParameterDefinition parameterDefinition = new ParameterDefinitionImpl();
+ parameterDefinition.setName(name);
+ work.addParameterDefinition(parameterDefinition);
+ return new ParameterWrapper(parameterDefinition, work);
}
public Object end(final String uri,
final String localName,
final ExtensibleXmlParser parser) throws SAXException {
- final Element element = parser.endElementBuilder();
- Work work = (Work) parser.getParent();
- final String name = element.getAttribute("name");
- emptyAttributeCheck(localName, "name", name, parser);
- final String type = element.getAttribute("type");
- emptyAttributeCheck(localName, "type", type, parser);
- DataType dataType = null;
- try {
- dataType = (DataType) Class.forName(type).newInstance();
- } catch (ClassNotFoundException e) {
- throw new SAXParseException(
- "Could not find datatype " + name, parser.getLocator());
- } catch (InstantiationException e) {
- throw new SAXParseException(
- "Could not instantiate datatype " + name, parser.getLocator());
- } catch (IllegalAccessException e) {
- throw new SAXParseException(
- "Could not access datatype " + name, parser.getLocator());
- }
- String text = ((Text)element.getChildNodes().item( 0 )).getWholeText();
- if (text != null) {
- text = text.trim();
- if ("".equals(text)) {
- text = null;
- }
- }
- Object value = restoreValue(text, dataType, parser);
- ParameterDefinition parameterDefinition = new ParameterDefinitionImpl(name, dataType);
- work.addParameterDefinition(parameterDefinition);
- work.setParameter(name, value);
+ parser.endElementBuilder();
return null;
}
- private Serializable restoreValue(String text, DataType dataType, ExtensibleXmlParser parser) throws SAXException {
- if (text == null || "".equals(text)) {
- return null;
- }
- if (dataType == null) {
- throw new SAXParseException(
- "Null datatype", parser.getLocator());
- }
- if (dataType instanceof StringDataType) {
- return text;
- } else if (dataType instanceof IntegerDataType) {
- return new Integer(text);
- } else if (dataType instanceof FloatDataType) {
- return new Float(text);
- } else if (dataType instanceof BooleanDataType) {
- return new Boolean(text);
- } else {
- throw new SAXParseException(
- "Unknown datatype " + dataType, parser.getLocator());
- }
+ public Class<?> generateNodeFor() {
+ return ParameterWrapper.class;
}
-
- public Class generateNodeFor() {
- return null;
+
+ public class ParameterWrapper implements TypeObject, ValueObject {
+ private Work work;
+ private ParameterDefinition parameterDefinition;
+ public ParameterWrapper(ParameterDefinition parameterDefinition, Work work) {
+ this.work = work;
+ this.parameterDefinition = parameterDefinition;
+ }
+ public DataType getType() {
+ return parameterDefinition.getType();
+ }
+ public void setType(DataType type) {
+ parameterDefinition.setType(type);
+ }
+ public Object getValue() {
+ return work.getParameter(parameterDefinition.getName());
+ }
+ public void setValue(Object value) {
+ work.setParameter(parameterDefinition.getName(), value);
+ }
}
}
diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/TypeHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/TypeHandler.java
index d3816891c01..ca816ed07b3 100644
--- a/drools-compiler/src/main/java/org/drools/xml/processes/TypeHandler.java
+++ b/drools-compiler/src/main/java/org/drools/xml/processes/TypeHandler.java
@@ -2,8 +2,9 @@
import java.util.HashSet;
-import org.drools.process.core.context.variable.Variable;
+import org.drools.process.core.TypeObject;
import org.drools.process.core.datatype.DataType;
+import org.drools.process.core.datatype.impl.type.ObjectDataType;
import org.drools.xml.BaseAbstractHandler;
import org.drools.xml.ExtensibleXmlParser;
import org.drools.xml.Handler;
@@ -16,10 +17,10 @@ public class TypeHandler extends BaseAbstractHandler
Handler {
public TypeHandler() {
if ( (this.validParents == null) && (this.validPeers == null) ) {
- this.validParents = new HashSet();
- this.validParents.add( Variable.class );
+ this.validParents = new HashSet<Class<?>>();
+ this.validParents.add( TypeObject.class );
- this.validPeers = new HashSet();
+ this.validPeers = new HashSet<Class<?>>();
this.validPeers.add( null );
this.allowNesting = false;
@@ -34,12 +35,18 @@ public Object start(final String uri,
final ExtensibleXmlParser parser) throws SAXException {
parser.startElementBuilder( localName,
attrs );
- Variable variable = (Variable) parser.getParent();
+ TypeObject typeable = (TypeObject) parser.getParent();
final String name = attrs.getValue("name");
emptyAttributeCheck(localName, "name", name, parser);
DataType dataType = null;
try {
dataType = (DataType) Class.forName(name).newInstance();
+ // TODO make this pluggable so datatypes can read in other properties as well
+ if (dataType instanceof ObjectDataType) {
+ final String className = attrs.getValue("className");
+ emptyAttributeCheck(localName, "className", className, parser);
+ ((ObjectDataType) dataType).setClassName(className);
+ }
} catch (ClassNotFoundException e) {
throw new SAXParseException(
"Could not find datatype " + name, parser.getLocator());
@@ -51,7 +58,7 @@ public Object start(final String uri,
"Could not access datatype " + name, parser.getLocator());
}
- variable.setType(dataType);
+ typeable.setType(dataType);
return dataType;
}
@@ -62,7 +69,7 @@ public Object end(final String uri,
return null;
}
- public Class generateNodeFor() {
+ public Class<?> generateNodeFor() {
return DataType.class;
}
diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/ValueHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/ValueHandler.java
index e37e9df1de8..956d41d91f0 100644
--- a/drools-compiler/src/main/java/org/drools/xml/processes/ValueHandler.java
+++ b/drools-compiler/src/main/java/org/drools/xml/processes/ValueHandler.java
@@ -1,14 +1,9 @@
package org.drools.xml.processes;
-import java.io.Serializable;
import java.util.HashSet;
-import org.drools.process.core.context.variable.Variable;
+import org.drools.process.core.ValueObject;
import org.drools.process.core.datatype.DataType;
-import org.drools.process.core.datatype.impl.type.BooleanDataType;
-import org.drools.process.core.datatype.impl.type.FloatDataType;
-import org.drools.process.core.datatype.impl.type.IntegerDataType;
-import org.drools.process.core.datatype.impl.type.StringDataType;
import org.drools.xml.BaseAbstractHandler;
import org.drools.xml.ExtensibleXmlParser;
import org.drools.xml.Handler;
@@ -18,15 +13,14 @@
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
-public class ValueHandler extends BaseAbstractHandler
- implements
- Handler {
+public class ValueHandler extends BaseAbstractHandler implements Handler {
+
public ValueHandler() {
if ( (this.validParents == null) && (this.validPeers == null) ) {
- this.validParents = new HashSet();
- this.validParents.add( Variable.class );
+ this.validParents = new HashSet<Class<?>>();
+ this.validParents.add( ValueObject.class );
- this.validPeers = new HashSet();
+ this.validPeers = new HashSet<Class<?>>();
this.validPeers.add( null );
this.allowNesting = false;
@@ -48,7 +42,7 @@ public Object end(final String uri,
final String localName,
final ExtensibleXmlParser parser) throws SAXException {
final Element element = parser.endElementBuilder();
- Variable variable = (Variable) parser.getParent();
+ ValueObject valueObject = (ValueObject) parser.getParent();
String text = ((Text)element.getChildNodes().item( 0 )).getWholeText();
if (text != null) {
text.trim();
@@ -56,12 +50,12 @@ public Object end(final String uri,
text = null;
}
}
- Serializable value = restoreValue(text, variable.getType(), parser);
- variable.setValue(value);
+ Object value = restoreValue(text, valueObject.getType(), parser);
+ valueObject.setValue(value);
return null;
}
- private Serializable restoreValue(String text, DataType dataType, ExtensibleXmlParser parser) throws SAXException {
+ private Object restoreValue(String text, DataType dataType, ExtensibleXmlParser parser) throws SAXException {
if (text == null || "".equals(text)) {
return null;
}
@@ -69,21 +63,10 @@ private Serializable restoreValue(String text, DataType dataType, ExtensibleXmlP
throw new SAXParseException(
"Null datatype", parser.getLocator());
}
- if (dataType instanceof StringDataType) {
- return text;
- } else if (dataType instanceof IntegerDataType) {
- return new Integer(text);
- } else if (dataType instanceof FloatDataType) {
- return new Float(text);
- } else if (dataType instanceof BooleanDataType) {
- return new Boolean(text);
- } else {
- throw new SAXParseException(
- "Unknown datatype " + dataType, parser.getLocator());
- }
+ return dataType.readValue(text);
}
- public Class generateNodeFor() {
+ public Class<?> generateNodeFor() {
return null;
}
diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/VariableHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/VariableHandler.java
index fb4462cfd37..906f991cec4 100644
--- a/drools-compiler/src/main/java/org/drools/xml/processes/VariableHandler.java
+++ b/drools-compiler/src/main/java/org/drools/xml/processes/VariableHandler.java
@@ -20,10 +20,10 @@ public class VariableHandler extends BaseAbstractHandler
Handler {
public VariableHandler() {
if ( (this.validParents == null) && (this.validPeers == null) ) {
- this.validParents = new HashSet();
+ this.validParents = new HashSet<Class<?>>();
this.validParents.add( Process.class );
- this.validPeers = new HashSet();
+ this.validPeers = new HashSet<Class<?>>();
this.validPeers.add( null );
this.allowNesting = false;
@@ -68,7 +68,7 @@ public Object end(final String uri,
return null;
}
- public Class generateNodeFor() {
+ public Class<?> generateNodeFor() {
return Variable.class;
}
diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java
index c04e09ca5ef..9a853034b87 100644
--- a/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java
+++ b/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java
@@ -4,10 +4,11 @@
import org.drools.process.core.ParameterDefinition;
import org.drools.process.core.Work;
+import org.drools.process.core.datatype.DataType;
import org.drools.workflow.core.Node;
import org.drools.workflow.core.node.WorkItemNode;
import org.drools.xml.ExtensibleXmlParser;
-import org.drools.xml.XmlDumper;
+import org.drools.xml.XmlWorkflowProcessDumper;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
@@ -29,7 +30,7 @@ protected Node createNode() {
return new WorkItemNode();
}
- public Class generateNodeFor() {
+ public Class<?> generateNodeFor() {
return WorkItemNode.class;
}
@@ -76,18 +77,15 @@ protected void visitWork(Work work, StringBuffer xmlDump, boolean includeMeta) {
if (work != null) {
xmlDump.append(" <work name=\"" + work.getName() + "\" >" + EOL);
for (ParameterDefinition paramDefinition: work.getParameterDefinitions()) {
- xmlDump.append(" <parameter name=\"" + paramDefinition.getName() + "\" " +
- "type=\"" + paramDefinition.getType().getClass().getName() + "\" ");
+ DataType dataType = paramDefinition.getType();
+ xmlDump.append(" <parameter name=\"" + paramDefinition.getName() + "\" >" + EOL + " ");
+ XmlWorkflowProcessDumper.visitDataType(dataType, xmlDump);
Object value = work.getParameter(paramDefinition.getName());
- if (value == null) {
- xmlDump.append("/>" + EOL);
- } else {
- if (value instanceof String) {
- xmlDump.append(">" + XmlDumper.replaceIllegalChars((String) value) + "</parameter>" + EOL);
- } else {
- throw new IllegalArgumentException("Unsupported value type: " + value);
- }
+ if (value != null) {
+ xmlDump.append(" ");
+ XmlWorkflowProcessDumper.visitValue(value, dataType, xmlDump);
}
+ xmlDump.append(" </parameter>" + EOL);
}
xmlDump.append(" </work>" + EOL);
}
diff --git a/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd b/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd
index 64208d28dae..566007adfdc 100644
--- a/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd
+++ b/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd
@@ -69,6 +69,7 @@
<xs:element name="type">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required"/>
+ <xs:attribute name="className" type="xs:string" />
</xs:complexType>
</xs:element>
<xs:element name="value">
@@ -269,12 +270,11 @@
</xs:element>
<xs:element name="parameter">
<xs:complexType>
- <xs:simpleContent>
- <xs:extension base="xs:string">
- <xs:attribute name="name" type="xs:string" use="required"/>
- <xs:attribute name="type" type="xs:string" use="required"/>
- </xs:extension>
- </xs:simpleContent>
+ <xs:choice minOccurs="0" maxOccurs="unbounded">
+ <xs:element ref="drools:type"/>
+ <xs:element ref="drools:value"/>
+ </xs:choice>
+ <xs:attribute name="name" type="xs:string"/>
</xs:complexType>
</xs:element>
<xs:element name="mapping">
diff --git a/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java b/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java
index 3a1531af6a1..5e9998d0733 100644
--- a/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java
+++ b/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java
@@ -10,12 +10,14 @@
import junit.framework.TestCase;
+import org.drools.Person;
import org.drools.compiler.PackageBuilderConfiguration;
import org.drools.process.core.ParameterDefinition;
import org.drools.process.core.Work;
import org.drools.process.core.context.swimlane.Swimlane;
import org.drools.process.core.context.variable.Variable;
import org.drools.process.core.datatype.impl.type.IntegerDataType;
+import org.drools.process.core.datatype.impl.type.ListDataType;
import org.drools.process.core.datatype.impl.type.ObjectDataType;
import org.drools.process.core.datatype.impl.type.StringDataType;
import org.drools.process.core.event.EventTypeFilter;
@@ -131,6 +133,23 @@ public void addNode(Node node) {
variable.setType(new IntegerDataType());
variable.setValue(2);
variables.add(variable);
+ variable = new Variable();
+ variable.setName("variable3");
+ variable.setType(new ObjectDataType("org.drools.Person"));
+ Person person = new Person();
+ person.setName("John");
+ variable.setValue(person);
+ variables.add(variable);
+ variable = new Variable();
+ variable.setName("variable3");
+ ListDataType listDataType = new ListDataType();
+ listDataType.setType(new ObjectDataType("java.lang.Integer"));
+ variable.setType(listDataType);
+ List<Integer> list = new ArrayList<Integer>();
+ list.add(10);
+ list.add(20);
+ variable.setValue(list);
+ variables.add(variable);
process.getVariableScope().setVariables(variables);
Swimlane swimlane = new Swimlane();
diff --git a/drools-core/src/main/java/org/drools/process/core/ParameterDefinition.java b/drools-core/src/main/java/org/drools/process/core/ParameterDefinition.java
index 1f62b474cf4..b2ac021711a 100644
--- a/drools-core/src/main/java/org/drools/process/core/ParameterDefinition.java
+++ b/drools-core/src/main/java/org/drools/process/core/ParameterDefinition.java
@@ -1,17 +1,13 @@
package org.drools.process.core;
-import org.drools.process.core.datatype.DataType;
/**
*
* @author <a href="mailto:[email protected]">Kris Verlaenen</a>
*/
-public interface ParameterDefinition {
+public interface ParameterDefinition extends TypeObject {
String getName();
void setName(String name);
- DataType getType();
- void setType(DataType type);
-
}
diff --git a/drools-core/src/main/java/org/drools/process/core/TypeObject.java b/drools-core/src/main/java/org/drools/process/core/TypeObject.java
new file mode 100644
index 00000000000..690e4f2dae5
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/process/core/TypeObject.java
@@ -0,0 +1,10 @@
+package org.drools.process.core;
+
+import org.drools.process.core.datatype.DataType;
+
+public interface TypeObject {
+
+ DataType getType();
+ void setType(DataType type);
+
+}
diff --git a/drools-core/src/main/java/org/drools/process/core/ValueObject.java b/drools-core/src/main/java/org/drools/process/core/ValueObject.java
new file mode 100644
index 00000000000..7f73b7de994
--- /dev/null
+++ b/drools-core/src/main/java/org/drools/process/core/ValueObject.java
@@ -0,0 +1,8 @@
+package org.drools.process.core;
+
+public interface ValueObject extends TypeObject {
+
+ Object getValue();
+
+ void setValue(Object value);
+}
diff --git a/drools-core/src/main/java/org/drools/process/core/context/variable/Variable.java b/drools-core/src/main/java/org/drools/process/core/context/variable/Variable.java
index 6ee0a2d0106..b9f061c8e67 100644
--- a/drools-core/src/main/java/org/drools/process/core/context/variable/Variable.java
+++ b/drools-core/src/main/java/org/drools/process/core/context/variable/Variable.java
@@ -18,7 +18,8 @@
import java.io.Serializable;
-import org.drools.process.core.context.variable.Variable;
+import org.drools.process.core.TypeObject;
+import org.drools.process.core.ValueObject;
import org.drools.process.core.datatype.DataType;
import org.drools.process.core.datatype.impl.type.UndefinedDataType;
@@ -27,13 +28,13 @@
*
* @author <a href="mailto:[email protected]">Kris Verlaenen</a>
*/
-public class Variable implements Serializable {
+public class Variable implements TypeObject, ValueObject, Serializable {
private static final long serialVersionUID = 400L;
- private String name;
- private DataType type;
- private Serializable value;
+ private String name;
+ private DataType type;
+ private Object value;
public Variable() {
this.type = UndefinedDataType.getInstance();
@@ -58,11 +59,11 @@ public void setType(final DataType type) {
this.type = type;
}
- public Serializable getValue() {
+ public Object getValue() {
return this.value;
}
- public void setValue(final Serializable value) {
+ public void setValue(final Object value) {
if ( this.type.verifyDataType( value ) ) {
this.value = value;
} else {
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/DataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/DataType.java
index 2e3717fcb7b..09336b9ffe6 100644
--- a/drools-core/src/main/java/org/drools/process/core/datatype/DataType.java
+++ b/drools-core/src/main/java/org/drools/process/core/datatype/DataType.java
@@ -29,5 +29,9 @@ public interface DataType extends Externalizable {
* Returns true if the given value is a valid value of this data type.
*/
boolean verifyDataType(Object value);
+
+ String writeValue(Object value);
+
+ Object readValue(String value);
}
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/BooleanDataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/BooleanDataType.java
index c5e24a7e701..aa487e54a08 100644
--- a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/BooleanDataType.java
+++ b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/BooleanDataType.java
@@ -45,4 +45,12 @@ public boolean verifyDataType(final Object value) {
}
return false;
}
+
+ public Object readValue(String value) {
+ return new Boolean(value);
+ }
+
+ public String writeValue(Object value) {
+ return (Boolean) value ? "true" : "false";
+ }
}
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/DateDataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/DateDataType.java
deleted file mode 100644
index 8e9209d7d68..00000000000
--- a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/DateDataType.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package org.drools.process.core.datatype.impl.type;
-
-/*
- * 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.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.Date;
-
-import org.drools.process.core.datatype.DataType;
-
-/**
- * Representation of a date datatype.
- *
- * @author <a href="mailto:[email protected]">Kris Verlaenen</a>
- */
-public final class DateDataType implements DataType {
-
- private static final long serialVersionUID = 400L;
-
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
- }
-
- public void writeExternal(ObjectOutput out) throws IOException {
- }
-
- public boolean verifyDataType(final Object value) {
- if ( value instanceof Date ) {
- return true;
- }
- return false;
- }
-}
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/FloatDataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/FloatDataType.java
index 7ab51d3a39e..7236b51dde9 100644
--- a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/FloatDataType.java
+++ b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/FloatDataType.java
@@ -48,4 +48,13 @@ public boolean verifyDataType(final Object value) {
return false;
}
}
+
+ public Object readValue(String value) {
+ return new Float(value);
+ }
+
+ public String writeValue(Object value) {
+ Float f = (Float) value;
+ return f == null ? "" : f.toString();
+ }
}
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/IntegerDataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/IntegerDataType.java
index b760b71d89c..45723150326 100644
--- a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/IntegerDataType.java
+++ b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/IntegerDataType.java
@@ -48,4 +48,14 @@ public boolean verifyDataType(final Object value) {
return false;
}
}
+
+ public Object readValue(String value) {
+ return new Integer(value);
+ }
+
+ public String writeValue(Object value) {
+ Integer i = (Integer) value;
+ return i == null ? "" : i.toString();
+ }
+
}
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/ListDataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/ListDataType.java
index ee84402f9df..270d1aedd7c 100644
--- a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/ListDataType.java
+++ b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/ListDataType.java
@@ -16,25 +16,30 @@
* limitations under the License.
*/
-import org.drools.process.core.datatype.DataType;
-
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Iterator;
import java.util.List;
+import org.drools.process.core.TypeObject;
+import org.drools.process.core.datatype.DataType;
+
/**
* Representation of a list datatype.
* All elements in the list must have the same datatype.
*
* @author <a href="mailto:[email protected]">Kris Verlaenen</a>
*/
-public class ListDataType implements DataType {
+public class ListDataType extends ObjectDataType implements TypeObject {
private static final long serialVersionUID = 400L;
private DataType dataType;
+
+ public ListDataType() {
+ setClassName("java.util.List");
+ }
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
dataType = (DataType)in.readObject();
@@ -44,18 +49,15 @@ public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(dataType);
}
- public ListDataType() {
- }
-
public ListDataType(DataType dataType) {
- setDataType(dataType);
+ setType(dataType);
}
- public void setDataType(final DataType dataType) {
+ public void setType(final DataType dataType) {
this.dataType = dataType;
}
- public DataType getDataType() {
+ public DataType getType() {
return this.dataType;
}
@@ -64,8 +66,8 @@ public boolean verifyDataType(final Object value) {
return true;
}
if (value instanceof List) {
- for (final Iterator<?> it = ((List<?>) value).iterator(); it.hasNext();) {
- if (!this.dataType.verifyDataType(it.next())) {
+ for (Object o: (List<?>) value) {
+ if (dataType != null && !dataType.verifyDataType(o)) {
return false;
}
}
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/ObjectDataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/ObjectDataType.java
index 650edbacfc4..7d81500b919 100644
--- a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/ObjectDataType.java
+++ b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/ObjectDataType.java
@@ -22,12 +22,14 @@
import org.drools.process.core.datatype.DataType;
+import com.thoughtworks.xstream.XStream;
+
/**
* Representation of an object datatype.
*
* @author <a href="mailto:[email protected]">Kris Verlaenen</a>
*/
-public final class ObjectDataType implements DataType {
+public class ObjectDataType implements DataType {
private static final long serialVersionUID = 4L;
@@ -49,9 +51,11 @@ public void setClassName(String className) {
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ className = in.readUTF();
}
public void writeExternal(ObjectOutput out) throws IOException {
+ out.writeUTF(className);
}
public boolean verifyDataType(final Object value) {
@@ -66,4 +70,14 @@ public boolean verifyDataType(final Object value) {
}
return false;
}
+
+ public Object readValue(String value) {
+ XStream xstream = new XStream();
+ return xstream.fromXML(value);
+ }
+
+ public String writeValue(Object value) {
+ XStream xstream = new XStream();
+ return xstream.toXML(value);
+ }
}
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/StringDataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/StringDataType.java
index 8cfef116939..af2aa2b1e72 100644
--- a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/StringDataType.java
+++ b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/StringDataType.java
@@ -27,9 +27,7 @@
*
* @author <a href="mailto:[email protected]">Kris Verlaenen</a>
*/
-public class StringDataType
- implements
- DataType {
+public class StringDataType implements DataType {
private static final long serialVersionUID = 400L;
@@ -48,4 +46,13 @@ public boolean verifyDataType(final Object value) {
return false;
}
}
+
+ public Object readValue(String value) {
+ return value;
+ }
+
+ public String writeValue(Object value) {
+ return (String) value;
+ }
+
}
diff --git a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/UndefinedDataType.java b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/UndefinedDataType.java
index bca9519d66a..a29954480a5 100644
--- a/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/UndefinedDataType.java
+++ b/drools-core/src/main/java/org/drools/process/core/datatype/impl/type/UndefinedDataType.java
@@ -51,4 +51,13 @@ public boolean verifyDataType(final Object value) {
}
return false;
}
+
+ public Object readValue(String value) {
+ throw new IllegalArgumentException("Undefined datatype");
+ }
+
+ public String writeValue(Object value) {
+ throw new IllegalArgumentException("Undefined datatype");
+ }
+
}
diff --git a/drools-core/src/main/java/org/drools/process/core/impl/ParameterDefinitionImpl.java b/drools-core/src/main/java/org/drools/process/core/impl/ParameterDefinitionImpl.java
index 61acfc2ef6c..1d97db1d2b8 100644
--- a/drools-core/src/main/java/org/drools/process/core/impl/ParameterDefinitionImpl.java
+++ b/drools-core/src/main/java/org/drools/process/core/impl/ParameterDefinitionImpl.java
@@ -11,4 +11,9 @@
*/
public class ParameterDefinitionImpl implements ParameterDefinition, Serializable {
- private static final long serialVersionUID = 400L;
private String name;
private DataType type;
public ParameterDefinitionImpl(String name, DataType type) {
setName(name);
setType(type);
}
public String getName() {
return name;
}
public void setName(String name) {
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
this.name = name;
}
public DataType getType() {
return type;
}
public void setType(DataType type) {
if (type == null) {
throw new IllegalArgumentException("Data type cannot be null");
}
this.type = type;
}
public String toString() {
return name;
}
}
\ No newline at end of file
+ private static final long serialVersionUID = 400L;
private String name;
private DataType type;
+
+ public ParameterDefinitionImpl() {
+ }
+
+ public ParameterDefinitionImpl(String name, DataType type) {
setName(name);
setType(type);
}
public String getName() {
return name;
}
public void setName(String name) {
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
this.name = name;
}
public DataType getType() {
return type;
}
public void setType(DataType type) {
if (type == null) {
throw new IllegalArgumentException("Data type cannot be null");
}
this.type = type;
}
public String toString() {
return name;
}
}
\ No newline at end of file
diff --git a/drools-core/src/main/resources/META-INF/WorkDefinitions.conf b/drools-core/src/main/resources/META-INF/WorkDefinitions.conf
index 36e3787162e..39ad4f3691d 100644
--- a/drools-core/src/main/resources/META-INF/WorkDefinitions.conf
+++ b/drools-core/src/main/resources/META-INF/WorkDefinitions.conf
@@ -3,7 +3,6 @@
// The allowed properties are name, parameters, displayName, icon and customEditor
// The returned result should thus be of type List<Map<String, Object>>
import org.drools.process.core.datatype.impl.type.StringDataType;
-import org.drools.process.core.datatype.impl.type.DateDataType;
[
diff --git a/drools-core/src/test/java/org/drools/process/ForEachTest.java b/drools-core/src/test/java/org/drools/process/ForEachTest.java
index e7ad535a773..a93bd432e23 100644
--- a/drools-core/src/test/java/org/drools/process/ForEachTest.java
+++ b/drools-core/src/test/java/org/drools/process/ForEachTest.java
@@ -42,7 +42,7 @@ public void testForEach() {
ListDataType listDataType = new ListDataType();
ObjectDataType personDataType = new ObjectDataType();
personDataType.setClassName("org.drools.Person");
- listDataType.setDataType(personDataType);
+ listDataType.setType(personDataType);
variable.setType(listDataType);
variables.add(variable);
process.getVariableScope().setVariables(variables);
|
75b81dcbd26a11d5b370ea5bdf102c2d62ebd0c3
|
drools
|
Fix OutOfBoundException on- MemoryFileSystem.existsFile("")--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFileSystem.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFileSystem.java
index 5be94a3ab0f..1f81319f79a 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFileSystem.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFileSystem.java
@@ -168,13 +168,16 @@ public boolean existsFolder(MemoryFolder folder) {
public boolean existsFolder(String path) {
if (path == null) {
- throw new NullPointerException("Path can not be null!");
+ throw new NullPointerException("Folder path can not be null!");
}
- return folders.get( path.length() > 0 ? MemoryFolder.trimLeadingAndTrailing( path ) : path ) != null;
+ return folders.get(MemoryFolder.trimLeadingAndTrailing(path)) != null;
}
public boolean existsFile(String path) {
- return fileContents.containsKey( MemoryFolder.trimLeadingAndTrailing( path ) );
+ if (path == null) {
+ throw new NullPointerException("File path can not be null!");
+ }
+ return fileContents.containsKey(MemoryFolder.trimLeadingAndTrailing(path));
}
public void createFolder(MemoryFolder folder) {
diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFolder.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFolder.java
index f22294b6868..e5f48df9295 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFolder.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/compiler/io/memory/MemoryFolder.java
@@ -98,13 +98,14 @@ public Folder getParent() {
}
}
-
-
return pFolder;
}
public static String trimLeadingAndTrailing(String p) {
+ if (p.isEmpty()) {
+ return p;
+ }
while ( p.charAt( 0 ) == '/') {
p = p.substring( 1 );
}
diff --git a/drools-compiler/src/test/java/org/drools/compiler/kproject/memory/MemoryFolderTest.java b/drools-compiler/src/test/java/org/drools/compiler/kproject/memory/MemoryFolderTest.java
index 8ef26dfa06f..1da5a39e63a 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/kproject/memory/MemoryFolderTest.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/kproject/memory/MemoryFolderTest.java
@@ -191,4 +191,12 @@ public void testFolderRemoval() throws IOException {
assertFalse( fs.getFile( "src/main/resources/org/domain/MyClass4.java" ).exists() );
}
+ @Test
+ public void trimLeadingAndTrailing() {
+ assertEquals("", MemoryFolder.trimLeadingAndTrailing(""));
+ assertEquals("src/main", MemoryFolder.trimLeadingAndTrailing("/src/main"));
+ assertEquals("src/main", MemoryFolder.trimLeadingAndTrailing("src/main/"));
+ assertEquals("src/main", MemoryFolder.trimLeadingAndTrailing("/src/main/"));
+ }
+
}
|
83fb0a1ee1d16ecb4339c7c822ebfcc21430be7f
|
arquillian$arquillian-graphene
|
ARQGRA-286: support for PhantomJS debugging + big refactoring
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/graphene-webdriver/graphene-webdriver-depchain/pom.xml b/graphene-webdriver/graphene-webdriver-depchain/pom.xml
index b740f0d2b..7ed2f786e 100644
--- a/graphene-webdriver/graphene-webdriver-depchain/pom.xml
+++ b/graphene-webdriver/graphene-webdriver-depchain/pom.xml
@@ -22,11 +22,6 @@
<artifactId>graphene-webdriver-impl</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>org.jboss.arquillian.graphene</groupId>
- <artifactId>graphene-webdriver-drone</artifactId>
- <version>${project.version}</version>
- </dependency>
<!-- Arquillian Drone -->
<dependency>
diff --git a/graphene-webdriver/graphene-webdriver-ftest/pom.xml b/graphene-webdriver/graphene-webdriver-ftest/pom.xml
index bd49746f7..e2f89c68d 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/pom.xml
+++ b/graphene-webdriver/graphene-webdriver-ftest/pom.xml
@@ -29,6 +29,14 @@
<type>pom</type>
<scope>test</scope>
</dependency>
+
+ <dependency>
+ <groupId>org.jboss.arquillian.graphene</groupId>
+ <artifactId>graphene-webdriver-impl</artifactId>
+ <version>${project.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
<!-- Arquillian JUnit -->
<dependency>
@@ -44,13 +52,6 @@
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.jboss.arquillian.test</groupId>
- <artifactId>arquillian-test-impl-base</artifactId>
- <classifier>tests</classifier>
- <scope>test</scope>
- </dependency>
-
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
@@ -95,6 +96,13 @@
<browser>chrome</browser>
</properties>
</profile>
+
+ <profile>
+ <id>webdriver-phantomjs</id>
+ <properties>
+ <browser>phantomjs</browser>
+ </properties>
+ </profile>
<profile>
<id>webdriver-firefox</id>
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/enricher/TestInitializingGenericPageObjects3.java
index 516ba9ddc..996b52eb6 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/enricher/TestInitializingGenericPageObjects3.java
@@ -21,9 +21,9 @@
*/
package org.jboss.arquillian.graphene.enricher;
-import org.jboss.arquillian.graphene.enricher.fragment.AbstractPageFragmentStub;
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.spi.annotations.Page;
import org.jboss.arquillian.junit.Arquillian;
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
new file mode 100644
index 000000000..fa5a46a41
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/InterceptorRegistrationExtension.java
@@ -0,0 +1,41 @@
+package org.jboss.arquillian.graphene.ftest.intercept;
+
+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.graphene.proxy.GrapheneProxyInstance;
+import org.jboss.arquillian.graphene.proxy.Interceptor;
+import org.jboss.arquillian.graphene.proxy.InvocationContext;
+import org.jboss.arquillian.test.spi.event.suite.Test;
+import org.openqa.selenium.WebDriver;
+
+public class InterceptorRegistrationExtension implements LoadableExtension {
+
+ public static volatile boolean invoked = false;
+
+ @Override
+ public void register(ExtensionBuilder builder) {
+ builder.observer(this.getClass());
+ }
+
+ public void register_interceptor(@Observes EventContext<Test> ctx) {
+ invoked = false;
+ try {
+ Test event = ctx.getEvent();
+ if (event.getTestClass().getJavaClass() == TestInterceptorRegistration.class) {
+ WebDriver browser = GrapheneContext.getProxy();
+ ((GrapheneProxyInstance) browser).registerInterceptor(new Interceptor() {
+
+ @Override
+ public Object intercept(InvocationContext context) throws Throwable {
+ invoked = true;
+ return context.invoke();
+ }
+ });
+ }
+ } finally {
+ ctx.proceed();
+ }
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/TestInterceptorRegistration.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/TestInterceptorRegistration.java
new file mode 100644
index 000000000..c0b5fc74a
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/TestInterceptorRegistration.java
@@ -0,0 +1,52 @@
+package org.jboss.arquillian.graphene.ftest.intercept;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.jboss.arquillian.drone.api.annotation.Drone;
+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.junit.Arquillian;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.WebDriver;
+
+@RunWith(Arquillian.class)
+public class TestInterceptorRegistration {
+ @Drone
+ private WebDriver browser;
+
+ private boolean interceptor_registered_before_test_invoked = false;
+
+ @Before
+ public void resetFlags() {
+ interceptor_registered_before_test_invoked = false;
+ }
+
+ @Before
+ public void register_interceptor_before_test() {
+ ((GrapheneProxyInstance) browser).registerInterceptor(new Interceptor() {
+ public Object intercept(InvocationContext context) throws Throwable {
+ interceptor_registered_before_test_invoked = true;
+ return context.invoke();
+ }
+ });
+ }
+
+ @Test
+ public void interceptor_can_be_registered_before_test() {
+ assertFalse(interceptor_registered_before_test_invoked);
+ browser.get("about:blank");
+ assertTrue(interceptor_registered_before_test_invoked);
+ }
+
+ @Test
+ public void interceptor_can_be_registered_by_extension_before_test() {
+ assertFalse(InterceptorRegistrationExtension.invoked);
+ browser.get("about:blank");
+ assertTrue(InterceptorRegistrationExtension.invoked);
+ }
+
+}
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/TestInterceptorSetupIsolation.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/TestInterceptorSetupIsolation.java
new file mode 100644
index 000000000..e713706cd
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/intercept/TestInterceptorSetupIsolation.java
@@ -0,0 +1,56 @@
+package org.jboss.arquillian.graphene.ftest.intercept;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.jboss.arquillian.drone.api.annotation.Drone;
+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.junit.Arquillian;
+import org.jboss.arquillian.junit.InSequence;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.WebDriver;
+
+@RunWith(Arquillian.class)
+public class TestInterceptorSetupIsolation {
+ @Drone
+ private WebDriver browser;
+
+ private boolean invoked = false;
+
+ @Before
+ public void resetFlags() {
+ invoked = false;
+ }
+
+ @Test
+ @InSequence(1)
+ public void interceptor_can_be_registered_in_test_itself() {
+ ((GrapheneProxyInstance) browser).registerInterceptor(new Interceptor() {
+
+ @Override
+ public Object intercept(InvocationContext context) throws Throwable {
+ invoked = true;
+ return context.invoke();
+ }
+ });
+
+ assertFalse(invoked);
+ browser.get("about:blank");
+ assertTrue(invoked);
+ }
+
+ /**
+ * Tests that interceptor from previous test isn't propagated to this test
+ */
+ @Test
+ @InSequence(2)
+ public void interceptors_arent_shared_across_tests() {
+ assertFalse(invoked);
+ browser.get("about:blank");
+ assertFalse(invoked);
+ }
+}
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 baa019c0c..d946f24e6 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
@@ -23,14 +23,15 @@
import java.net.URL;
import java.util.List;
+
import org.jboss.arquillian.drone.api.annotation.Drone;
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.junit.Test;
import org.junit.Assert;
+import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
@@ -78,7 +79,7 @@ public void testWithoutSourceAndWithInterfaceDependencies() {
loadPage();
JSInterfaceFactory.create(Document2.class).getTitle();
}
-
+
@Test
public void testAbstractClass() {
loadPage();
@@ -99,7 +100,7 @@ public static interface Document {
public static interface Document2 {
String getTitle();
}
-
+
@JavaScript("document")
public abstract class Document3 {
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/wait/LocatorAttributeTest.java b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/wait/LocatorAttributeTest.java
index ea8c8514b..2bb9f5e2c 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/wait/LocatorAttributeTest.java
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/ftest/wait/LocatorAttributeTest.java
@@ -11,7 +11,7 @@ public class LocatorAttributeTest extends AbstractWaitTest {
@Test
public void testAttributeIsPresent() {
loadPage();
- checkAttributeIsPresent(Graphene.waitModel().until().element(BY_HEADER).attribute("style"));
+ checkAttributeIsPresent(Graphene.waitAjax().until().element(BY_HEADER).attribute("style"));
}
@Test
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension
new file mode 100644
index 000000000..9c4fce7c8
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension
@@ -0,0 +1 @@
+org.jboss.arquillian.graphene.ftest.intercept.InterceptorRegistrationExtension
\ No newline at end of file
diff --git a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/arquillian.xml b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/arquillian.xml
index b2ee93377..c50ad7c39 100644
--- a/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/arquillian.xml
+++ b/graphene-webdriver/graphene-webdriver-ftest/src/test/resources/arquillian.xml
@@ -23,7 +23,7 @@
-->
<arquillian xmlns="http://jboss.com/arquillian" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
+ xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<extension qualifier="webdriver">
<property name="browserCapabilities">${browser}</property>
@@ -32,4 +32,10 @@
<property name="javascriptEnabled">true</property>
</extension>
+
+ <extension qualifier="graphene">
+ <property name="waitAjaxInterval">1</property>
+ <property name="waitModelInterval">1</property>
+ </extension>
+
</arquillian>
diff --git a/graphene-webdriver/graphene-webdriver-impl/pom.xml b/graphene-webdriver/graphene-webdriver-impl/pom.xml
index cdb6b958b..9e6b5872e 100644
--- a/graphene-webdriver/graphene-webdriver-impl/pom.xml
+++ b/graphene-webdriver/graphene-webdriver-impl/pom.xml
@@ -76,6 +76,30 @@
<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>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.arquillian.core</groupId>
+ <artifactId>arquillian-core-impl-base</artifactId>
+ <version>1.0.3.Final</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.arquillian.test</groupId>
+ <artifactId>arquillian-test-impl-base</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.arquillian.test</groupId>
+ <artifactId>arquillian-test-impl-base</artifactId>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
<!-- Test dependencies -->
<dependency>
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
index ab64c436e..a57654a77 100644
--- 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
@@ -24,9 +24,10 @@
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.GrapheneProxyUtil;
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;
@@ -50,13 +51,28 @@
public final class GrapheneContext {
/**
- * The thread local context of AjaxSelenium
+ * 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
*
@@ -70,6 +86,7 @@ public static void set(WebDriver driver) {
if (GrapheneProxy.isProxyInstance(driver)) {
throw new IllegalArgumentException("instance of the proxy can't be set to the context");
}
+
REFERENCE.set(driver);
}
@@ -78,6 +95,7 @@ public static void set(WebDriver driver) {
*/
public static void reset() {
REFERENCE.set(null);
+ HANDLER.get().resetInterceptors();
}
/**
@@ -109,21 +127,34 @@ public static boolean isInitialized() {
* @return the instance of proxy to thread local context of WebDriver
*/
public static WebDriver getProxy() {
- WebDriver webdriver = GrapheneProxy.getProxyForFutureTarget(TARGET, null, WebDriver.class, JavascriptExecutor.class, HasInputDevices.class);
+ 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) {
- T webdriver = GrapheneProxy.<T>getProxyForFutureTarget(TARGET, webDriverImplClass);
+ 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());
@@ -139,7 +170,7 @@ public static <T extends WebDriver> T getProxyForDriver(Class<T> webDriverImplCl
public static <T> T getProxyForInterfaces(Class<?>... interfaces) {
Class<?>[] interfacesIncludingWebdriver = GrapheneProxyUtil.concatClasses(interfaces, WebDriver.class);
- T webdriver = GrapheneProxy.<T>getProxyForFutureTarget(TARGET, null, interfacesIncludingWebdriver);
+ T webdriver = GrapheneProxy.<T>getProxyForHandler(HANDLER.get(), null, interfacesIncludingWebdriver);
GrapheneProxyInstance proxy = (GrapheneProxyInstance) webdriver;
proxy.registerInterceptor(new SearchContextInterceptor());
proxy.registerInterceptor(new StaleElementInterceptor());
@@ -155,11 +186,4 @@ public static <T> T getProxyForInterfaces(Class<?>... interfaces) {
public static boolean holdsInstanceOf(Class<?> clazz) {
return clazz.isAssignableFrom(get().getClass());
}
-
- private static FutureTarget TARGET = new FutureTarget() {
- @Override
- public Object getTarget() {
- return get();
- }
- };
-}
\ No newline at end of file
+}
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 837cbdd81..bda7b231e 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
@@ -156,7 +156,8 @@ public IndirectProvider() {
public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
final M base = base();
- ((GrapheneProxyInstance) base).registerInterceptor(new Interceptor() {
+ // this interceptor is created just to create future target of invocation
+ Interceptor interceptor = new Interceptor() {
@Override
public Object intercept(final InvocationContext context) throws Throwable {
@@ -176,9 +177,15 @@ public Object getTarget() {
throw new IllegalStateException("You cannot invoke method " + method + " on the " + mediatorType);
}
}
- });
+ };
- return invoke(base);
+ ((GrapheneProxyInstance) base).registerInterceptor(interceptor);
+
+ Object futureTargetProxy = invoke(base);
+
+ ((GrapheneProxyInstance) base).unregisterInterceptor(interceptor);
+
+ return futureTargetProxy;
}
public abstract T invoke(M mediator);
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/DroneEnhancer.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/DroneEnhancer.java
index 3c684fdff..705a30640 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/DroneEnhancer.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/integration/DroneEnhancer.java
@@ -48,6 +48,8 @@ public WebDriver deenhance(WebDriver enhancedDriver, Class<? extends Annotation>
return ((GrapheneProxyInstance) enhancedDriver).unwrap();
}
+ GrapheneContext.reset();
+
return enhancedDriver;
}
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
index 23d90f163..79dd3d7db 100644
--- 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
@@ -38,6 +38,7 @@
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>
@@ -61,7 +62,7 @@ public void registerPageExtensionRegistry(@Observes BeforeClass event, TestClass
pageExtensionRegistry.set(new PageExtensionRegistryImpl());
loadPageExtensions(testClass);
GraphenePageExtensionsContext.setRegistry(pageExtensionRegistry.get());
- pageExtensionInstallatorProvider.set(new RemotePageExtensionInstallatorProvider(pageExtensionRegistry.get(), GrapheneContext.getProxy()));
+ pageExtensionInstallatorProvider.set(new RemotePageExtensionInstallatorProvider(pageExtensionRegistry.get(), GrapheneContext.<JavascriptExecutor>getProxyForInterfaces(JavascriptExecutor.class)));
GraphenePageExtensionsContext.setInstallatorProvider(pageExtensionInstallatorProvider.get());
pageExtensionsReady.fire(new PageExtensionsReady());
}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/RemotePageExtensionInstallatorProvider.java b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/RemotePageExtensionInstallatorProvider.java
index fe2a7d875..5349e0bc9 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/RemotePageExtensionInstallatorProvider.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/page/extension/RemotePageExtensionInstallatorProvider.java
@@ -25,7 +25,6 @@
import org.jboss.arquillian.graphene.javascript.JavaScriptUtils;
import org.jboss.arquillian.graphene.spi.page.PageExtension;
import org.openqa.selenium.JavascriptExecutor;
-import org.openqa.selenium.WebDriver;
/**
* Provider for {@link PageExtensionInstallator}s using {@link org.openqa.selenium.JavascriptExecutor#executeScript(java.lang.String, java.lang.Object[]) }
@@ -35,13 +34,13 @@
*/
public class RemotePageExtensionInstallatorProvider extends AbstractPageExtensionInstallatorProvider {
- private final WebDriver driver;
+ private final JavascriptExecutor executor;
- public RemotePageExtensionInstallatorProvider(PageExtensionRegistry registry, WebDriver driver) {
+ public RemotePageExtensionInstallatorProvider(PageExtensionRegistry registry, JavascriptExecutor executor) {
super(registry);
- Validate.notNull(driver, "driver should not be null");
- this.driver = driver;
- if (!(driver instanceof JavascriptExecutor)) {
+ Validate.notNull(executor, "executor should not be null");
+ this.executor = executor;
+ if (!(executor instanceof JavascriptExecutor)) {
throw new IllegalStateException("Can't use the given driver to execute javascript, because it doesn't implement " + JavascriptExecutor.class + " interface.");
}
}
@@ -51,12 +50,12 @@ public PageExtensionInstallator createInstallator(final PageExtension extension)
return new AbstractPageExtensionInstallator(extension, this) {
@Override
protected void installWithoutRequirements() {
- JavaScriptUtils.execute((JavascriptExecutor) driver, extension.getExtensionScript());
+ JavaScriptUtils.execute(executor, extension.getExtensionScript());
}
@Override
public boolean isInstalled() {
- Object result = JavaScriptUtils.execute((JavascriptExecutor) driver, extension.getInstallationDetectionScript());
+ Object result = JavaScriptUtils.execute(executor, extension.getInstallationDetectionScript());
if (!(result instanceof Boolean)) {
throw new IllegalStateException("The result of installation detection script is not boolean as expected, " + result + " given.");
}
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 dcba81cc5..728dd4f76 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
@@ -25,17 +25,17 @@
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
+import net.sf.cglib.proxy.Enhancer;
+
/**
- * GrapheneProxy provides methods for wrapping the target of invocation in the
- * proxy.
+ * GrapheneProxy provides methods for wrapping the target of invocation in the proxy.
*
* @author Lukas Fryc
*/
public final class GrapheneProxy {
/**
- * Returns whether given
- * <code>object</code> is instance of context proxy.
+ * Returns whether given <code>object</code> is instance of context proxy.
*
* @param target target instance to check
* @return true when target is a Proxy instance, false otherwise
@@ -45,10 +45,13 @@ public static boolean isProxyInstance(Object target) {
}
/**
- * <p> Wraps the given target instance in the proxy. </p>
+ * <p>
+ * Wraps the given target instance in the proxy.
+ * </p>
*
- * <p> The list of interfaces which should be implemented by the proxy is
- * automatically computer from provided instance. </p>
+ * <p>
+ * The list of interfaces which should be implemented by the proxy is automatically computer from provided instance.
+ * </p>
*
*
* @param target the target instance to be wrapped
@@ -60,7 +63,8 @@ public static <T> T getProxyForTarget(T target) {
if (target.getClass().getInterfaces().length > 0) {
return GrapheneProxy.getProxyForTargetWithInterfaces(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.");
+ 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);
@@ -68,15 +72,17 @@ public static <T> T getProxyForTarget(T target) {
}
/**
- * <p> Wraps the given target instance in the proxy. </p>
+ * <p>
+ * Wraps the given target instance in the proxy.
+ * </p>
*
- * <p> The list of interfaces which should be implemented by the proxy needs
- * to be provided. </p>
+ * <p>
+ * The list of interfaces which should be implemented by the proxy needs to be provided.
+ * </p>
*
*
* @param target the target instance to be wrapped
- * @param interfaces the list of interfaces which should be implemented by
- * created proxy
+ * @param interfaces the list of interfaces which should be implemented by created proxy
* @return the proxy wrapping the target
*/
@SuppressWarnings("unchecked")
@@ -86,58 +92,71 @@ public static <T> T getProxyForTargetWithInterfaces(T target, Class<?>... interf
}
/**
- * <p> Wraps the given future target instance in the proxy. </p>
+ * <p>
+ * Wraps the given future target instance in the proxy.
+ * </p>
*
- * <p> Future target can be computed dynamically for each invocation of
- * proxy. </p>
+ * <p>
+ * Future target can be computed dynamically for each invocation of proxy.
+ * </p>
*
- * <p> In this case interfaces which should the proxy implement needs to be
- * provided. </p>
+ * <p>
+ * In this case interfaces which should the proxy implement needs to be provided.
+ * </p>
*
- * <p> The list of any classes can be provided, the list of interfaces will
- * be automatically computed. </p>
+ * <p>
+ * The list of any classes can be provided, the list of interfaces will be automatically computed.
+ * </p>
*
* @param futureTarget the future target of invocation
- * @param baseType the list of classes from which should be determined what
- * interfaces will returned proxy implement
- * @param additionalInterfaces additional interfaces which should a created
- * proxy implement
+ * @param baseType the list of classes from which should be determined what interfaces will returned proxy implement
+ * @param additionalInterfaces additional interfaces which should a created proxy implement
* @return the proxy wrapping the future target
*/
- @SuppressWarnings("unchecked")
+ @Deprecated
public static <T> T getProxyForFutureTarget(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);
} else {
- throw new IllegalStateException("Can't create a proxy for " + baseType + ", it's final and no additional interface has been given.");
+ 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);
+ return getProxyForHandler(handler, baseType, additionalInterfaces);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T getProxyForHandler(GrapheneProxyHandler handler, Class<?> baseType, Class<?>... additionalInterfaces) {
return (T) createProxy(handler, baseType, additionalInterfaces);
}
/**
- * <p> Uses given proxy factory to create new proxy for given implementation
- * class or interfaces with the given method handler. </p>
+ * <p>
+ * Uses given proxy factory to create new proxy for given implementation class or interfaces with the given method handler.
+ * </p>
*
- * <p> The returned proxy implements {@link GrapheneProxyInstance} by
- * default.
+ * <p>
+ * The returned proxy implements {@link GrapheneProxyInstance} by default.
*
- * @param factory the {@link ProxyFactory} which will be used to create
- * proxy
+ * @param factory the {@link ProxyFactory} which will be used to create proxy
* @param interceptor the {@link MethodHandler} for handling invocation
- * @param baseType the class or interface used as base type or null if
- * additionalInterfaces list should be used instead
- * @param additionalInterfaces additional interfaces which should a created
- * proxy implement
- * @return the proxy for given implementation class or interfaces with the
- * given method handler.
+ * @param baseType the class or interface used as base type or null if additionalInterfaces list should be used instead
+ * @param additionalInterfaces additional interfaces which should a created proxy implement
+ * @return the proxy for given implementation class or interfaces with the given method handler.
*/
@SuppressWarnings("unchecked")
static <T> T createProxy(GrapheneProxyHandler interceptor, Class<T> baseType, Class<?>... additionalInterfaces) {
+ if (baseType != null) {
+ while (Enhancer.isEnhanced(baseType)) {
+ baseType = (Class<T>) baseType.getSuperclass();
+ }
+ }
+
Class<?>[] ancillaryTypes = GrapheneProxyUtil.concatClasses(additionalInterfaces, GrapheneProxyInstance.class);
if (baseType == null || baseType.isInterface()) {
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 e2ffca52c..be0a2250a 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
@@ -44,7 +44,7 @@
*
* @author Lukas Fryc
*/
-class GrapheneProxyHandler implements MethodInterceptor, InvocationHandler {
+public class GrapheneProxyHandler implements MethodInterceptor, InvocationHandler {
private Object target;
private FutureTarget future;
@@ -59,7 +59,7 @@ private GrapheneProxyHandler() {
* @param target the target of invocation
* @return invocation handler which wraps the given target instance
*/
- static GrapheneProxyHandler forTarget(Object target) {
+ public static GrapheneProxyHandler forTarget(Object target) {
GrapheneProxyHandler handler = new GrapheneProxyHandler();
handler.target = target;
return handler;
@@ -71,7 +71,7 @@ static GrapheneProxyHandler forTarget(Object target) {
* @param future the future target
* @return invocation handler which wraps the target for future computation
*/
- static GrapheneProxyHandler forFuture(FutureTarget future) {
+ public static GrapheneProxyHandler forFuture(FutureTarget future) {
GrapheneProxyHandler handler = new GrapheneProxyHandler();
handler.future = future;
return handler;
@@ -92,7 +92,7 @@ static GrapheneProxyHandler forFuture(FutureTarget future) {
* invocation.
*/
@Override
- public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
+ public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
// handle the GrapheneProxyInstance's method unwrap
if (method.equals(GrapheneProxyInstance.class.getMethod("unwrap"))) {
Object target = getTarget();
@@ -132,6 +132,10 @@ public Object invoke(Object proxy, final Method method, final Object[] args) thr
}
return clone;
}
+ // handle GrapheneProxyInstance's method copy
+ if (method.equals(GrapheneProxyInstance.class.getMethod("getHandler"))) {
+ return this;
+ }
InvocationContext invocationContext = new InvocationContext() {
@@ -143,7 +147,11 @@ public Object invoke() throws Throwable {
}
if (isProxyable(method, args) && !(result instanceof GrapheneProxyInstance)) {
Class<?>[] interfaces = GrapheneProxyUtil.getInterfaces(result.getClass());
- return GrapheneProxy.getProxyForTargetWithInterfaces(result, interfaces);
+ Object newProxy = GrapheneProxy.getProxyForTargetWithInterfaces(result, interfaces);
+
+// List<Interceptor> inheritingInterceptors = ((GrapheneProxyInstance)proxy).getInheritingInterceptors();
+
+ return newProxy;
}
return result;
}
@@ -227,4 +235,11 @@ Object getTarget() {
return (future == null) ? target : future.getTarget();
}
+ /**
+ * Resets the interceptors
+ */
+ public void resetInterceptors() {
+ interceptors.clear();
+ }
+
}
\ No newline at end of file
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 f9b623dc4..cfd6aefa6 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,7 @@
*/
package org.jboss.arquillian.graphene.proxy;
+
/**
* <p>
* Marker interface for all instances of proxies created by {@link GrapheneProxy}.
@@ -34,6 +35,8 @@ public interface GrapheneProxyInstance {
Interceptor unregisterInterceptor(Interceptor interceptor);
+ GrapheneProxyHandler getHandler();
+
<T> T copy();
<T> T unwrap();
diff --git a/graphene-webdriver/graphene-webdriver-ftest/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
similarity index 100%
rename from graphene-webdriver/graphene-webdriver-ftest/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java
rename to graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/configuration/ConfigurationContextTestCase.java
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
new file mode 100644
index 000000000..9f6fd17d0
--- /dev/null
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/intercept/TestIntercepting.java
@@ -0,0 +1,31 @@
+package org.jboss.arquillian.graphene.intercept;
+
+import org.jboss.arquillian.graphene.proxy.GrapheneProxy;
+import org.jboss.arquillian.graphene.proxy.GrapheneProxyInstance;
+import org.jboss.arquillian.graphene.proxy.Interceptor;
+import org.jboss.arquillian.graphene.proxy.InvocationContext;
+import org.junit.Test;
+
+public class TestIntercepting {
+
+ @Test
+ public void testInterceptorCalling() {
+ // having
+ MyObject target = new MyObject();
+ MyObject proxy = GrapheneProxy.getProxyForTarget(target);
+
+ // when
+ ((GrapheneProxyInstance) proxy).registerInterceptor(new Interceptor() {
+ public Object intercept(InvocationContext context) throws Throwable {
+ return context.invoke();
+ }
+ });
+
+ proxy.someMethod();
+ }
+
+ public class MyObject {
+ public void someMethod() {
+ }
+ }
+}
diff --git a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/page/extension/RemotePageExtensionInstallatorProviderTestCase.java b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/page/extension/RemotePageExtensionInstallatorProviderTestCase.java
index bfbcbc158..25dc6fccf 100644
--- a/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/page/extension/RemotePageExtensionInstallatorProviderTestCase.java
+++ b/graphene-webdriver/graphene-webdriver-impl/src/test/java/org/jboss/arquillian/graphene/page/extension/RemotePageExtensionInstallatorProviderTestCase.java
@@ -1,18 +1,20 @@
package org.jboss.arquillian.graphene.page.extension;
+import static org.mockito.Mockito.when;
+
+import java.util.Collections;
+
+import junit.framework.Assert;
+
import org.jboss.arquillian.graphene.spi.javascript.JavaScript;
import org.jboss.arquillian.graphene.spi.page.PageExtension;
import org.junit.Before;
-import org.mockito.Mock;
-import java.util.Collections;
-import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.openqa.selenium.JavascriptExecutor;
-import org.openqa.selenium.WebDriver;
-import static org.mockito.Mockito.when;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
@@ -20,13 +22,13 @@
@RunWith(MockitoJUnitRunner.class)
public class RemotePageExtensionInstallatorProviderTestCase {
- @Mock(extraInterfaces={JavascriptExecutor.class})
- private WebDriver driver;
+ @Mock
+ private JavascriptExecutor executor;
@Before
public void prepareDriver() {
- when(((JavascriptExecutor) driver).executeScript("install")).thenReturn(null);
- when(((JavascriptExecutor) driver).executeScript("check")).thenReturn(false, true, true);
+ when((executor).executeScript("install")).thenReturn(null);
+ when((executor).executeScript("check")).thenReturn(false, true, true);
}
@Test
@@ -41,7 +43,7 @@ public void testInstallation() {
PageExtensionRegistry registry = new PageExtensionRegistryImpl();
registry.register(pageExtensionMock);
// tests
- PageExtensionInstallatorProvider provider = new RemotePageExtensionInstallatorProvider(registry, driver);
+ PageExtensionInstallatorProvider provider = new RemotePageExtensionInstallatorProvider(registry, executor);
Assert.assertFalse(provider.installator(pageExtensionMock.getName()).isInstalled());
provider.installator(pageExtensionMock.getName()).install();
Assert.assertTrue(provider.installator(pageExtensionMock.getName()).isInstalled());
diff --git a/pom.xml b/pom.xml
index 8575fae37..ae5af0f7d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -29,7 +29,8 @@
<!-- Arquillian -->
<version.arquillian.core>1.0.3.Final</version.arquillian.core>
- <version.arquillian.drone>1.1.0.Final</version.arquillian.drone>
+ <version.arquillian.drone>1.2.0.Final-SNAPSHOT</version.arquillian.drone>
+ <version.selenium>2.31.0</version.selenium>
<!-- Runtime dependencies -->
<version.javassist>3.12.1.GA</version.javassist>
@@ -85,7 +86,7 @@
<dependency>
<groupId>org.jboss.arquillian.selenium</groupId>
<artifactId>selenium-bom</artifactId>
- <version>2.28.0</version>
+ <version>${version.selenium}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
|
1bacaac77d55c6bc522ec1ec03e155b1c44981e0
|
cyberfox$jbidwatcher
|
Move the makeStandardDirectory functionality into the Path object where it belongs.
|
p
|
https://github.com/cyberfox/jbidwatcher
|
diff --git a/src/com/cyberfox/util/platform/Path.java b/src/com/cyberfox/util/platform/Path.java
index 04caf81b..c8e3d060 100644
--- a/src/com/cyberfox/util/platform/Path.java
+++ b/src/com/cyberfox/util/platform/Path.java
@@ -92,4 +92,31 @@ public static String getCanonicalFile(String fname, String dirname, boolean must
return outName;
}
+
+ public static String makeStandardDirectory(String inPath, String defaultSubdir, String defaultDirectory) {
+ String outPath = inPath;
+
+ if(outPath != null) {
+ File fp_test = new File(outPath);
+ if(!fp_test.exists()) {
+ if(!fp_test.mkdirs()) {
+ outPath = null;
+ }
+ }
+ }
+
+ if(outPath == null) {
+ String directoryPath = getCanonicalFile(defaultSubdir, defaultDirectory, false);
+ File fp = new File(directoryPath);
+
+ if(fp.exists()) {
+ outPath = fp.getAbsolutePath();
+ } else {
+ if(!fp.mkdirs()) JConfig.log().logDebug("Couldn't mkdir " + directoryPath);
+ outPath = fp.getAbsolutePath();
+ }
+ }
+
+ return outPath;
+ }
}
diff --git a/src/com/jbidwatcher/app/JBidWatch.java b/src/com/jbidwatcher/app/JBidWatch.java
index 68617e75..c6c526e4 100644
--- a/src/com/jbidwatcher/app/JBidWatch.java
+++ b/src/com/jbidwatcher/app/JBidWatch.java
@@ -107,38 +107,11 @@ public final class JBidWatch implements JConfig.ConfigListener {
* @return - a String identifying the path to our save directory.
*/
private static String makeSaveDirectory(String inPath) {
- return makeStandardDirectory(inPath, "auctionsave", "jbidwatcher");
+ return Path.makeStandardDirectory(inPath, "auctionsave", "jbidwatcher");
}
private static String makePlatformDirectory(String inPath) {
- return makeStandardDirectory(inPath, "platform", "jbidwatcher");
- }
-
- private static String makeStandardDirectory(String inPath, String defaultSubdir, String defaultDirectory) {
- String outPath = inPath;
-
- if(outPath != null) {
- File fp_test = new File(outPath);
- if(!fp_test.exists()) {
- if(!fp_test.mkdirs()) {
- outPath = null;
- }
- }
- }
-
- if(outPath == null) {
- String directoryPath = Path.getCanonicalFile(defaultSubdir, defaultDirectory, false);
- File fp = new File(directoryPath);
-
- if(fp.exists()) {
- outPath = fp.getAbsolutePath();
- } else {
- if(!fp.mkdirs()) JConfig.log().logDebug("Couldn't mkdir " + directoryPath);
- outPath = fp.getAbsolutePath();
- }
- }
-
- return outPath;
+ return Path.makeStandardDirectory(inPath, "platform", "jbidwatcher");
}
private static void getUserSetup() {
|
17db0f11e85bb21def0af785e654db15120d874b
|
Delta Spike
|
DELTASPIKE-339 don't lot the Exception as this is a normal operating situation
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/util/JndiUtils.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/util/JndiUtils.java
index 85fa77b79..9301da536 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/util/JndiUtils.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/util/JndiUtils.java
@@ -190,7 +190,7 @@ public static <T> Map<String, T> list(String name, Class<T> type)
}
catch (NamingException e)
{
- LOG.log(Level.SEVERE, "InitialContext#list failed!", e);
+ // this is expected if there is no entry in JNDI for the requested name or type
}
return result;
}
|
e99464c45f8394708291498864de1c18f183434c
|
tapiji
|
Removes the outdate plug-in 'org.apache.commons.io'.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.apache.commons.io/.classpath b/org.apache.commons.io/.classpath
deleted file mode 100644
index f2d41466..00000000
--- a/org.apache.commons.io/.classpath
+++ /dev/null
@@ -1,7 +0,0 @@
-<?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 exported="true" kind="lib" path=""/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/org.apache.commons.io/.project b/org.apache.commons.io/.project
deleted file mode 100644
index b4ddad64..00000000
--- a/org.apache.commons.io/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.apache.commons.io</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/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs b/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index 2f1261fd..00000000
--- a/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,8 +0,0 @@
-#Sat Apr 21 11:12:43 CEST 2012
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.apache.commons.io/META-INF/LICENSE.txt b/org.apache.commons.io/META-INF/LICENSE.txt
deleted file mode 100644
index 43e91eb0..00000000
--- a/org.apache.commons.io/META-INF/LICENSE.txt
+++ /dev/null
@@ -1,203 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- 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.
-
diff --git a/org.apache.commons.io/META-INF/MANIFEST.MF b/org.apache.commons.io/META-INF/MANIFEST.MF
deleted file mode 100644
index 79a52482..00000000
--- a/org.apache.commons.io/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,12 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Apache Commons IO
-Bundle-SymbolicName: org.apache.commons.io
-Bundle-Version: 1.0.0
-Export-Package: org.apache.commons.io,
- org.apache.commons.io.comparator,
- org.apache.commons.io.filefilter,
- org.apache.commons.io.input,
- org.apache.commons.io.monitor,
- org.apache.commons.io.output
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/org.apache.commons.io/META-INF/NOTICE.txt b/org.apache.commons.io/META-INF/NOTICE.txt
deleted file mode 100644
index 7632eb8e..00000000
--- a/org.apache.commons.io/META-INF/NOTICE.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Apache Commons IO
-Copyright 2002-2012 The Apache Software Foundation
-
-This product includes software developed by
-The Apache Software Foundation (http://www.apache.org/).
-
diff --git a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties b/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties
deleted file mode 100644
index b3e76eb3..00000000
--- a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties
+++ /dev/null
@@ -1,5 +0,0 @@
-#Generated by Maven
-#Tue Apr 10 11:00:26 EDT 2012
-version=2.3
-groupId=commons-io
-artifactId=commons-io
diff --git a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml b/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml
deleted file mode 100644
index bae10d22..00000000
--- a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml
+++ /dev/null
@@ -1,346 +0,0 @@
-<?xml version="1.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.
--->
-<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">
- <parent>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-parent</artifactId>
- <version>24</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.3</version>
- <name>Commons IO</name>
-
- <inceptionYear>2002</inceptionYear>
- <description>
-The Commons IO library contains utility classes, stream implementations, file filters,
-file comparators, endian transformation classes, and much more.
- </description>
-
- <url>http://commons.apache.org/io/</url>
-
- <issueManagement>
- <system>jira</system>
- <url>http://issues.apache.org/jira/browse/IO</url>
- </issueManagement>
-
- <distributionManagement>
- <site>
- <id>apache.website</id>
- <name>Apache Commons IO Site</name>
- <url>${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/${commons.componentid}</url>
- </site>
- </distributionManagement>
-
- <scm>
- <connection>scm:svn:http://svn.apache.org/repos/asf/commons/proper/io/trunk</connection>
- <developerConnection>scm:svn:https://svn.apache.org/repos/asf/commons/proper/io/trunk</developerConnection>
- <url>http://svn.apache.org/viewvc/commons/proper/io/trunk</url>
- </scm>
-
- <developers>
- <developer>
- <name>Scott Sanders</name>
- <id>sanders</id>
- <email>[email protected]</email>
- <organization></organization>
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>dIon Gillard</name>
- <id>dion</id>
- <email>[email protected]</email>
- <organization></organization>
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>Nicola Ken Barozzi</name>
- <id>nicolaken</id>
- <email>[email protected]</email>
- <organization></organization>
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>Henri Yandell</name>
- <id>bayard</id>
- <email>[email protected]</email>
- <organization></organization>
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>Stephen Colebourne</name>
- <id>scolebourne</id>
- <organization></organization>
- <roles>
- <role>Java Developer</role>
- </roles>
- <timezone>0</timezone>
- </developer>
- <developer>
- <name>Jeremias Maerki</name>
- <id>jeremias</id>
- <email>[email protected]</email>
- <organization />
- <roles>
- <role>Java Developer</role>
- </roles>
- <timezone>+1</timezone>
- </developer>
- <developer>
- <name>Matthew Hawthorne</name>
- <id>matth</id>
- <email>[email protected]</email>
- <organization />
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>Martin Cooper</name>
- <id>martinc</id>
- <email>[email protected]</email>
- <organization />
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>Rob Oxspring</name>
- <id>roxspring</id>
- <email>[email protected]</email>
- <organization />
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>Jochen Wiedmann</name>
- <id>jochen</id>
- <email>[email protected]</email>
- </developer>
- <developer>
- <name>Niall Pemberton</name>
- <id>niallp</id>
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>Jukka Zitting</name>
- <id>jukka</id>
- <roles>
- <role>Java Developer</role>
- </roles>
- </developer>
- <developer>
- <name>Gary Gregory</name>
- <id>ggregory</id>
- <email>[email protected]</email>
- <url>http://www.garygregory.com</url>
- <timezone>-5</timezone>
- </developer>
- </developers>
-
- <contributors>
- <contributor>
- <name>Rahul Akolkar</name>
- </contributor>
- <contributor>
- <name>Jason Anderson</name>
- </contributor>
- <contributor>
- <name>Nathan Beyer</name>
- </contributor>
- <contributor>
- <name>Emmanuel Bourg</name>
- </contributor>
- <contributor>
- <name>Chris Eldredge</name>
- </contributor>
- <contributor>
- <name>Magnus Grimsell</name>
- </contributor>
- <contributor>
- <name>Jim Harrington</name>
- </contributor>
- <contributor>
- <name>Thomas Ledoux</name>
- </contributor>
- <contributor>
- <name>Andy Lehane</name>
- </contributor>
- <contributor>
- <name>Marcelo Liberato</name>
- </contributor>
- <contributor>
- <name>Alban Peignier</name>
- <email>alban.peignier at free.fr</email>
- </contributor>
- <contributor>
- <name>Ian Springer</name>
- </contributor>
- <contributor>
- <name>Masato Tezuka</name>
- </contributor>
- <contributor>
- <name>James Urie</name>
- </contributor>
- <contributor>
- <name>Frank W. Zammetti</name>
- </contributor>
- </contributors>
-
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.10</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <properties>
- <maven.compile.source>1.6</maven.compile.source>
- <maven.compile.target>1.6</maven.compile.target>
- <commons.componentid>io</commons.componentid>
- <commons.rc.version>RC1</commons.rc.version>
- <commons.release.version>2.3</commons.release.version>
- <commons.release.desc>(requires JDK 1.6+)</commons.release.desc>
- <commons.release.2.version>2.2</commons.release.2.version>
- <commons.release.2.desc>(requires JDK 1.5+)</commons.release.2.desc>
- <commons.jira.id>IO</commons.jira.id>
- <commons.jira.pid>12310477</commons.jira.pid>
- <!-- temporary override of parent -->
- <commons.clirr.version>2.4</commons.clirr.version>
- </properties>
-
- <build>
- <pluginManagement>
- <plugins>
- <!-- Temporarily needed until CP25 is available -->
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>clirr-maven-plugin</artifactId>
- <version>${commons.clirr.version}</version>
- <configuration>
- <minSeverity>${minSeverity}</minSeverity>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <forkMode>pertest</forkMode>
- <!-- limit memory size see IO-161 -->
- <argLine>-Xmx25M</argLine>
- <includes>
- <!-- Only include test classes, not test data -->
- <include>**/*Test*.class</include>
- </includes>
- <excludes>
- <exclude>**/*AbstractTestCase*</exclude>
- <exclude>**/testtools/**</exclude>
-
- <!-- http://jira.codehaus.org/browse/SUREFIRE-44 -->
- <exclude>**/*$*</exclude>
- </excludes>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <descriptors>
- <descriptor>src/main/assembly/bin.xml</descriptor>
- <descriptor>src/main/assembly/src.xml</descriptor>
- </descriptors>
- <tarLongFileMode>gnu</tarLongFileMode>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <reporting>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <version>2.9.1</version>
- <configuration>
- <configLocation>${basedir}/checkstyle.xml</configLocation>
- <enableRulesSummary>false</enableRulesSummary>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>findbugs-maven-plugin</artifactId>
- <version>2.4.0</version>
- <configuration>
- <threshold>Normal</threshold>
- <effort>Default</effort>
- <excludeFilterFile>${basedir}/findbugs-exclude-filter.xml</excludeFilterFile>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-changes-plugin</artifactId>
- <version>${commons.changes.version}</version>
- <configuration>
- <xmlPath>${basedir}/src/changes/changes.xml</xmlPath>
- <columnNames>Fix Version,Key,Component,Summary,Type,Resolution,Status</columnNames>
- <!-- Sort cols have to be reversed in JIRA 4 -->
- <sortColumnNames>Key DESC,Type,Fix Version DESC</sortColumnNames>
- <resolutionIds>Fixed</resolutionIds>
- <statusIds>Resolved,Closed</statusIds>
- <!-- Don't include sub-task -->
- <typeIds>Bug,New Feature,Task,Improvement,Wish,Test</typeIds>
- <maxEntries>300</maxEntries>
- </configuration>
- <reportSets>
- <reportSet>
- <reports>
- <report>changes-report</report>
- <report>jira-report</report>
- </reports>
- </reportSet>
- </reportSets>
- </plugin>
- <plugin>
- <groupId>org.apache.rat</groupId>
- <artifactId>apache-rat-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>src/test/resources/**/*.bin</exclude>
- <exclude>.pmd</exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
- </reporting>
-</project>
diff --git a/org.apache.commons.io/build.properties b/org.apache.commons.io/build.properties
deleted file mode 100644
index 1ac73bad..00000000
--- a/org.apache.commons.io/build.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-output.. = .
-bin.includes = META-INF/,\
- org/
diff --git a/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class b/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class
deleted file mode 100644
index 8bebf2de..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/Charsets.class b/org.apache.commons.io/org/apache/commons/io/Charsets.class
deleted file mode 100644
index 88a74baf..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/Charsets.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/CopyUtils.class b/org.apache.commons.io/org/apache/commons/io/CopyUtils.class
deleted file mode 100644
index 6de1db52..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/CopyUtils.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class b/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class
deleted file mode 100644
index ed333c99..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class b/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class
deleted file mode 100644
index db7fc482..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/EndianUtils.class b/org.apache.commons.io/org/apache/commons/io/EndianUtils.class
deleted file mode 100644
index f4b0af54..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/EndianUtils.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaner.class b/org.apache.commons.io/org/apache/commons/io/FileCleaner.class
deleted file mode 100644
index 17ee0f8b..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileCleaner.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class
deleted file mode 100644
index 6c0a2d53..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class
deleted file mode 100644
index 063d71c0..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class
deleted file mode 100644
index f793406b..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class b/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class
deleted file mode 100644
index 49b9d33c..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class b/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class
deleted file mode 100644
index 8731c9c9..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileExistsException.class b/org.apache.commons.io/org/apache/commons/io/FileExistsException.class
deleted file mode 100644
index 8eef129b..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileExistsException.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class b/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class
deleted file mode 100644
index 68888e3a..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FileUtils.class b/org.apache.commons.io/org/apache/commons/io/FileUtils.class
deleted file mode 100644
index f2d4c17c..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FileUtils.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class b/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class
deleted file mode 100644
index 059b648a..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/HexDump.class b/org.apache.commons.io/org/apache/commons/io/HexDump.class
deleted file mode 100644
index c88a861e..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/HexDump.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/IOCase.class b/org.apache.commons.io/org/apache/commons/io/IOCase.class
deleted file mode 100644
index 26f6e6da..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/IOCase.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class b/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class
deleted file mode 100644
index e0835d50..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/IOUtils.class b/org.apache.commons.io/org/apache/commons/io/IOUtils.class
deleted file mode 100644
index 725d4f68..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/IOUtils.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/LineIterator.class b/org.apache.commons.io/org/apache/commons/io/LineIterator.class
deleted file mode 100644
index 08221a75..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/LineIterator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class b/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class
deleted file mode 100644
index 1eddd012..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class b/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class
deleted file mode 100644
index 5719a356..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class
deleted file mode 100644
index a3e8b2e2..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class
deleted file mode 100644
index b5774654..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class
deleted file mode 100644
index 19e76e80..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class
deleted file mode 100644
index 6718ac63..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class
deleted file mode 100644
index 11a85482..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class
deleted file mode 100644
index b12636e8..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class
deleted file mode 100644
index ed030680..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class
deleted file mode 100644
index 4effb1be..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class
deleted file mode 100644
index f616dc37..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class
deleted file mode 100644
index ad506044..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class
deleted file mode 100644
index f00eaae1..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class
deleted file mode 100644
index f02c5716..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class
deleted file mode 100644
index 601b4d26..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class
deleted file mode 100644
index 26665156..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class
deleted file mode 100644
index 9d6a2977..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class
deleted file mode 100644
index 903e3ab2..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class
deleted file mode 100644
index 049d673f..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class
deleted file mode 100644
index 89f1b8a6..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class
deleted file mode 100644
index 79377308..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class
deleted file mode 100644
index f5b36c5b..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class
deleted file mode 100644
index ed3ca02d..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class
deleted file mode 100644
index 9165c54b..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class
deleted file mode 100644
index 4c8efb7f..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class
deleted file mode 100644
index c602e578..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class
deleted file mode 100644
index 406c5058..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class
deleted file mode 100644
index 413a5f08..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class
deleted file mode 100644
index e1cd2877..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class
deleted file mode 100644
index 74a1b5ce..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class
deleted file mode 100644
index 8001d9ee..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class
deleted file mode 100644
index c2fa2b41..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class
deleted file mode 100644
index df634ec6..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class
deleted file mode 100644
index f213e1c6..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class
deleted file mode 100644
index 2a162e39..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class
deleted file mode 100644
index 75ab2b8d..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class
deleted file mode 100644
index c6726689..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class
deleted file mode 100644
index b46d8845..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class
deleted file mode 100644
index 3b186d4e..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class
deleted file mode 100644
index 3aa01980..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class
deleted file mode 100644
index ed86c824..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class
deleted file mode 100644
index d56d99d4..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class b/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class
deleted file mode 100644
index cba1c0fc..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class
deleted file mode 100644
index 7280e831..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class
deleted file mode 100644
index 89c5b5d0..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class
deleted file mode 100644
index 77110a09..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class
deleted file mode 100644
index e391e3a0..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class
deleted file mode 100644
index c1c62315..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class
deleted file mode 100644
index fe780a58..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/NullReader.class b/org.apache.commons.io/org/apache/commons/io/input/NullReader.class
deleted file mode 100644
index f6ce8309..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/NullReader.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class
deleted file mode 100644
index bcb63360..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class b/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class
deleted file mode 100644
index 0e88acc8..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class
deleted file mode 100644
index 33b0e11a..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class
deleted file mode 100644
index e7a796ca..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class
deleted file mode 100644
index ddb4de84..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class
deleted file mode 100644
index 2f4819a2..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class
deleted file mode 100644
index 15ccb85c..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class
deleted file mode 100644
index 2e3c7571..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/Tailer.class b/org.apache.commons.io/org/apache/commons/io/input/Tailer.class
deleted file mode 100644
index 100e2959..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/Tailer.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class b/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class
deleted file mode 100644
index a0f1b7d9..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class b/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class
deleted file mode 100644
index 44b075de..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class
deleted file mode 100644
index 534db867..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class b/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class
deleted file mode 100644
index 9a82342f..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class b/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class
deleted file mode 100644
index d0d2cf4b..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class
deleted file mode 100644
index 90ffd926..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class
deleted file mode 100644
index e3f7f582..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class
deleted file mode 100644
index d7694004..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class
deleted file mode 100644
index d3f0cf7a..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class
deleted file mode 100644
index eb8bd5de..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class
deleted file mode 100644
index 06c9873e..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class
deleted file mode 100644
index e0279aaa..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class
deleted file mode 100644
index 734579ba..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class
deleted file mode 100644
index c8dd34de..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class
deleted file mode 100644
index 65d60dd8..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class
deleted file mode 100644
index a27ea22b..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class
deleted file mode 100644
index 64eb167b..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class b/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class
deleted file mode 100644
index c40975b5..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class b/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class
deleted file mode 100644
index 92f1a8f6..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class
deleted file mode 100644
index c9a9e1d9..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class b/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class
deleted file mode 100644
index 7794b638..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class
deleted file mode 100644
index e0619cc9..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class b/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class
deleted file mode 100644
index 93a958c3..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class b/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class
deleted file mode 100644
index 190828ef..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class
deleted file mode 100644
index 52b5a498..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class
deleted file mode 100644
index 7de3c99f..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class
deleted file mode 100644
index 370a0322..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class
deleted file mode 100644
index ec9e6770..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class and /dev/null differ
diff --git a/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class b/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class
deleted file mode 100644
index c2b8e394..00000000
Binary files a/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class and /dev/null differ
|
76517d9ac96d3f7f9475743c539e2b9efbd0d0f0
|
ReactiveX-RxJava
|
1.x: fix Completable.onErrorComplete(Func1) not- relaying function crash (-4027)--
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/src/main/java/rx/Completable.java b/src/main/java/rx/Completable.java
index b5f9baebb7..69c0df708d 100644
--- a/src/main/java/rx/Completable.java
+++ b/src/main/java/rx/Completable.java
@@ -1663,8 +1663,9 @@ public void onError(Throwable e) {
try {
b = predicate.call(e);
} catch (Throwable ex) {
+ Exceptions.throwIfFatal(ex);
e = new CompositeException(Arrays.asList(e, ex));
- return;
+ b = false;
}
if (b) {
diff --git a/src/test/java/rx/CompletableTest.java b/src/test/java/rx/CompletableTest.java
index a2a49d6c2d..4aee2eed85 100644
--- a/src/test/java/rx/CompletableTest.java
+++ b/src/test/java/rx/CompletableTest.java
@@ -4112,4 +4112,29 @@ public void onStart() {
ts.assertCompleted();
}
+ @Test
+ public void onErrorCompleteFunctionThrows() {
+ TestSubscriber<String> ts = new TestSubscriber<String>();
+
+ error.completable.onErrorComplete(new Func1<Throwable, Boolean>() {
+ @Override
+ public Boolean call(Throwable t) {
+ throw new TestException("Forced inner failure");
+ }
+ }).subscribe(ts);
+
+ ts.assertNoValues();
+ ts.assertNotCompleted();
+ ts.assertError(CompositeException.class);
+
+ CompositeException composite = (CompositeException)ts.getOnErrorEvents().get(0);
+
+ List<Throwable> errors = composite.getExceptions();
+ Assert.assertEquals(2, errors.size());
+
+ Assert.assertTrue(errors.get(0).toString(), errors.get(0) instanceof TestException);
+ Assert.assertEquals(errors.get(0).toString(), null, errors.get(0).getMessage());
+ Assert.assertTrue(errors.get(1).toString(), errors.get(1) instanceof TestException);
+ Assert.assertEquals(errors.get(1).toString(), "Forced inner failure", errors.get(1).getMessage());
+ }
}
\ No newline at end of file
|
eb1027b5e8c047059f68e7547188d08c7fde0b6f
|
intellij-community
|
fixed PY-12251 Project Interpreters: Create- virtualenv from settings doesn't update warnigns about python package- management tools--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/python/ide/src/com/jetbrains/python/configuration/PyActiveSdkConfigurable.java b/python/ide/src/com/jetbrains/python/configuration/PyActiveSdkConfigurable.java
index 4a193b3cccd9d..8c3cd3268fefe 100644
--- a/python/ide/src/com/jetbrains/python/configuration/PyActiveSdkConfigurable.java
+++ b/python/ide/src/com/jetbrains/python/configuration/PyActiveSdkConfigurable.java
@@ -99,8 +99,7 @@ private void initContent() {
public void actionPerformed(ActionEvent e) {
final Sdk selectedSdk = (Sdk)mySdkCombo.getSelectedItem();
myPackagesPanel.updatePackages(selectedSdk != null ? new PyPackageManagementService(myProject, selectedSdk) : null);
- if (selectedSdk != null)
- myPackagesPanel.updateNotifications(selectedSdk);
+ myPackagesPanel.updateNotifications(selectedSdk);
}
});
myDetailsCallback = new NullableConsumer<Sdk>() {
@@ -148,6 +147,7 @@ public void consume(Sdk sdk) {
updateSdkList(false);
mySdkCombo.getModel().setSelectedItem(sdk);
myPackagesPanel.updatePackages(new PyPackageManagementService(myProject, sdk));
+ myPackagesPanel.updateNotifications(sdk);
}
}
);
diff --git a/python/src/com/jetbrains/python/packaging/ui/PyInstalledPackagesPanel.java b/python/src/com/jetbrains/python/packaging/ui/PyInstalledPackagesPanel.java
index a9e0ca211171b..0fdbc53a55860 100644
--- a/python/src/com/jetbrains/python/packaging/ui/PyInstalledPackagesPanel.java
+++ b/python/src/com/jetbrains/python/packaging/ui/PyInstalledPackagesPanel.java
@@ -33,6 +33,7 @@
import com.jetbrains.python.sdk.flavors.IronPythonSdkFlavor;
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Set;
@@ -75,7 +76,11 @@ private Sdk getSelectedSdk() {
return service != null ? service.getSdk() : null;
}
- public void updateNotifications(@NotNull final Sdk selectedSdk) {
+ public void updateNotifications(@Nullable final Sdk selectedSdk) {
+ if (selectedSdk == null) {
+ myNotificationArea.hide();
+ return;
+ }
final Application application = ApplicationManager.getApplication();
application.executeOnPooledThread(new Runnable() {
@Override
|
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);
}
|
4da9b2cc9c18a5b8680550e3bdbe2c405abb5d81
|
elasticsearch
|
Catch AmazonClientExceptions to prevent- connection loss If the AWS client throws an exception (e.g: because of a DNS- failure) it will end up killing the rejoin thread and stop retrying which can- lead to a node getting stuck unable to rejoin the cluster.--Closes -30.-
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2UnicastHostsProvider.java b/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2UnicastHostsProvider.java
index abca15afd8e3a..a8f99462b9442 100644
--- a/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2UnicastHostsProvider.java
+++ b/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2UnicastHostsProvider.java
@@ -19,6 +19,7 @@
package org.elasticsearch.discovery.ec2;
+import com.amazonaws.AmazonClientException;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.*;
import org.elasticsearch.Version;
@@ -96,7 +97,14 @@ public AwsEc2UnicastHostsProvider(Settings settings, TransportService transportS
public List<DiscoveryNode> buildDynamicNodes() {
List<DiscoveryNode> discoNodes = Lists.newArrayList();
- DescribeInstancesResult descInstances = client.describeInstances(new DescribeInstancesRequest());
+ DescribeInstancesResult descInstances;
+ try {
+ descInstances = client.describeInstances(new DescribeInstancesRequest());
+ } catch (AmazonClientException e) {
+ logger.info("Exception while retrieving instance list from AWS API: {}", e.getMessage());
+ logger.debug("Full exception:", e);
+ return discoNodes;
+ }
logger.trace("building dynamic unicast discovery nodes...");
for (Reservation reservation : descInstances.getReservations()) {
|
f53baebf899b9a03f2bddbc205a764f3002911eb
|
kotlin
|
Show warning on usages of javaClass<T>() in- annotations loaded from Java--
|
a
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/JavaAnnotationCallChecker.kt b/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/JavaAnnotationCallChecker.kt
index ec41dae95eceb..07f917fcf7430 100644
--- a/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/JavaAnnotationCallChecker.kt
+++ b/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/JavaAnnotationCallChecker.kt
@@ -16,15 +16,23 @@
package org.jetbrains.kotlin.load.kotlin
+import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.CallableDescriptor
+import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
+import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
+import org.jetbrains.kotlin.diagnostics.DiagnosticFactory0
import org.jetbrains.kotlin.load.java.JvmAnnotationNames
import org.jetbrains.kotlin.load.java.descriptors.JavaConstructorDescriptor
+import org.jetbrains.kotlin.psi.JetExpression
+import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
+import org.jetbrains.kotlin.resolve.calls.model.ResolvedValueArgument
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
+import org.jetbrains.kotlin.types.JetType
public class JavaAnnotationCallChecker : CallChecker {
override fun <F : CallableDescriptor?> check(resolvedCall: ResolvedCall<F>, context: BasicCallResolutionContext) {
@@ -32,14 +40,56 @@ public class JavaAnnotationCallChecker : CallChecker {
if (resultingDescriptor !is JavaConstructorDescriptor ||
resultingDescriptor.getContainingDeclaration().getKind() != ClassKind.ANNOTATION_CLASS) return
+ reportErrorsOnPositionedArguments(resolvedCall, context)
+ reportWarningOnJavaClassUsages(resolvedCall, context)
+ }
+
+ private fun reportWarningOnJavaClassUsages(
+ resolvedCall: ResolvedCall<*>,
+ context: BasicCallResolutionContext
+ ) {
+ resolvedCall.getValueArguments().filter { it.getKey().getType().isJavaLangClassOrArray() }.forEach {
+ reportOnValueArgument(context, it, ErrorsJvm.JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION)
+ }
+ }
+
+ private fun JetType.isJavaLangClassOrArray() = isJavaLangClass() ||
+ (KotlinBuiltIns.isArray(this) && getArguments().first().getType().isJavaLangClass())
+
+ private fun JetType.isJavaLangClass(): Boolean {
+ val classifier = getConstructor().getDeclarationDescriptor()
+
+ if (classifier !is ClassDescriptor) return false
+ return DescriptorUtils.isJavaLangClass(classifier)
+ }
+
+ private fun reportErrorsOnPositionedArguments(
+ resolvedCall: ResolvedCall<*>,
+ context: BasicCallResolutionContext
+ ) {
resolvedCall.getValueArguments().filter {
- p -> p.key.getName() != JvmAnnotationNames.DEFAULT_ANNOTATION_MEMBER_NAME &&
- p.value is ExpressionValueArgument &&
- !((p.value as ExpressionValueArgument).getValueArgument()?.isNamed() ?: true)
+ p ->
+ p.key.getName() != JvmAnnotationNames.DEFAULT_ANNOTATION_MEMBER_NAME &&
+ p.value is ExpressionValueArgument &&
+ !((p.value as ExpressionValueArgument).getValueArgument()?.isNamed() ?: true)
}.forEach {
- context.trace.report(
- ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION.on(
- it.getValue().getArguments().first().getArgumentExpression()))
+ reportOnValueArgument(context, it, ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION)
+ }
+ }
+
+ private fun reportOnValueArgument(
+ context: BasicCallResolutionContext,
+ argument: Map.Entry<ValueParameterDescriptor, ResolvedValueArgument>,
+ diagnostic: DiagnosticFactory0<JetExpression>
+ ) {
+ argument.getValue().getArguments().forEach {
+ if (it.getArgumentExpression() != null) {
+ context.trace.report(
+ diagnostic.on(
+ it.getArgumentExpression()
+ )
+ )
+ }
}
}
}
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 92550e0b3e788..4d72b7482cc13 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
@@ -57,6 +57,7 @@ public String render(@NotNull ConflictingJvmDeclarationsData data) {
MAP.put(ErrorsJvm.NATIVE_DECLARATION_CANNOT_BE_INLINED, "Members of traits can not be inlined");
MAP.put(ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION, "Only named arguments are available for Java annotations");
+ MAP.put(ErrorsJvm.JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION, "Usage of `javaClass<T>()` in annotations is deprecated. Use T::class instead");
MAP.put(ErrorsJvm.NO_REFLECTION_IN_CLASS_PATH, "Expression ''{0}'' uses reflection which is not found in compilation classpath. Make sure you have kotlin-reflect.jar in the classpath", Renderers.ELEMENT_TEXT);
diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/ErrorsJvm.java b/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/ErrorsJvm.java
index d28078e6e6b4c..c0b5ec2f51d48 100644
--- a/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/ErrorsJvm.java
+++ b/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/ErrorsJvm.java
@@ -52,6 +52,7 @@ public interface ErrorsJvm {
DiagnosticFactory0<JetDeclaration> NATIVE_DECLARATION_CANNOT_BE_INLINED = DiagnosticFactory0.create(ERROR, DECLARATION_SIGNATURE);
DiagnosticFactory0<JetExpression> POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION = DiagnosticFactory0.create(ERROR);
+ DiagnosticFactory0<JetExpression> JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION = DiagnosticFactory0.create(WARNING);
// TODO: make this a warning
DiagnosticFactory1<JetExpression, JetExpression> NO_REFLECTION_IN_CLASS_PATH = DiagnosticFactory1.create(ERROR);
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.java
index f5b310d1a9ffc..4792eeee08129 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.java
@@ -306,7 +306,7 @@ private static void checkCompileTimeConstant(
if (descriptor != null && DescriptorUtils.isEnumClass(descriptor)) {
trace.report(Errors.ANNOTATION_PARAMETER_MUST_BE_ENUM_CONST.on(argumentExpression));
}
- else if (descriptor instanceof ClassDescriptor && CompileTimeConstantUtils.isJavaLangClass((ClassDescriptor) descriptor)) {
+ else if (descriptor instanceof ClassDescriptor && DescriptorUtils.isJavaLangClass((ClassDescriptor) descriptor)) {
trace.report(Errors.ANNOTATION_PARAMETER_MUST_BE_CLASS_LITERAL.on(argumentExpression));
}
else if (descriptor instanceof ClassDescriptor && KotlinBuiltIns.isKClass((ClassDescriptor) descriptor)) {
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/CompileTimeConstantUtils.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/CompileTimeConstantUtils.java
index 2187d6d074bbf..aae2f988c6cf0 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/CompileTimeConstantUtils.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/CompileTimeConstantUtils.java
@@ -78,7 +78,7 @@ private static boolean isAcceptableTypeForAnnotationParameter(@NotNull JetType p
KotlinBuiltIns builtIns = KotlinBuiltIns.getInstance();
if (isEnumClass(typeDescriptor) ||
isAnnotationClass(typeDescriptor) ||
- isJavaLangClass(typeDescriptor) ||
+ DescriptorUtils.isJavaLangClass(typeDescriptor) ||
KotlinBuiltIns.isKClass(typeDescriptor) ||
KotlinBuiltIns.isPrimitiveArray(parameterType) ||
KotlinBuiltIns.isPrimitiveType(parameterType) ||
@@ -97,7 +97,7 @@ private static boolean isAcceptableTypeForAnnotationParameter(@NotNull JetType p
if (arrayTypeDescriptor != null) {
return isEnumClass(arrayTypeDescriptor) ||
isAnnotationClass(arrayTypeDescriptor) ||
- isJavaLangClass(arrayTypeDescriptor) ||
+ DescriptorUtils.isJavaLangClass(arrayTypeDescriptor) ||
KotlinBuiltIns.isKClass(arrayTypeDescriptor) ||
builtIns.getStringType().equals(arrayType);
}
@@ -127,10 +127,6 @@ public static boolean isJavaClassMethodCall(@NotNull ResolvedCall<?> resolvedCal
return "kotlin.javaClass.function".equals(getIntrinsicAnnotationArgument(resolvedCall.getResultingDescriptor().getOriginal()));
}
- public static boolean isJavaLangClass(ClassDescriptor descriptor) {
- return "java.lang.Class".equals(DescriptorUtils.getFqName(descriptor).asString());
- }
-
public static boolean canBeReducedToBooleanConstant(
@Nullable JetExpression expression,
@NotNull BindingTrace trace,
diff --git a/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArgumentError.kt b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArgumentError.kt
new file mode 100644
index 0000000000000..f1e76b1d440f2
--- /dev/null
+++ b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArgumentError.kt
@@ -0,0 +1,17 @@
+// FILE: A.java
+public @interface A {
+ Class<?>[] value();
+}
+
+// FILE: b.kt
+val jClass = javaClass<String>()
+A(
+ <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION, ANNOTATION_PARAMETER_MUST_BE_CLASS_LITERAL!>jClass<!>,
+ <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Int>()<!>
+)
+class MyClass1
+
+A(
+ <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<<!UNRESOLVED_REFERENCE!>Err<!>>()<!>,
+ <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<String>()<!>
+) class MyClass2
diff --git a/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArgumentError.txt b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArgumentError.txt
new file mode 100644
index 0000000000000..3fb2f0ce6ac25
--- /dev/null
+++ b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArgumentError.txt
@@ -0,0 +1,26 @@
+package
+
+internal val jClass: java.lang.Class<kotlin.String>
+
+public final annotation class A : kotlin.Annotation {
+ public /*synthesized*/ constructor A(/*0*/ vararg value: java.lang.Class<*> /*kotlin.Array<out java.lang.Class<*>>*/)
+ public constructor A(/*0*/ vararg value: kotlin.reflect.KClass<*> /*kotlin.Array<out kotlin.reflect.KClass<*>>*/)
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+ public abstract fun value(): kotlin.Array<kotlin.reflect.KClass<*>>
+}
+
+A(value = {javaClass<kotlin.Int>()}: kotlin.Array<out java.lang.Class<*>>) internal final class MyClass1 {
+ public constructor MyClass1()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(value = {javaClass<[ERROR : Err]>(), javaClass<kotlin.String>()}: kotlin.Array<out java.lang.Class<*>>) internal final class MyClass2 {
+ public constructor MyClass2()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
diff --git a/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArrayInAnnotations.kt b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArrayInAnnotations.kt
new file mode 100644
index 0000000000000..ab3eab07cbc76
--- /dev/null
+++ b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArrayInAnnotations.kt
@@ -0,0 +1,26 @@
+// FILE: A.java
+public @interface A {
+ Class<?>[] value() default {Integer.class};
+ Class<?>[] arg() default {String.class};
+}
+
+// FILE: b.kt
+A(<!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Int>()<!>,
+<!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Any>()<!>,
+arg = <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>array(javaClass<String>(), javaClass<Double>())<!>)
+class MyClass1
+
+A(<!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Int>()<!>, <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Any>()<!>)
+class MyClass2
+
+A(arg = <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>array(javaClass<String>(), javaClass<Double>())<!>)
+class MyClass3
+
+A class MyClass4
+
+A(value = *<!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>array(javaClass<Int>(), javaClass<Any>())<!>,
+arg = <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>array(javaClass<String>(), javaClass<Double>())<!>)
+class MyClass5
+
+A(value = *<!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>array(javaClass<Int>(), javaClass<Any>())<!>)
+class MyClass6
diff --git a/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArrayInAnnotations.txt b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArrayInAnnotations.txt
new file mode 100644
index 0000000000000..5f97cf407f09b
--- /dev/null
+++ b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArrayInAnnotations.txt
@@ -0,0 +1,53 @@
+package
+
+public final annotation class A : kotlin.Annotation {
+ public /*synthesized*/ constructor A(/*0*/ vararg value: java.lang.Class<*> /*kotlin.Array<out java.lang.Class<*>>*/ = ..., /*1*/ arg: kotlin.Array<out java.lang.Class<*>> = ...)
+ public constructor A(/*0*/ vararg value: kotlin.reflect.KClass<*> /*kotlin.Array<out kotlin.reflect.KClass<*>>*/ = ..., /*1*/ arg: kotlin.Array<out kotlin.reflect.KClass<*>> = ...)
+ public abstract fun arg(): kotlin.Array<kotlin.reflect.KClass<*>>
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+ public abstract fun value(): kotlin.Array<kotlin.reflect.KClass<*>>
+}
+
+A(arg = {javaClass<kotlin.String>(), javaClass<kotlin.Double>()}: kotlin.Array<java.lang.Class<out kotlin.Comparable<out kotlin.Any?>>>, value = {javaClass<kotlin.Int>(), javaClass<kotlin.Any>()}: kotlin.Array<out java.lang.Class<*>>) internal final class MyClass1 {
+ public constructor MyClass1()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(value = {javaClass<kotlin.Int>(), javaClass<kotlin.Any>()}: kotlin.Array<out java.lang.Class<*>>) internal final class MyClass2 {
+ public constructor MyClass2()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(arg = {javaClass<kotlin.String>(), javaClass<kotlin.Double>()}: kotlin.Array<java.lang.Class<out kotlin.Comparable<out kotlin.Any?>>>) internal final class MyClass3 {
+ public constructor MyClass3()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A() internal final class MyClass4 {
+ public constructor MyClass4()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(arg = {javaClass<kotlin.String>(), javaClass<kotlin.Double>()}: kotlin.Array<java.lang.Class<out kotlin.Comparable<out kotlin.Any?>>>, value = {javaClass<kotlin.Int>(), javaClass<kotlin.Any>()}: kotlin.Array<java.lang.Class<out kotlin.Any>>) internal final class MyClass5 {
+ public constructor MyClass5()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(value = {javaClass<kotlin.Int>(), javaClass<kotlin.Any>()}: kotlin.Array<java.lang.Class<out kotlin.Any>>) internal final class MyClass6 {
+ public constructor MyClass6()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
diff --git a/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassInAnnotations.kt b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassInAnnotations.kt
new file mode 100644
index 0000000000000..4a7adf7db8045
--- /dev/null
+++ b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassInAnnotations.kt
@@ -0,0 +1,14 @@
+// FILE: A.java
+public @interface A {
+ Class<?> value() default Integer.class;
+ Class<?> arg() default String.class;
+}
+
+// FILE: b.kt
+A(<!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Int>()<!>, arg = <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<String>()<!>) class MyClass1
+A(<!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Int>()<!>) class MyClass2
+A(arg = <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<String>()<!>) class MyClass3
+A class MyClass4
+
+A(value = <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Int>()<!>, arg = <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<String>()<!>) class MyClass5
+A(value = <!JAVA_LANG_CLASS_ARGUMENT_IN_ANNOTATION!>javaClass<Int>()<!>) class MyClass6
diff --git a/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassInAnnotations.txt b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassInAnnotations.txt
new file mode 100644
index 0000000000000..5318be6a8f630
--- /dev/null
+++ b/compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassInAnnotations.txt
@@ -0,0 +1,53 @@
+package
+
+public final annotation class A : kotlin.Annotation {
+ public /*synthesized*/ constructor A(/*0*/ value: java.lang.Class<*> = ..., /*1*/ arg: java.lang.Class<*> = ...)
+ public constructor A(/*0*/ value: kotlin.reflect.KClass<*> = ..., /*1*/ arg: kotlin.reflect.KClass<*> = ...)
+ public abstract fun arg(): kotlin.reflect.KClass<*>
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+ public abstract fun value(): kotlin.reflect.KClass<*>
+}
+
+A(arg = javaClass<kotlin.String>(): java.lang.Class<kotlin.String>, value = javaClass<kotlin.Int>(): java.lang.Class<kotlin.Int>) internal final class MyClass1 {
+ public constructor MyClass1()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(value = javaClass<kotlin.Int>(): java.lang.Class<kotlin.Int>) internal final class MyClass2 {
+ public constructor MyClass2()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(arg = javaClass<kotlin.String>(): java.lang.Class<kotlin.String>) internal final class MyClass3 {
+ public constructor MyClass3()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A() internal final class MyClass4 {
+ public constructor MyClass4()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(arg = javaClass<kotlin.String>(): java.lang.Class<kotlin.String>, value = javaClass<kotlin.Int>(): java.lang.Class<kotlin.Int>) internal final class MyClass5 {
+ public constructor MyClass5()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
+
+A(value = javaClass<kotlin.Int>(): java.lang.Class<kotlin.Int>) internal final class MyClass6 {
+ public constructor MyClass6()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+}
diff --git a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestWithStdLibGenerated.java b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestWithStdLibGenerated.java
index 16ff8282609fd..72ad06d7a15dc 100644
--- a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestWithStdLibGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestWithStdLibGenerated.java
@@ -117,6 +117,24 @@ public void testAllFilesPresentInAnnotationParameters() throws Exception {
JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters"), Pattern.compile("^(.+)\\.kt$"), true);
}
+ @TestMetadata("javaClassArgumentError.kt")
+ public void testJavaClassArgumentError() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArgumentError.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("javaClassArrayInAnnotations.kt")
+ public void testJavaClassArrayInAnnotations() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassArrayInAnnotations.kt");
+ doTest(fileName);
+ }
+
+ @TestMetadata("javaClassInAnnotations.kt")
+ public void testJavaClassInAnnotations() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/javaClassInAnnotations.kt");
+ doTest(fileName);
+ }
+
@TestMetadata("orderWithValue.kt")
public void testOrderWithValue() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/testsWithStdLib/annotations/annotationParameters/orderWithValue.kt");
diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorUtils.java b/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorUtils.java
index 275c7047a0a35..2b2a107fef7ca 100644
--- a/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorUtils.java
+++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorUtils.java
@@ -532,4 +532,8 @@ private static void getSubPackagesFqNames(PackageViewDescriptor packageView, Set
}
}
}
+
+ public static boolean isJavaLangClass(ClassDescriptor descriptor) {
+ return "java.lang.Class".equals(getFqName(descriptor).asString());
+ }
}
|
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
|
80636e5a6f8e4283b0470306331c013c2ea38018
|
restlet-framework-java
|
Fixed bug--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/source/main/com/noelios/restlet/util/UniformCallModel.java b/source/main/com/noelios/restlet/util/UniformCallModel.java
index 3bbf8a82f9..172d18540f 100644
--- a/source/main/com/noelios/restlet/util/UniformCallModel.java
+++ b/source/main/com/noelios/restlet/util/UniformCallModel.java
@@ -118,7 +118,7 @@ public String get(String name)
if((rest.charAt(0) == '[') && (rest.charAt(rest.length() - 1) == ']'))
{
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
if(rest.equals("first"))
{
@@ -155,7 +155,7 @@ else if(name.startsWith(NAME_COOKIE))
if((rest.charAt(0) == '[') && (rest.charAt(rest.length() - 1) == ']'))
{
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
if(rest.equals("first"))
{
@@ -168,7 +168,7 @@ else if(rest.equals("last"))
else if((rest.charAt(0) == '"') && (rest.charAt(rest.length() - 1) == '"'))
{
// Lookup by name
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
result = CookieUtils.getFirstCookie(call.getCookies(), rest).getValue();
}
else
@@ -234,7 +234,7 @@ else if(name.startsWith(NAME_RESOURCE_QUERY))
if((rest.charAt(0) == '[') && (rest.charAt(rest.length() - 1) == ']'))
{
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
if(rest.equals("first"))
{
@@ -248,7 +248,7 @@ else if(rest.equals("last"))
else if((rest.charAt(0) == '"') && (rest.charAt(rest.length() - 1) == '"'))
{
// Lookup by name
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
result = call.getResourceRef().getQueryAsForm().getFirstParameter(rest).getValue();
}
else
|
7b7ab09e22500c6140fafbf59e46c5d3843571c7
|
camel
|
CAMEL-1842 Added OSGi integration test for- camel-mail and camel-cxf--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@795813 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/examples/camel-example-reportincident/pom.xml b/examples/camel-example-reportincident/pom.xml
index ec1468cc86253..a314c4cc51c77 100755
--- a/examples/camel-example-reportincident/pom.xml
+++ b/examples/camel-example-reportincident/pom.xml
@@ -31,89 +31,157 @@
and send as emails to a backing system
</description>
<packaging>war</packaging>
+
+ <repositories>
+ <repository>
+ <id>ops4j.releases</id>
+ <url>http://repository.ops4j.org/maven2</url>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ </repository>
+ <repository>
+ <id>ops4j.snapshots</id>
+ <url>http://repository.ops4j.org/mvn-snapshots</url>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ <repository>
+ <id>aqute.biz</id>
+ <url>http://www.aqute.biz/repo</url>
+ </repository>
+ </repositories>
- <dependencies>
- <dependency>
- <groupId>org.apache.camel</groupId>
- <artifactId>camel-core</artifactId>
- </dependency>
+ <pluginRepositories>
+ <pluginRepository>
+ <id>ops4j.releases</id>
+ <url>http://repository.ops4j.org/maven2</url>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ </pluginRepository>
+ </pluginRepositories>
- <dependency>
- <groupId>org.apache.camel</groupId>
- <artifactId>camel-spring</artifactId>
- </dependency>
+ <properties>
+ <pax-exam-version>0.6.0</pax-exam-version>
+ <pax-tiny-bundle-version>1.0.0</pax-tiny-bundle-version>
+ </properties>
- <dependency>
- <groupId>org.apache.camel</groupId>
- <artifactId>camel-cxf</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.camel</groupId>
- <artifactId>camel-velocity</artifactId>
- </dependency>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-core</artifactId>
+ </dependency>
- <dependency>
- <groupId>org.apache.camel</groupId>
- <artifactId>camel-mail</artifactId>
- </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-spring</artifactId>
+ </dependency>
- <!-- cxf -->
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-core</artifactId>
- <version>${cxf-version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-frontend-jaxws</artifactId>
- <version>${cxf-version}</version>
- </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-cxf</artifactId>
+ </dependency>
- <!-- regular http transport -->
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-transports-http</artifactId>
- <version>${cxf-version}</version>
- </dependency>
-
- <!-- logging -->
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.14</version>
- </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-velocity</artifactId>
+ </dependency>
- <!-- cxf web container for unit testing -->
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-transports-http-jetty</artifactId>
- <version>${cxf-version}</version>
- </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-mail</artifactId>
+ </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.2</version>
- <scope>test</scope>
- </dependency>
+ <!-- cxf -->
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-core</artifactId>
+ <version>${cxf-version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-frontend-jaxws</artifactId>
+ <version>${cxf-version}</version>
+ </dependency>
- <!-- unit testing mail using mock -->
- <dependency>
- <groupId>org.jvnet.mock-javamail</groupId>
- <artifactId>mock-javamail</artifactId>
- <version>1.7</version>
- <scope>test</scope>
- </dependency>
+ <!-- regular http transport -->
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-transports-http</artifactId>
+ <version>${cxf-version}</version>
+ </dependency>
- <dependency>
- <groupId>org.apache.camel</groupId>
- <artifactId>camel-core</artifactId>
- <scope>test</scope>
- <type>test-jar</type>
- </dependency>
+ <!-- logging -->
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.14</version>
+ </dependency>
+
+ <!-- cxf web container for unit testing -->
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-transports-http-jetty</artifactId>
+ <version>${cxf-version}</version>
+ </dependency>
- </dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam</artifactId>
+ <version>${pax-exam-version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-junit</artifactId>
+ <version>${pax-exam-version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-container-default</artifactId>
+ <version>${pax-exam-version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-junit-extender-impl</artifactId>
+ <version>${pax-exam-version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.swissbox</groupId>
+ <artifactId>pax-swissbox-tinybundles</artifactId>
+ <version>1.0.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel.karaf</groupId>
+ <artifactId>features</artifactId>
+ <version>${version}</version>
+ <type>pom</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-osgi</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel.tests</groupId>
+ <artifactId>org.apache.camel.tests.mock-javamail_1.7</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
<build>
<plugins>
@@ -127,7 +195,20 @@
<target>1.5</target>
</configuration>
</plugin>
-
+
+ <plugin>
+ <groupId>org.apache.servicemix.tooling</groupId>
+ <artifactId>depends-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>generate-depends-file</id>
+ <goals>
+ <goal>generate-depends-file</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
<!-- CXF wsdl2java generator, will plugin to the compile goal -->
<plugin>
<groupId>org.apache.cxf</groupId>
@@ -141,7 +222,7 @@
<sourceRoot>${basedir}/target/generated/src/main/java</sourceRoot>
<wsdlOptions>
<wsdlOption>
- <wsdl>${basedir}/src/main/resources/report_incident.wsdl</wsdl>
+ <wsdl>${basedir}/src/main/resources/etc/report_incident.wsdl</wsdl>
</wsdlOption>
</wsdlOptions>
</configuration>
@@ -167,6 +248,16 @@
</configuration>
</plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <excludes>
+ <!-- TODO: temporary disable unit test to let TC not hang -->
+ <exclude>**/*OSGiTest.*</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+
</plugins>
</build>
diff --git a/examples/camel-example-reportincident/src/main/java/org/apache/camel/example/reportincident/ReportIncidentRoutes.java b/examples/camel-example-reportincident/src/main/java/org/apache/camel/example/reportincident/ReportIncidentRoutes.java
index 49a4d40e32c81..a8d49efd54319 100755
--- a/examples/camel-example-reportincident/src/main/java/org/apache/camel/example/reportincident/ReportIncidentRoutes.java
+++ b/examples/camel-example-reportincident/src/main/java/org/apache/camel/example/reportincident/ReportIncidentRoutes.java
@@ -48,7 +48,7 @@ public void configure() throws Exception {
}
String cxfEndpoint = cxfEndpointAddress
+ "?serviceClass=org.apache.camel.example.reportincident.ReportIncidentEndpoint"
- + "&wsdlURL=report_incident.wsdl";
+ + "&wsdlURL=etc/report_incident.wsdl";
// first part from the webservice -> file backup
from(cxfEndpoint)
@@ -57,7 +57,7 @@ public void configure() throws Exception {
// then set the file name using the FilenameGenerator bean
.setHeader(Exchange.FILE_NAME, BeanLanguage.bean(FilenameGenerator.class, "generateFilename"))
// and create the mail body using velocity template
- .to("velocity:MailBody.vm")
+ .to("velocity:etc/MailBody.vm")
// and store the file
.to("file://target/subfolder")
// return OK as response
diff --git a/examples/camel-example-reportincident/src/main/resources/META-INF/spring/camel-context.xml b/examples/camel-example-reportincident/src/main/resources/META-INF/spring/camel-context.xml
index 288646a52274b..b19fd2f8af620 100644
--- a/examples/camel-example-reportincident/src/main/resources/META-INF/spring/camel-context.xml
+++ b/examples/camel-example-reportincident/src/main/resources/META-INF/spring/camel-context.xml
@@ -31,7 +31,7 @@
<cxf:cxfEndpoint id="reportIncident"
address="http://localhost:9080/camel-example-reportincident/webservices/incident"
- wsdlURL="report_incident.wsdl"
+ wsdlURL="etc/report_incident.wsdl"
serviceClass="org.apache.camel.example.reportincident.ReportIncidentEndpoint">
</cxf:cxfEndpoint>
@@ -46,7 +46,7 @@
<camel:setHeader headerName="CamelFileName">
<camel:method bean="filenameGenerator" method="generateFilename" />
</camel:setHeader>
- <camel:to uri="velocity:MailBody.vm"/>
+ <camel:to uri="velocity:etc/MailBody.vm"/>
<camel:to uri="file://target/subfolder"/>
<camel:transform>
<camel:method bean="myBean" method="getOK" />
diff --git a/examples/camel-example-reportincident/src/main/resources/MailBody.vm b/examples/camel-example-reportincident/src/main/resources/etc/MailBody.vm
similarity index 100%
rename from examples/camel-example-reportincident/src/main/resources/MailBody.vm
rename to examples/camel-example-reportincident/src/main/resources/etc/MailBody.vm
diff --git a/examples/camel-example-reportincident/src/main/resources/report_incident.wsdl b/examples/camel-example-reportincident/src/main/resources/etc/report_incident.wsdl
similarity index 100%
rename from examples/camel-example-reportincident/src/main/resources/report_incident.wsdl
rename to examples/camel-example-reportincident/src/main/resources/etc/report_incident.wsdl
diff --git a/examples/camel-example-reportincident/src/test/java/org/apache/camel/example/reportincident/ReportIncidentRoutesOSGiTest.java b/examples/camel-example-reportincident/src/test/java/org/apache/camel/example/reportincident/ReportIncidentRoutesOSGiTest.java
new file mode 100644
index 0000000000000..938ce29fce661
--- /dev/null
+++ b/examples/camel-example-reportincident/src/test/java/org/apache/camel/example/reportincident/ReportIncidentRoutesOSGiTest.java
@@ -0,0 +1,118 @@
+/**
+ * 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.example.reportincident;
+
+
+import org.apache.camel.CamelContext;
+
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.osgi.CamelContextFactory;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.jvnet.mock_javamail.Mailbox;
+import org.ops4j.pax.exam.Inject;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.Configuration;
+import org.ops4j.pax.exam.junit.JUnit4TestRunner;
+import org.ops4j.pax.swissbox.tinybundles.core.TinyBundle;
+import org.ops4j.pax.swissbox.tinybundles.dp.Constants;
+import org.osgi.framework.BundleContext;
+
+import static org.ops4j.pax.exam.CoreOptions.bundle;
+import static org.ops4j.pax.exam.CoreOptions.felix;
+import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
+import static org.ops4j.pax.exam.CoreOptions.options;
+import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.logProfile;
+import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.profile;
+import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures;
+import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.asURL;
+import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.newBundle;
+import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.withBnd;
+/**
+ * Unit test of our routes
+ */
+@RunWith(JUnit4TestRunner.class)
+public class ReportIncidentRoutesOSGiTest extends ReportIncidentRoutesTest {
+ private static final transient Log LOG = LogFactory.getLog(ReportIncidentRoutesOSGiTest.class);
+
+ @Inject
+ protected BundleContext bundleContext;
+
+ protected void startOSGiCamel() throws Exception {
+ CamelContextFactory factory = new CamelContextFactory();
+ factory.setBundleContext(bundleContext);
+ LOG.info("Get the bundleContext is " + bundleContext);
+ camel = factory.createContext();
+ ReportIncidentRoutes routes = new ReportIncidentRoutes();
+ routes.setUsingServletTransport(false);
+ camel.addRoutes(routes);
+ camel.start();
+ }
+
+
+ @Test
+ public void testRendportIncident() throws Exception {
+ startOSGiCamel();
+ runTest();
+ stopCamel();
+ }
+
+ @Configuration
+ public static Option[] configure() {
+ Option[] options = options(
+ // install log service using pax runners profile abstraction (there are more profiles, like DS)
+ logProfile().version("1.3.0"),
+ // install the spring dm profile
+ profile("spring.dm").version("1.2.0"),
+ // this is how you set the default log level when using pax logging (logProfile)
+ org.ops4j.pax.exam.CoreOptions.systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
+ org.ops4j.pax.exam.CoreOptions.systemProperty("org.apache.cxf.nofastinfoset").value("false"),
+ org.ops4j.pax.exam.CoreOptions.systemProperty("xml.catalog.staticCatalog").value("false"),
+ // using the features to install the camel components
+ scanFeatures(mavenBundle().groupId("org.apache.camel.karaf").
+ artifactId("features").versionAsInProject().type("xml/features"),
+ "camel-core", "camel-osgi", "camel-spring", "camel-test", "camel-velocity", "camel-cxf", "camel-mail"),
+
+ // Added the mock_java_mail bundle for testing
+ mavenBundle().groupId("org.apache.camel.tests").artifactId("org.apache.camel.tests.mock-javamail_1.7").versionAsInProject(),
+
+ // create a customer bundle start up the report incident bundle
+ bundle(newBundle().addClass(InputReportIncident.class)
+ .addClass(ObjectFactory.class)
+ .addClass(OutputReportIncident.class)
+ .addClass(ReportIncidentRoutesOSGiTest.class)
+ .addClass(ReportIncidentRoutesTest.class)
+ .addClass(ReportIncidentRoutes.class)
+ .addClass(MyBean.class)
+ .addClass(FilenameGenerator.class)
+ .addClass(ReportIncidentEndpoint.class)
+ .addClass(ReportIncidentEndpointService.class)
+ .addResource("etc/report_incident.wsdl", ReportIncidentRoutesTest.class.getResource("/etc/report_incident.wsdl"))
+ .addResource("etc/MailBody.vm", ReportIncidentRoutesTest.class.getResource("/etc/MailBody.vm"))
+ .prepare(withBnd().set(Constants.BUNDLE_SYMBOLICNAME, "CamelExampleReportIncidentBundle")
+ .set(Constants.EXPORT_PACKAGE, "org.apache.camel.example.reportincident,etc")).build(asURL()).toString()),
+
+
+ felix());
+
+ return options;
+ }
+
+}
diff --git a/examples/camel-example-reportincident/src/test/java/org/apache/camel/example/reportincident/ReportIncidentRoutesTest.java b/examples/camel-example-reportincident/src/test/java/org/apache/camel/example/reportincident/ReportIncidentRoutesTest.java
index 6a602a2186c43..8ecb760c0c3ff 100755
--- a/examples/camel-example-reportincident/src/test/java/org/apache/camel/example/reportincident/ReportIncidentRoutesTest.java
+++ b/examples/camel-example-reportincident/src/test/java/org/apache/camel/example/reportincident/ReportIncidentRoutesTest.java
@@ -20,12 +20,15 @@
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
+import org.junit.Test;
import org.jvnet.mock_javamail.Mailbox;
+import static org.junit.Assert.assertEquals;
+
/**
* Unit test of our routes
*/
-public class ReportIncidentRoutesTest extends TestCase {
+public class ReportIncidentRoutesTest {
// should be the same address as we have in our route
private static final String URL = "http://localhost:9080/camel-example-reportincident/webservices/incident";
@@ -52,10 +55,18 @@ protected static ReportIncidentEndpoint createCXFClient() {
return (ReportIncidentEndpoint) factory.create();
}
+ @Test
public void testRendportIncident() throws Exception {
// start camel
startCamel();
+ runTest();
+
+ // stop camel
+ stopCamel();
+ }
+
+ protected void runTest() throws Exception {
// assert mailbox is empty before starting
Mailbox inbox = Mailbox.get("[email protected]");
inbox.clear();
@@ -84,8 +95,5 @@ public void testRendportIncident() throws Exception {
// assert mail box
assertEquals("Should have got 1 mail", 1, inbox.size());
-
- // stop camel
- stopCamel();
}
}
diff --git a/parent/pom.xml b/parent/pom.xml
index d004878066b4d..b1808760a2837 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -443,6 +443,12 @@
<artifactId>camel-manual</artifactId>
<version>${project.version}</version>
</dependency>
+
+ <dependency>
+ <groupId>org.apache.camel.tests</groupId>
+ <artifactId>org.apache.camel.tests.mock-javamail_1.7</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<!-- testing jars -->
<dependency>
diff --git a/pom.xml b/pom.xml
index e9b9433155aff..17c92e2ca0310 100755
--- a/pom.xml
+++ b/pom.xml
@@ -97,10 +97,10 @@
<module>parent</module>
<module>camel-core</module>
<module>components</module>
- <module>examples</module>
<module>platforms</module>
<module>tooling</module>
<module>tests</module>
+ <module>examples</module>
<module>apache-camel</module>
</modules>
diff --git a/tests/camel-itest-osgi/pom.xml b/tests/camel-itest-osgi/pom.xml
index a7a4329fdd905..36021410a093c 100644
--- a/tests/camel-itest-osgi/pom.xml
+++ b/tests/camel-itest-osgi/pom.xml
@@ -127,6 +127,21 @@
<groupId>org.apache.camel</groupId>
<artifactId>camel-servlet</artifactId>
<scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel.tests</groupId>
+ <artifactId>org.apache.camel.tests.mock-javamail_1.7</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context-support</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-test</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/MailRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/MailRouteTest.java
new file mode 100644
index 0000000000000..11260009a1006
--- /dev/null
+++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/MailRouteTest.java
@@ -0,0 +1,146 @@
+/**
+ * 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.osgi;
+
+import java.io.InputStream;
+import java.util.HashMap;
+
+import javax.mail.Address;
+import javax.mail.Message;
+import javax.mail.Message.RecipientType;
+
+
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.converter.IOConverter;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.jvnet.mock_javamail.Mailbox;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.Configuration;
+import org.ops4j.pax.exam.junit.JUnit4TestRunner;
+
+import static org.ops4j.pax.exam.CoreOptions.felix;
+import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
+import static org.ops4j.pax.exam.CoreOptions.options;
+import static org.ops4j.pax.exam.CoreOptions.provision;
+import static org.ops4j.pax.exam.CoreOptions.wrappedBundle;
+import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.logProfile;
+import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.profile;
+import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures;
+
+@RunWith(JUnit4TestRunner.class)
+public class MailRouteTest extends OSGiIntegrationTestSupport {
+
+ @Test
+ public void testSendAndReceiveMails() throws Exception {
+ Mailbox.clearAll();
+
+ MockEndpoint resultEndpoint = getMockEndpoint("mock:result");
+ resultEndpoint.expectedBodiesReceived("hello world!");
+
+ HashMap<String, Object> headers = new HashMap<String, Object>();
+ headers.put("reply-to", "route-test-reply@localhost");
+ template.sendBodyAndHeaders("smtp://route-test-james@localhost", "hello world!", headers);
+
+ // lets test the first sent worked
+ assertMailboxReceivedMessages("route-test-james@localhost");
+
+ // lets sleep to check that the mail poll does not redeliver duplicate mails
+ Thread.sleep(3000);
+
+ // lets test the receive worked
+ resultEndpoint.assertIsSatisfied();
+
+ // Validate that the headers were preserved.
+ Exchange exchange = resultEndpoint.getReceivedExchanges().get(0);
+ String replyTo = (String)exchange.getIn().getHeader("reply-to");
+ assertEquals("route-test-reply@localhost", replyTo);
+
+ assertMailboxReceivedMessages("route-test-copy@localhost");
+ }
+
+ protected void assertMailboxReceivedMessages(String name) throws Exception {
+ Mailbox mailbox = Mailbox.get(name);
+ assertEquals(name + " should have received 1 mail", 1, mailbox.size());
+
+ Message message = mailbox.get(0);
+ assertNotNull(name + " should have received at least one mail!", message);
+ Object content = message.getContent();
+ assertNotNull("The content should not be null!", content);
+ if (content instanceof InputStream) {
+ assertEquals("hello world!", IOConverter.toString((InputStream)content));
+ } else {
+ assertEquals("hello world!", message.getContent());
+ }
+ assertEquals("camel@localhost", message.getFrom()[0].toString());
+ boolean found = false;
+ for (Address adr : message.getRecipients(RecipientType.TO)) {
+ if (name.equals(adr.toString())) {
+ found = true;
+ }
+ }
+ assertTrue("Should have found the recpient to in the mail: " + name, found);
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("pop3://route-test-james@localhost?consumer.delay=1000")
+ .to("direct:a");
+
+ // must use fixed to option to send the mail to the given reciever, as we have polled
+ // a mail from a mailbox where it already has the 'old' To as header value
+ // here we send the mail to 2 recievers. notice we can use a plain string with semi colon
+ // to seperate the mail addresses
+ from("direct:a")
+ .setHeader("to", constant("route-test-result@localhost; route-test-copy@localhost"))
+ .to("smtp://localhost");
+
+ from("pop3://route-test-result@localhost?consumer.delay=1000")
+ .convertBodyTo(String.class).to("mock:result");
+ }
+ };
+ }
+
+ @Configuration
+ public static Option[] configure() {
+ Option[] options = options(
+ // install log service using pax runners profile abstraction (there are more profiles, like DS)
+ logProfile().version("1.3.0"),
+ // install the spring dm profile
+ profile("spring.dm").version("1.2.0"),
+ // this is how you set the default log level when using pax logging (logProfile)
+ org.ops4j.pax.exam.CoreOptions.systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),
+
+ // using the features to install the camel components
+ scanFeatures(mavenBundle().groupId("org.apache.camel.karaf").
+ artifactId("features").versionAsInProject().type("xml/features"),
+ "camel-core", "camel-osgi", "camel-spring", "camel-test", "camel-mail"),
+
+ // Added the mock_java_mail bundle for testing
+ mavenBundle().groupId("org.apache.camel.tests").artifactId("org.apache.camel.tests.mock-javamail_1.7").versionAsInProject(),
+
+ felix());
+
+ return options;
+ }
+
+}
diff --git a/tests/camel-itest-osgi/src/test/resources/log4j.properties b/tests/camel-itest-osgi/src/test/resources/log4j.properties
index 58f8a8380214e..48315a605ba15 100644
--- a/tests/camel-itest-osgi/src/test/resources/log4j.properties
+++ b/tests/camel-itest-osgi/src/test/resources/log4j.properties
@@ -18,7 +18,7 @@
#
# The logging properties used during tests..
#
-log4j.rootLogger=INFO, stdout
+log4j.rootLogger=INFO, out
# Use the following line to turn on debug output for camel
#log4j.logger.org.apache.camel=DEBUG
|
471adaa458ed6768d199dab17d07a013bf65e693
|
arrayexpress$annotare2
|
Updated file upload; Added "preview" of context help tooltip functionality
|
p
|
https://github.com/arrayexpress/annotare2
|
diff --git a/app/web/src/main/java/com/google/gwt/user/client/ui/TooltipPopup.java b/app/web/src/main/java/com/google/gwt/user/client/ui/TooltipPopup.java
new file mode 100644
index 000000000..c44813bc1
--- /dev/null
+++ b/app/web/src/main/java/com/google/gwt/user/client/ui/TooltipPopup.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2009-2016 European Molecular Biology Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package com.google.gwt.user.client.ui;
+
+import com.google.gwt.core.client.Scheduler;
+import com.google.gwt.dom.client.Element;
+import com.google.gwt.event.dom.client.*;
+
+// http://martinivanov.net/2010/11/25/creating-a-speech-bubble-with-css3-and-without-additional-markup/
+// and http://mrcoles.com/blog/callout-box-css-border-triangles-cross-browser/
+
+public class TooltipPopup {
+
+ private final PopupPanel tooltipPanel;
+ private final HTML tooltipContents;
+
+ public TooltipPopup() {
+ tooltipPanel = createPanel();
+ tooltipContents = new HTML("<div/>");
+ tooltipPanel.setWidget(tooltipContents);
+ }
+
+ protected PopupPanel createPanel() {
+ PopupPanel p = new PopupPanel(true, false);
+ p.setStyleName("gwt-TooltipPopup");
+ PopupPanel.setStyleName(p.getContainerElement(), "callout");
+ p.setPreviewingAllNativeEvents(true);
+ p.setAnimationType(PopupPanel.AnimationType.ROLL_DOWN);
+ return p;
+ }
+
+ public void showTip(final Element element, String html) {
+ tooltipContents.setHTML(html + "<b class=\"border-notch notch\"></b><b class=\"notch\"></b>");
+
+ Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() {
+ public boolean execute() {
+ // Show the popup under the input element
+ tooltipPanel.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
+ public void setPosition(int offsetWidth, int offsetHeight) {
+ tooltipPanel.setPopupPosition(element.getAbsoluteLeft(),
+ element.getAbsoluteBottom());
+// tooltipPanel.getElement().getStyle().setProperty("minWidth",
+// (element.getAbsoluteRight() - element.getAbsoluteLeft())
+// + Style.Unit.PX.getType());
+ }
+ });
+ return false;
+ }
+ }, 500);
+
+ }
+
+ public void hideTip() {
+ tooltipPanel.hide();
+ }
+
+ private final static TooltipPopup popupInstance = new TooltipPopup();
+
+ public static void attachTooltip(HasAllFocusHandlers focusTarget, final Element elementTarget, final String html) {
+
+ focusTarget.addFocusHandler(new FocusHandler() {
+ @Override
+ public void onFocus(FocusEvent event) {
+ popupInstance.showTip(elementTarget, html);
+ }
+ });
+ focusTarget.addBlurHandler(new BlurHandler() {
+ @Override
+ public void onBlur(BlurEvent event) {
+ popupInstance.hideTip();
+ }
+ });
+ }
+}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/DataFilesService.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/DataFilesService.java
index 40da9c8ce..1413f3b92 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/DataFilesService.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/DataFilesService.java
@@ -20,10 +20,9 @@
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.DataFileRow;
-import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.HttpFileInfo;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.UploadedFileInfo;
import java.util.List;
-import java.util.Map;
@RemoteServiceRelativePath(DataFilesService.NAME)
public interface DataFilesService extends RemoteService {
@@ -34,7 +33,7 @@ public interface DataFilesService extends RemoteService {
String initSubmissionFtpDirectory(long submissionId) throws ResourceNotFoundException, NoPermissionException;
- Map<Integer, String> registerHttpFiles(long submissionId, List<HttpFileInfo> filesInfo) throws ResourceNotFoundException, NoPermissionException;
+ String registerUploadedFile(long submissionId, UploadedFileInfo fileInfo) throws ResourceNotFoundException, NoPermissionException;
String registerFtpFiles(long submissionId, List<String> filesInfo) throws ResourceNotFoundException, NoPermissionException;
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/DataFilesServiceAsync.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/DataFilesServiceAsync.java
index 67e4ac446..584e7e593 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/DataFilesServiceAsync.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/DataFilesServiceAsync.java
@@ -19,10 +19,9 @@
import com.google.gwt.user.client.rpc.AsyncCallback;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.DataFileRow;
-import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.HttpFileInfo;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.UploadedFileInfo;
import java.util.List;
-import java.util.Map;
public interface DataFilesServiceAsync {
@@ -30,7 +29,7 @@ public interface DataFilesServiceAsync {
void initSubmissionFtpDirectory(long submissionId, AsyncCallback<String> async);
- void registerHttpFiles(long submissionId, List<HttpFileInfo> filesInfo, AsyncCallback<Map<Integer, String>> async);
+ void registerUploadedFile(long submissionId, UploadedFileInfo fileInfo, AsyncCallback<String> async);
void registerFtpFiles(long submissionId, List<String> filesInfo, AsyncCallback<String> async);
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/proxy/DataFilesProxy.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/proxy/DataFilesProxy.java
index 03b7e35e3..0c6ba31ee 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/proxy/DataFilesProxy.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/proxy/DataFilesProxy.java
@@ -24,11 +24,10 @@
import uk.ac.ebi.fg.annotare2.web.gwt.common.client.rpc.AsyncCallbackWrapper;
import uk.ac.ebi.fg.annotare2.web.gwt.common.client.rpc.Updater;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.DataFileRow;
-import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.HttpFileInfo;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.UploadedFileInfo;
import java.util.ArrayList;
import java.util.List;
-import java.util.Map;
public class DataFilesProxy {
@@ -74,15 +73,15 @@ public void onSuccess(String result) {
}.wrap());
}
- public void registerHttpFiles(long submissionId, List<HttpFileInfo> filesInfo, final AsyncCallback<Map<Integer, String>> callback) {
- filesService.registerHttpFiles(submissionId, filesInfo, new AsyncCallbackWrapper<Map<Integer, String>>() {
+ public void registerHttpFile(long submissionId, UploadedFileInfo fileInfo, final AsyncCallback<String> callback) {
+ filesService.registerUploadedFile(submissionId, fileInfo, new AsyncCallbackWrapper<String>() {
@Override
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
@Override
- public void onSuccess(Map<Integer, String> result) {
+ public void onSuccess(String result) {
updater.update();
callback.onSuccess(result);
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadPanel.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadPanel.java
index 2aa7c446f..cab15df0c 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadPanel.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadPanel.java
@@ -19,7 +19,7 @@
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
-import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.HttpFileInfo;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.UploadedFileInfo;
import java.util.List;
import java.util.Map;
@@ -126,7 +126,7 @@ public void hide() {
}
public interface Presenter {
- void uploadFiles(List<HttpFileInfo> filesInfo, AsyncCallback<Map<Integer, String>> callback);
+ void uploadFiles(List<UploadedFileInfo> filesInfo, AsyncCallback<Map<Integer, String>> callback);
}
private String removeFakePath(String fileName) {
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadView.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadView.java
index 8cbaadf7d..063fd64e2 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadView.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadView.java
@@ -36,7 +36,7 @@ public interface DataFilesUploadView extends IsWidget {
void setApplicationProperties(ApplicationProperties properties);
- interface Presenter extends DataFilesUploadPanel.Presenter, FTPUploadDialog.Presenter, DataFileListPanel.Presenter {
+ interface Presenter extends UploadProgressPopupPanel.Presenter, FTPUploadDialog.Presenter, DataFileListPanel.Presenter {
void initSubmissionFtpDirectory(AsyncCallback<String> callback);
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadViewImpl.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadViewImpl.java
index c013e572f..daaceea5d 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadViewImpl.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/DataFilesUploadViewImpl.java
@@ -155,7 +155,7 @@ public void setExperimentType(ExperimentProfileType type) {
@Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
-// uploadPanel.setPresenter(presenter);
+ progressPanel.setPresenter(presenter);
fileListPanel.setPresenter(presenter);
// ftpUploadDialog.setPresenter(presenter);
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/UploadProgressPopupPanel.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/UploadProgressPopupPanel.java
index 92d3b03f9..5718c4614 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/UploadProgressPopupPanel.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/client/view/UploadProgressPopupPanel.java
@@ -18,11 +18,15 @@
package uk.ac.ebi.fg.annotare2.web.gwt.common.client.view;
import com.google.gwt.core.client.JsArray;
+import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
+import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.PopupPanel;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.client.rpc.ReportingAsyncCallback;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.UploadedFileInfo;
import uk.ac.ebi.fg.gwt.resumable.client.ResumableCallback;
import uk.ac.ebi.fg.gwt.resumable.client.ResumableFile;
import uk.ac.ebi.fg.gwt.resumable.client.ResumableFileCallback;
@@ -37,6 +41,8 @@ public class UploadProgressPopupPanel extends PopupPanel {
private final ResumableUploader uploader;
private final DivElement messageElement;
+ private Presenter presenter;
+
public UploadProgressPopupPanel(ResumableUploader uploader) {
super(false, true);
this.uploader = uploader;
@@ -81,6 +87,14 @@ private void updateMessage(String message) {
messageElement.setInnerHTML(message);
}
+ public void setPresenter(Presenter presenter) {
+ this.presenter = presenter;
+ }
+
+ public interface Presenter {
+ void uploadFile(UploadedFileInfo fileInfo, AsyncCallback<String> callback);
+ }
+
// private void scheduleAutoHide() {
// Timer timer = new Timer() {
// @Override
@@ -172,7 +186,7 @@ public UploaderFileCallback(UploadProgressPopupPanel panel) {
@Override
public void onFileAdded(ResumableUploader uploader, ResumableFile file) {
- logger.info("Added file " + file.getFileName() + ", size " + file.getFileSize());
+ logger.info("Added file " + file.getFileName() + ", size " + file.getSize());
uploader.upload();
}
@@ -187,8 +201,13 @@ public void onFileProgress(ResumableUploader uploader, ResumableFile file) {
}
@Override
- public void onFileSuccess(ResumableUploader uploader, ResumableFile file) {
- panel.updateMessage("Successfully sent " + file.getFileName());
+ public void onFileSuccess(ResumableUploader uploader, final ResumableFile file) {
+ panel.updateMessage("Successfully sent " + file.getFileName() + " " + file.getSize());
+ Scheduler.get().scheduleDeferred(
+ new SendUploadedFileInfoCommand(
+ new UploadedFileInfo(file.getFileName(), file.getSize())
+ )
+ );
}
@Override
@@ -201,4 +220,24 @@ public void onFileError(ResumableUploader uploader, ResumableFile file, String m
panel.updateMessage("Error sending " + file.getFileName());
}
}
+
+ private class SendUploadedFileInfoCommand implements Scheduler.ScheduledCommand {
+
+ private final UploadedFileInfo fileInfo;
+
+ public SendUploadedFileInfoCommand(UploadedFileInfo fileInfo) {
+ this.fileInfo = fileInfo;
+ }
+
+ @Override
+ public void execute() {
+ presenter.uploadFile(fileInfo,
+ new ReportingAsyncCallback<String>() {
+ @Override
+ public void onSuccess(String result) {
+ //
+ }
+ });
+ }
+ }
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/shared/exepriment/HttpFileInfo.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/shared/exepriment/UploadedFileInfo.java
similarity index 73%
rename from app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/shared/exepriment/HttpFileInfo.java
rename to app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/shared/exepriment/UploadedFileInfo.java
index 4d7b771f3..09e6ddcde 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/shared/exepriment/HttpFileInfo.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/common/shared/exepriment/UploadedFileInfo.java
@@ -18,27 +18,23 @@
import com.google.gwt.user.client.rpc.IsSerializable;
-public class HttpFileInfo implements IsSerializable {
-
- private String fieldName;
+public class UploadedFileInfo implements IsSerializable {
private String fileName;
+ private long fileSize;
@SuppressWarnings("unused")
- HttpFileInfo() {
+ UploadedFileInfo() {
/* used by GWT serialization */
}
- public HttpFileInfo(String fieldName, String fileName) {
- this.fieldName = fieldName;
+ public UploadedFileInfo(String fileName, long fileSize) {
this.fileName = fileName;
+ this.fileSize = fileSize;
}
- public String getFieldName() {
- return fieldName;
- }
-
- public String getFileName() {
- return fileName;
+ @Override
+ public String toString() {
+ return fileName + ":" + fileSize;
}
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/activity/experiment/DataUploadAndAssignmentActivity.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/activity/experiment/DataUploadAndAssignmentActivity.java
index 319ed03a4..1ebb3f89f 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/activity/experiment/DataUploadAndAssignmentActivity.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/activity/experiment/DataUploadAndAssignmentActivity.java
@@ -36,7 +36,7 @@
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.DataAssignmentColumn;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.DataAssignmentColumnsAndRows;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.DataFileRow;
-import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.HttpFileInfo;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.UploadedFileInfo;
import uk.ac.ebi.fg.annotare2.web.gwt.editor.client.event.CriticalUpdateEvent;
import uk.ac.ebi.fg.annotare2.web.gwt.editor.client.event.CriticalUpdateEventHandler;
import uk.ac.ebi.fg.annotare2.web.gwt.editor.client.event.DataFileRenamedEvent;
@@ -48,7 +48,6 @@
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import static com.google.common.collect.Collections2.transform;
@@ -197,8 +196,8 @@ public void initSubmissionFtpDirectory(AsyncCallback<String> callback) {
}
@Override
- public void uploadFiles(List<HttpFileInfo> filesInfo, AsyncCallback<Map<Integer, String>> callback) {
- filesService.registerHttpFiles(getSubmissionId(), filesInfo, callback);
+ public void uploadFile(UploadedFileInfo fileInfo, AsyncCallback<String> callback) {
+ filesService.registerHttpFile(getSubmissionId(), fileInfo, callback);
}
@Override
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/view/experiment/info/ExperimentDetailsViewImpl.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/view/experiment/info/ExperimentDetailsViewImpl.java
index 02dd321c2..1a613e555 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/view/experiment/info/ExperimentDetailsViewImpl.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/view/experiment/info/ExperimentDetailsViewImpl.java
@@ -86,11 +86,19 @@ interface Binder extends UiBinder<Widget, ExperimentDetailsViewImpl> {
@Inject
public ExperimentDetailsViewImpl() {
+
experimentalDesigns = new LinkedHashMap<>();
experimentalDesignList = new ListBox(true);
initWidget(Binder.BINDER.createAndBindUi(this));
+ TooltipPopup.attachTooltip(title, title.getElement(), "Provide an informative experiment title (max. 255 characters).<br/>" +
+ "E.g. \"RNA-seq of human breast cancer cell line MCF-7 treated with tamoxifen against untreated controls.\"");
+
+ TooltipPopup.attachTooltip(description, description.getElement(), "Describe the biological relevance and intent of the experiment.<br/>" +
+ "Include an overview of the experimental workflow. Avoid copy-and-pasting your manuscript's abstract.");
+
+
DateBox.DefaultFormat format = new DateBox.DefaultFormat(dateTimeFormat());
dateOfExperiment.setFormat(format);
dateOfExperiment.getElement().setPropertyString("placeholder", dateTimeFormatPlaceholder());
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/user/client/activity/ImportSubmissionActivity.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/user/client/activity/ImportSubmissionActivity.java
index a01348a4f..37ed03ff3 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/user/client/activity/ImportSubmissionActivity.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/user/client/activity/ImportSubmissionActivity.java
@@ -36,7 +36,7 @@
import uk.ac.ebi.fg.annotare2.web.gwt.common.client.rpc.ReportingAsyncCallback.FailureMessage;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.ValidationResult;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.DataFileRow;
-import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.HttpFileInfo;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.UploadedFileInfo;
import uk.ac.ebi.fg.annotare2.web.gwt.user.client.place.ImportSubmissionPlace;
import uk.ac.ebi.fg.annotare2.web.gwt.user.client.place.SubmissionListPlace;
import uk.ac.ebi.fg.annotare2.web.gwt.user.client.view.ImportSubmissionView;
@@ -44,7 +44,6 @@
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import static com.google.common.collect.Collections2.transform;
@@ -166,8 +165,8 @@ public void onSuccess(Void result) {
}
@Override
- public void uploadFiles(List<HttpFileInfo> filesInfo, AsyncCallback<Map<Integer, String>> callback) {
- dataFilesService.registerHttpFiles(submissionId, filesInfo, callback);
+ public void uploadFile(UploadedFileInfo fileInfo, AsyncCallback<String> callback) {
+ dataFilesService.registerHttpFile(submissionId, fileInfo, callback);
}
@Override
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/rpc/DataFilesServiceImpl.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/rpc/DataFilesServiceImpl.java
index 91a01ef22..cb795b6da 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/rpc/DataFilesServiceImpl.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/rpc/DataFilesServiceImpl.java
@@ -33,7 +33,7 @@
import uk.ac.ebi.fg.annotare2.web.gwt.common.client.ResourceNotFoundException;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.DataFileRow;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.FtpFileInfo;
-import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.HttpFileInfo;
+import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.exepriment.UploadedFileInfo;
import uk.ac.ebi.fg.annotare2.web.server.properties.AnnotareProperties;
import uk.ac.ebi.fg.annotare2.web.server.services.*;
import uk.ac.ebi.fg.annotare2.web.server.services.files.DataFileSource;
@@ -121,11 +121,11 @@ public String initSubmissionFtpDirectory(long submissionId)
@Transactional(rollbackOn = {NoPermissionException.class, ResourceNotFoundException.class})
@Override
- public Map<Integer, String> registerHttpFiles(long submissionId, List<HttpFileInfo> filesInfo)
+ public String registerUploadedFile(long submissionId, UploadedFileInfo fileInfo)
throws ResourceNotFoundException, NoPermissionException {
try {
Submission submission = getSubmission(submissionId, Permission.UPDATE);
- HashMap<Integer, String> errors = new HashMap<>();
+ String result = "";
// int index = 0;
// for (HttpFileInfo info : filesInfo) {
// File uploadedFile = new File(properties.getHttpUploadDir(), info.getFileName());
@@ -141,7 +141,7 @@ public Map<Integer, String> registerHttpFiles(long submissionId, List<HttpFileIn
// index++;
// }
// UploadedFiles.removeSessionFiles(getSession());
- return errors;
+ return result;
} catch (Exception e) {
throw unexpected(e);
}
diff --git a/app/web/src/main/resources/uk/ac/ebi/fg/annotare2/web/gwt/common/public/CommonApp.css b/app/web/src/main/resources/uk/ac/ebi/fg/annotare2/web/gwt/common/public/CommonApp.css
index 7c117b614..3da45ed6f 100644
--- a/app/web/src/main/resources/uk/ac/ebi/fg/annotare2/web/gwt/common/public/CommonApp.css
+++ b/app/web/src/main/resources/uk/ac/ebi/fg/annotare2/web/gwt/common/public/CommonApp.css
@@ -163,6 +163,42 @@
background: rgba(0,0,0,0.3);
}
+.gwt-TooltipPopup .callout {
+ position: relative;
+ margin: 18px 0;
+ padding: 18px 20px;
+ color: black;
+ background-color: #eef4f9;
+ /* easy rounded corners for modern browsers */
+ -moz-border-radius: 6px;
+ -webkit-border-radius: 6px;
+ border-radius: 6px;
+}
+
+.gwt-TooltipPopup .callout .notch {
+ position: absolute;
+ top: -10px;
+ left: 20px;
+ margin: 0;
+ border-top: 0;
+ border-left: 10px solid transparent;
+ border-right: 10px solid transparent;
+ border-bottom: 10px solid #eef4f9;
+ padding: 0;
+ width: 0;
+ height: 0;
+ /* ie6 height fix */
+ font-size: 0;
+ line-height: 0;
+ /* ie6 transparent fix */
+ _border-right-color: pink;
+ _border-left-color: pink;
+ _filter: chroma(color=pink);
+}
+
+.gwt-TooltipPopup .callout { border: 1px solid #c5d9e8; padding: 17px 19px; }
+.gwt-TooltipPopup .callout .border-notch { border-bottom-color: #c5d9e8; top: -11px; }
+
.gwt-NotificationPopup {
max-width: 40%;
background-color: white;
|
630620ee581f7fbe07b95ec8cce030e56108cbdf
|
restlet-framework-java
|
- Continued SIP transaction support--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/internal/SipClientOutboundWay.java b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/internal/SipClientOutboundWay.java
index 89e7bcb763..8518e34707 100644
--- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/internal/SipClientOutboundWay.java
+++ b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/internal/SipClientOutboundWay.java
@@ -36,6 +36,7 @@
import org.restlet.engine.connector.Connection;
import org.restlet.engine.header.HeaderConstants;
import org.restlet.engine.header.TagWriter;
+import org.restlet.engine.io.IoState;
import org.restlet.ext.sip.SipRecipientInfo;
import org.restlet.ext.sip.SipRequest;
import org.restlet.util.Series;
@@ -212,8 +213,16 @@ protected void addRequestHeaders(Series<Parameter> headers) {
@Override
protected void handle(Response response) {
- // TODO Auto-generated method stub
+ setMessage(response);
+ }
+
+ @Override
+ public void updateState() {
+ if (getMessage() != null) {
+ setIoState(IoState.INTEREST);
+ }
+ super.updateState();
}
}
|
a40c1ef1aebb6263f4f32c6d36a8c12be6423338
|
tapiji
|
Adds missing resources to translator plug-in.
|
c
|
https://github.com/tapiji/tapiji
|
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
new file mode 100644
index 00000000..fe5188e1
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java
@@ -0,0 +1,78 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+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
new file mode 100644
index 00000000..e7aa31fc
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator;
+
+import org.eclipse.equinox.app.IApplication;
+import org.eclipse.equinox.app.IApplicationContext;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ * This class controls all aspects of the application's execution
+ */
+public class Application implements IApplication {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.
+ * IApplicationContext)
+ */
+ public Object start(IApplicationContext context) {
+ Display display = PlatformUI.createDisplay();
+ try {
+ int returnCode = PlatformUI.createAndRunWorkbench(display,
+ new ApplicationWorkbenchAdvisor());
+ if (returnCode == PlatformUI.RETURN_RESTART) {
+ return IApplication.EXIT_RESTART;
+ }
+ return IApplication.EXIT_OK;
+ } finally {
+ display.dispose();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.equinox.app.IApplication#stop()
+ */
+ public void stop() {
+ if (!PlatformUI.isWorkbenchRunning())
+ return;
+ final IWorkbench workbench = PlatformUI.getWorkbench();
+ final Display display = workbench.getDisplay();
+ display.syncExec(new Runnable() {
+ public void run() {
+ if (!display.isDisposed())
+ workbench.close();
+ }
+ });
+ }
+}
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
new file mode 100644
index 00000000..ee1cda38
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java
@@ -0,0 +1,124 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator;
+
+import org.eclipse.jface.action.GroupMarker;
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.action.ICoolBarManager;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.action.MenuManager;
+import org.eclipse.jface.action.Separator;
+import org.eclipse.jface.action.ToolBarContributionItem;
+import org.eclipse.jface.action.ToolBarManager;
+import org.eclipse.ui.IWorkbenchActionConstants;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.actions.ActionFactory;
+import org.eclipse.ui.actions.ContributionItemFactory;
+import org.eclipse.ui.application.ActionBarAdvisor;
+import org.eclipse.ui.application.IActionBarConfigurer;
+
+/**
+ * An action bar advisor is responsible for creating, adding, and disposing of
+ * the actions added to a workbench window. Each window will be populated with
+ * new actions.
+ */
+public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
+
+ public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
+ super(configurer);
+ }
+
+ @Override
+ protected void fillCoolBar(ICoolBarManager coolBar) {
+ super.fillCoolBar(coolBar);
+
+ coolBar.add(new GroupMarker("group.file"));
+ {
+ // File Group
+ IToolBarManager fileToolBar = new ToolBarManager(coolBar.getStyle());
+
+ fileToolBar.add(new Separator(IWorkbenchActionConstants.NEW_GROUP));
+ fileToolBar
+ .add(new GroupMarker(IWorkbenchActionConstants.OPEN_EXT));
+
+ fileToolBar.add(new GroupMarker(
+ IWorkbenchActionConstants.SAVE_GROUP));
+ fileToolBar.add(getAction(ActionFactory.SAVE.getId()));
+
+ // Add to the cool bar manager
+ coolBar.add(new ToolBarContributionItem(fileToolBar,
+ IWorkbenchActionConstants.TOOLBAR_FILE));
+ }
+
+ coolBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
+ coolBar.add(new GroupMarker(IWorkbenchActionConstants.GROUP_EDITOR));
+ }
+
+ @Override
+ protected void fillMenuBar(IMenuManager menuBar) {
+ super.fillMenuBar(menuBar);
+
+ menuBar.add(fileMenu());
+ menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
+ menuBar.add(helpMenu());
+ }
+
+ private MenuManager helpMenu() {
+ MenuManager helpMenu = new MenuManager("&Help",
+ IWorkbenchActionConstants.M_HELP);
+
+ helpMenu.add(getAction(ActionFactory.ABOUT.getId()));
+
+ return helpMenu;
+ }
+
+ private MenuManager fileMenu() {
+ MenuManager menu = new MenuManager("&File", "file_mnu");
+ menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_START));
+
+ menu.add(getAction(ActionFactory.CLOSE.getId()));
+ menu.add(getAction(ActionFactory.CLOSE_ALL.getId()));
+
+ menu.add(new GroupMarker(IWorkbenchActionConstants.CLOSE_EXT));
+ menu.add(new Separator());
+ menu.add(getAction(ActionFactory.SAVE.getId()));
+ menu.add(getAction(ActionFactory.SAVE_ALL.getId()));
+
+ menu.add(ContributionItemFactory.REOPEN_EDITORS
+ .create(getActionBarConfigurer().getWindowConfigurer()
+ .getWindow()));
+ menu.add(new GroupMarker(IWorkbenchActionConstants.MRU));
+ menu.add(new Separator());
+ menu.add(getAction(ActionFactory.QUIT.getId()));
+ return menu;
+ }
+
+ @Override
+ protected void makeActions(IWorkbenchWindow window) {
+ super.makeActions(window);
+
+ registerAsGlobal(ActionFactory.SAVE.create(window));
+ registerAsGlobal(ActionFactory.SAVE_AS.create(window));
+ registerAsGlobal(ActionFactory.SAVE_ALL.create(window));
+ registerAsGlobal(ActionFactory.CLOSE.create(window));
+ registerAsGlobal(ActionFactory.CLOSE_ALL.create(window));
+ registerAsGlobal(ActionFactory.CLOSE_ALL_SAVED.create(window));
+ registerAsGlobal(ActionFactory.ABOUT.create(window));
+ registerAsGlobal(ActionFactory.QUIT.create(window));
+ }
+
+ private void registerAsGlobal(IAction action) {
+ getActionBarConfigurer().registerGlobalAction(action);
+ register(action);
+ }
+
+}
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
new file mode 100644
index 00000000..5a897172
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator;
+
+import org.eclipse.ui.application.IWorkbenchConfigurer;
+import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
+import org.eclipse.ui.application.WorkbenchAdvisor;
+import org.eclipse.ui.application.WorkbenchWindowAdvisor;
+
+public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
+
+ private static final String PERSPECTIVE_ID = "org.eclipselabs.tapiji.translator.perspective";
+
+ public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
+ IWorkbenchWindowConfigurer configurer) {
+ return new ApplicationWorkbenchWindowAdvisor(configurer);
+ }
+
+ public String getInitialWindowPerspectiveId() {
+ return PERSPECTIVE_ID;
+ }
+
+ @Override
+ public void initialize(IWorkbenchConfigurer configurer) {
+ super.initialize(configurer);
+ configurer.setSaveAndRestore(true);
+ }
+
+}
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
new file mode 100644
index 00000000..93cb05f9
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java
@@ -0,0 +1,189 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ShellAdapter;
+import org.eclipse.swt.events.ShellEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Tray;
+import org.eclipse.swt.widgets.TrayItem;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.application.ActionBarAdvisor;
+import org.eclipse.ui.application.IActionBarConfigurer;
+import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
+import org.eclipse.ui.application.WorkbenchWindowAdvisor;
+import org.eclipse.ui.handlers.IHandlerService;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.eclipselabs.tapiji.translator.utils.FileUtils;
+
+public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
+
+ /** Workbench state **/
+ private IWorkbenchWindow window;
+
+ /** System tray item / icon **/
+ private TrayItem trayItem;
+ private Image trayImage;
+
+ /** Command ids **/
+ private final static String COMMAND_ABOUT_ID = "org.eclipse.ui.help.aboutAction";
+ private final static String COMMAND_EXIT_ID = "org.eclipse.ui.file.exit";
+
+ public ApplicationWorkbenchWindowAdvisor(
+ IWorkbenchWindowConfigurer configurer) {
+ super(configurer);
+ }
+
+ public ActionBarAdvisor createActionBarAdvisor(
+ IActionBarConfigurer configurer) {
+ return new ApplicationActionBarAdvisor(configurer);
+ }
+
+ public void preWindowOpen() {
+ IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
+ configurer.setShowFastViewBars(true);
+ configurer.setShowCoolBar(true);
+ configurer.setShowStatusLine(true);
+ configurer.setInitialSize(new Point(1024, 768));
+
+ /** Init workspace and container project */
+ try {
+ FileUtils.getProject();
+ } catch (CoreException e) {
+ }
+ }
+
+ @Override
+ public void postWindowOpen() {
+ super.postWindowOpen();
+ window = getWindowConfigurer().getWindow();
+
+ /** Add the application into the system tray icon section **/
+ trayItem = initTrayItem(window);
+
+ // If tray items are not supported by the operating system
+ if (trayItem != null) {
+
+ // minimize / maximize action
+ window.getShell().addShellListener(new ShellAdapter() {
+ public void shellIconified(ShellEvent e) {
+ window.getShell().setMinimized(true);
+ window.getShell().setVisible(false);
+ }
+ });
+
+ trayItem.addListener(SWT.DefaultSelection, new Listener() {
+ public void handleEvent(Event event) {
+ Shell shell = window.getShell();
+ if (!shell.isVisible() || window.getShell().getMinimized()) {
+ window.getShell().setMinimized(false);
+ shell.setVisible(true);
+ }
+ }
+ });
+
+ // Add actions menu
+ hookActionsMenu();
+ }
+ }
+
+ private void hookActionsMenu() {
+ trayItem.addListener(SWT.MenuDetect, new Listener() {
+ @Override
+ 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.addListener(SWT.Selection, new Listener() {
+
+ @Override
+ public void handleEvent(Event event) {
+ try {
+ IHandlerService handlerService = (IHandlerService) window
+ .getService(IHandlerService.class);
+ handlerService.executeCommand(COMMAND_ABOUT_ID,
+ null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ });
+
+ MenuItem sep = new MenuItem(menu, SWT.SEPARATOR);
+
+ // Add exit action
+ MenuItem exit = new MenuItem(menu, SWT.NONE);
+ exit.setText("Exit");
+ exit.addListener(SWT.Selection, new Listener() {
+ @Override
+ public void handleEvent(Event event) {
+ // Perform a call to the exit command
+ IHandlerService handlerService = (IHandlerService) window
+ .getService(IHandlerService.class);
+ try {
+ handlerService
+ .executeCommand(COMMAND_EXIT_ID, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ });
+
+ menu.setVisible(true);
+ }
+ });
+ }
+
+ private TrayItem initTrayItem(IWorkbenchWindow window) {
+ final Tray osTray = window.getShell().getDisplay().getSystemTray();
+ TrayItem item = new TrayItem(osTray, SWT.None);
+
+ trayImage = AbstractUIPlugin.imageDescriptorFromPlugin(
+ Activator.PLUGIN_ID, "/icons/TapiJI_32.png").createImage();
+ item.setImage(trayImage);
+ item.setToolTipText("TapiJI - Translator");
+
+ return item;
+ }
+
+ @Override
+ public void dispose() {
+ try {
+ super.dispose();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ try {
+ if (trayImage != null)
+ trayImage.dispose();
+ if (trayItem != null)
+ trayItem.dispose();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void postWindowClose() {
+ super.postWindowClose();
+ }
+}
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
new file mode 100644
index 00000000..910e91fe
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java
@@ -0,0 +1,36 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+package org.eclipselabs.tapiji.translator;
+
+import org.eclipse.ui.IPageLayout;
+import org.eclipse.ui.IPerspectiveFactory;
+import org.eclipselabs.tapiji.translator.views.GlossaryView;
+
+public class Perspective implements IPerspectiveFactory {
+
+ public void createInitialLayout(IPageLayout layout) {
+ layout.setEditorAreaVisible(true);
+ layout.setFixed(true);
+
+ initEditorArea(layout);
+ initViewsArea(layout);
+ }
+
+ private void initViewsArea(IPageLayout layout) {
+ layout.addStandaloneView(GlossaryView.ID, false, IPageLayout.BOTTOM,
+ .6f, IPageLayout.ID_EDITOR_AREA);
+ }
+
+ private void initEditorArea(IPageLayout layout) {
+
+ }
+
+}
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
new file mode 100644
index 00000000..6c8fcec8
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+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
new file mode 100644
index 00000000..aa5f64f4
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java
@@ -0,0 +1,55 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+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/widgets/GlossaryWidget.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
new file mode 100644
index 00000000..4c0c0b47
--- /dev/null
+++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java
@@ -0,0 +1,656 @@
+/*******************************************************************************
+ * 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
+ *
+ * Contributors:
+ * Martin Reiterer - initial API and implementation
+ ******************************************************************************/
+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();
+ }
+
+}
|
4617ba5d93275cafb34b8208ccea60b76576c191
|
Vala
|
gdk-2.0: Fix types of several Gdk.Event*.state fields
Fixes bug 607337.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gdk-2.0.vapi b/vapi/gdk-2.0.vapi
index 08cfcf8b4c..e143cbeea2 100644
--- a/vapi/gdk-2.0.vapi
+++ b/vapi/gdk-2.0.vapi
@@ -638,7 +638,7 @@ namespace Gdk {
public double x;
public double y;
public double axes;
- public uint state;
+ public Gdk.ModifierType state;
public uint button;
public weak Gdk.Device device;
public double x_root;
@@ -677,7 +677,7 @@ namespace Gdk {
public Gdk.CrossingMode mode;
public Gdk.NotifyType detail;
public bool focus;
- public uint state;
+ public Gdk.ModifierType state;
}
[CCode (type_id = "GDK_TYPE_EVENT_DND", cheader_filename = "gdk/gdk.h")]
public struct EventDND {
@@ -720,7 +720,7 @@ namespace Gdk {
public weak Gdk.Window window;
public char send_event;
public uint32 time;
- public uint state;
+ public Gdk.ModifierType state;
public uint keyval;
public int length;
[CCode (cname = "string")]
@@ -768,7 +768,7 @@ namespace Gdk {
public char send_event;
public Gdk.Atom atom;
public uint32 time;
- public uint state;
+ public Gdk.PropertyState state;
}
[CCode (type_id = "GDK_TYPE_EVENT_PROXIMITY", cheader_filename = "gdk/gdk.h")]
public struct EventProximity {
@@ -786,7 +786,7 @@ namespace Gdk {
public uint32 time;
public double x;
public double y;
- public uint state;
+ public Gdk.ModifierType state;
public Gdk.ScrollDirection direction;
public weak Gdk.Device device;
public double x_root;
diff --git a/vapi/packages/gdk-2.0/gdk-2.0.metadata b/vapi/packages/gdk-2.0/gdk-2.0.metadata
index 513a81ded6..6e29aadd55 100644
--- a/vapi/packages/gdk-2.0/gdk-2.0.metadata
+++ b/vapi/packages/gdk-2.0/gdk-2.0.metadata
@@ -35,8 +35,13 @@ gdk_draw_rgb*_image*.buf no_array_length="1"
gdk_draw_rgb*_image*.rgb_buf no_array_length="1"
GdkEvent is_value_type="0"
GdkEvent* is_value_type="1"
+GdkEventButton.state type_name="ModifierType"
+GdkEventCrossing.state type_name="ModifierType"
+GdkEventKey.state type_name="ModifierType"
GdkEventMotion.is_hint type_name="bool"
GdkEventMotion.state type_name="ModifierType"
+GdkEventProperty.state type_name="PropertyState"
+GdkEventScroll.state type_name="ModifierType"
gdk_event_copy transfer_ownership="1"
gdk_event_get_state.state is_out="1"
gdk_event_get_axis.value is_out="1"
|
218ee6d24c991f841ee91085c2bb26d6198db8c6
|
spring-framework
|
added "boolean isRegisteredWithDestination()"- method (SPR-7065)--
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java
index 3f608f086723..6ba4154e117c 100644
--- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java
+++ b/org.springframework.jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java
@@ -178,6 +178,8 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe
private int activeInvokerCount = 0;
+ private int registeredWithDestination = 0;
+
private Runnable stopCallback;
private Object currentRecoveryMarker = new Object();
@@ -577,6 +579,27 @@ public final int getActiveConsumerCount() {
}
}
+ /**
+ * Return whether at lease one consumer has entered a fixed registration with the
+ * target destination. This is particularly interesting for the pub-sub case where
+ * it might be important to have an actual consumer registered that is guaranteed
+ * to not miss any messages that are just about to be published.
+ * <p>This method may be polled after a {@link #start()} call, until asynchronous
+ * registration of consumers has happened which is when the method will start returning
+ * <code>true</code> - provided that the listener container actually ever establishes
+ * a fixed registration. It will then keep returning <code>true</code> until shutdown,
+ * since the container will hold on to at least one consumer registration thereafter.
+ * <p>Note that a listener container is not bound to having a fixed registration in
+ * the first place. It may also keep recreating consumers for every invoker execution.
+ * This particularly depends on the {@link #setCacheLevel cache level} setting:
+ * Only CACHE_CONSUMER will lead to a fixed registration.
+ */
+ public boolean isRegisteredWithDestination() {
+ synchronized (this.lifecycleMonitor) {
+ return (this.registeredWithDestination > 0);
+ }
+ }
+
/**
* Create a default TaskExecutor. Called if no explicit TaskExecutor has been specified.
@@ -1026,6 +1049,9 @@ private void initResourcesIfNecessary() throws JMSException {
}
if (this.consumer == null && getCacheLevel() >= CACHE_CONSUMER) {
this.consumer = createListenerConsumer(this.session);
+ synchronized (lifecycleMonitor) {
+ registeredWithDestination++;
+ }
}
}
}
@@ -1047,6 +1073,11 @@ private void clearResources() {
JmsUtils.closeMessageConsumer(this.consumer);
JmsUtils.closeSession(this.session);
}
+ if (this.consumer != null) {
+ synchronized (lifecycleMonitor) {
+ registeredWithDestination--;
+ }
+ }
this.consumer = null;
this.session = null;
}
|
7ccd3abb7942553d5b1dc6c6c18cdbe9d6ecc129
|
intellij-community
|
fix indefinite loop (IDEA-67750)--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java
index 3c5b1ca1cc100..6ba74f07083f4 100644
--- a/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java
+++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java
@@ -251,11 +251,13 @@ public String getCurrentLine() {
}
public String getNextLine() {
- final int next = myIndex + 1;
- if (next >= javacMessages.size()) {
+ final int size = javacMessages.size();
+ final int next = Math.min(myIndex + 1, javacMessages.size());
+ myIndex = next;
+ if (next >= size) {
return null;
}
- return javacMessages.get(myIndex = next);
+ return javacMessages.get(next);
}
@Override
|
af1d3891570f23ef391c4b7aed3f6dedbcf9277b
|
hadoop
|
YARN-2519. Credential Provider related unit tests- failed on Windows. Contributed by Xiaoyu Yao.--(cherry picked from commit cbea1b10efd871d04c648af18449dc724685db74)-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index cf9fe6e6f793c..83274b65b7236 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -264,6 +264,9 @@ Release 2.6.0 - UNRELEASED
YARN-2431. NM restart: cgroup is not removed for reacquired containers
(jlowe)
+ YARN-2519. Credential Provider related unit tests failed on Windows.
+ (Xiaoyu Yao via cnauroth)
+
Release 2.5.1 - UNRELEASED
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/util/TestWebAppUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/util/TestWebAppUtils.java
index 18600fdea6886..2bd91b4ac6d37 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/util/TestWebAppUtils.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/util/TestWebAppUtils.java
@@ -24,6 +24,7 @@
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
import org.apache.hadoop.http.HttpServer2;
import org.apache.hadoop.http.HttpServer2.Builder;
import org.apache.hadoop.security.alias.CredentialProvider;
@@ -74,8 +75,9 @@ protected Configuration provisionCredentialsForSSL() throws IOException,
"target/test-dir"));
Configuration conf = new Configuration();
+ final Path jksPath = new Path(testDir.toString(), "test.jks");
final String ourUrl =
- JavaKeyStoreProvider.SCHEME_NAME + "://file/" + testDir + "/test.jks";
+ JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri();
File file = new File(testDir, "test.jks");
file.delete();
|
ff7d4eebd8ebbf011656313dca8c6ee1a598c2aa
|
spring-framework
|
Polish AbstractHandlerMethodMapping---
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
index c463ee1fcb85..367dcb765bf7 100644
--- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
+++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
@@ -390,10 +390,15 @@ protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpSer
/**
* Retrieve the CORS configuration for the given handler.
+ * @param handler the handler to check (never {@code null}).
+ * @param request the current request.
+ * @return the CORS configuration for the handler or {@code null}.
*/
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
- handler = (handler instanceof HandlerExecutionChain) ? ((HandlerExecutionChain) handler).getHandler() : handler;
- if (handler != null && handler instanceof CorsConfigurationSource) {
+ if (handler instanceof HandlerExecutionChain) {
+ handler = ((HandlerExecutionChain) handler).getHandler();
+ }
+ if (handler instanceof CorsConfigurationSource) {
return ((CorsConfigurationSource) handler).getCorsConfiguration(request);
}
return null;
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
index 9a36308ce00d..4fc653eb8b7a 100644
--- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
+++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
@@ -83,7 +83,7 @@ public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMap
private final MultiValueMap<String, HandlerMethod> nameMap = new LinkedMultiValueMap<String, HandlerMethod>();
- private final Map<Method, CorsConfiguration> corsConfigurations = new LinkedHashMap<Method, CorsConfiguration>();
+ private final Map<Method, CorsConfiguration> corsMap = new LinkedHashMap<Method, CorsConfiguration>();
/**
@@ -113,20 +113,6 @@ public Map<T, HandlerMethod> getHandlerMethods() {
return Collections.unmodifiableMap(this.handlerMethods);
}
- protected Map<Method, CorsConfiguration> getCorsConfigurations() {
- return corsConfigurations;
- }
-
- @Override
- protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
- CorsConfiguration config = super.getCorsConfiguration(handler, request);
- if (config == null && handler instanceof HandlerMethod) {
- HandlerMethod handlerMethod = (HandlerMethod)handler;
- config = this.getCorsConfigurations().get(handlerMethod.getMethod());
- }
- return config;
- }
-
/**
* Return the handler methods mapped to the mapping with the given name.
* @param mappingName the mapping name
@@ -159,10 +145,9 @@ protected void initHandlerMethods() {
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class));
- for (String beanName : beanNames) {
- if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX) &&
- isHandler(getApplicationContext().getType(beanName))){
- detectHandlerMethods(beanName);
+ for (String name : beanNames) {
+ if (!name.startsWith(SCOPED_TARGET_NAME_PREFIX) && isHandler(getApplicationContext().getType(name))) {
+ detectHandlerMethods(name);
}
}
registerMultiMatchCorsConfiguration();
@@ -175,7 +160,7 @@ private void registerMultiMatchCorsConfiguration() {
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);
- this.corsConfigurations.put(PREFLIGHT_MULTI_MATCH_HANDLER_METHOD.getMethod(), config);
+ this.corsMap.put(PREFLIGHT_MULTI_MATCH_HANDLER_METHOD.getMethod(), config);
}
/**
@@ -262,7 +247,7 @@ protected void registerHandlerMethod(Object handler, Method method, T mapping) {
CorsConfiguration config = initCorsConfiguration(handler, method, mapping);
if (config != null) {
- this.corsConfigurations.put(method, config);
+ this.corsMap.put(method, config);
}
}
@@ -442,6 +427,14 @@ protected HandlerMethod handleNoMatch(Set<T> mappings, String lookupPath, HttpSe
return null;
}
+ @Override
+ protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
+ if (handler instanceof HandlerMethod) {
+ this.corsMap.get(((HandlerMethod) handler).getMethod());
+ }
+ return null;
+ }
+
/**
* A thin wrapper around a matched HandlerMethod and its mapping, for the purpose of
|
9a987307f7158dcdfc6ffa23a2adda444dc00c8a
|
Vala
|
libsoup-2.4: nullability fixes for Soup.MessageHeaders methods
Fixes bug 604907.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/libsoup-2.4.vapi b/vapi/libsoup-2.4.vapi
index 64d2c4ca75..ed282cad9a 100644
--- a/vapi/libsoup-2.4.vapi
+++ b/vapi/libsoup-2.4.vapi
@@ -290,10 +290,10 @@ namespace Soup {
public void @foreach (Soup.MessageHeadersForeachFunc func);
public void free_ranges (Soup.Range ranges);
public unowned string @get (string name);
- public bool get_content_disposition (out string disposition, out GLib.HashTable @params);
+ public bool get_content_disposition (out string disposition, out GLib.HashTable? @params);
public int64 get_content_length ();
public bool get_content_range (int64 start, int64 end, int64 total_length);
- public unowned string get_content_type (out GLib.HashTable @params);
+ public unowned string get_content_type (out GLib.HashTable? @params);
public Soup.Encoding get_encoding ();
public Soup.Expectation get_expectations ();
public bool get_ranges (int64 total_length, out unowned Soup.Range ranges, int length);
diff --git a/vapi/packages/libsoup-2.4/libsoup-2.4.metadata b/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
index 00a69cd525..a9fc405c6c 100644
--- a/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
+++ b/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
@@ -20,8 +20,8 @@ SoupMessage::wrote_chunk has_emitter="1"
SoupMessage::wrote_headers has_emitter="1"
SoupMessage::wrote_informational has_emitter="1"
soup_message_headers_get_content_disposition.disposition transfer_ownership="1"
-soup_message_headers_get_content_disposition.params is_out="1" transfer_ownership="1"
-soup_message_headers_get_content_type.params is_out="1" transfer_ownership="1"
+soup_message_headers_get_content_disposition.params is_out="1" transfer_ownership="1" nullable="1"
+soup_message_headers_get_content_type.params is_out="1" transfer_ownership="1" nullable="1"
SoupMessageBody.data type_name="uint8" is_array="1"
soup_server_new ellipsis="1"
soup_server_add_handler.destroy hidden="1"
|
4cfc90590c1e54c88fc5a683b061258dd897da49
|
hadoop
|
YARN-2065 AM cannot create new containers after- restart--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1607440 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 872997c372050..f223854b88fc6 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -303,6 +303,9 @@ Release 2.5.0 - UNRELEASED
YARN-2216 TestRMApplicationHistoryWriter sometimes fails in trunk.
(Zhijie Shen via xgong)
+ YARN-2216 YARN-2065 AM cannot create new containers after restart
+ (Jian He via stevel)
+
Release 2.4.1 - 2014-06-23
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java
index ded2013bfc90b..1e155d27b84c9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java
@@ -475,8 +475,8 @@ protected void authorizeStartRequest(NMTokenIdentifier nmTokenIdentifier,
boolean unauthorized = false;
StringBuilder messageBuilder =
new StringBuilder("Unauthorized request to start container. ");
- if (!nmTokenIdentifier.getApplicationAttemptId().equals(
- containerId.getApplicationAttemptId())) {
+ if (!nmTokenIdentifier.getApplicationAttemptId().getApplicationId().equals(
+ containerId.getApplicationAttemptId().getApplicationId())) {
unauthorized = true;
messageBuilder.append("\nNMToken for application attempt : ")
.append(nmTokenIdentifier.getApplicationAttemptId())
@@ -810,26 +810,24 @@ protected void authorizeGetAndStopContainerRequest(ContainerId containerId,
* belongs to the same application attempt (NMToken) which was used. (Note:-
* This will prevent user in knowing another application's containers).
*/
-
- if ((!identifier.getApplicationAttemptId().equals(
- containerId.getApplicationAttemptId()))
- || (container != null && !identifier.getApplicationAttemptId().equals(
- container.getContainerId().getApplicationAttemptId()))) {
+ ApplicationId nmTokenAppId =
+ identifier.getApplicationAttemptId().getApplicationId();
+ if ((!nmTokenAppId.equals(containerId.getApplicationAttemptId().getApplicationId()))
+ || (container != null && !nmTokenAppId.equals(container
+ .getContainerId().getApplicationAttemptId().getApplicationId()))) {
if (stopRequest) {
LOG.warn(identifier.getApplicationAttemptId()
+ " attempted to stop non-application container : "
- + container.getContainerId().toString());
+ + container.getContainerId());
NMAuditLogger.logFailure("UnknownUser", AuditConstants.STOP_CONTAINER,
"ContainerManagerImpl", "Trying to stop unknown container!",
- identifier.getApplicationAttemptId().getApplicationId(),
- container.getContainerId());
+ nmTokenAppId, container.getContainerId());
} else {
LOG.warn(identifier.getApplicationAttemptId()
+ " attempted to get status for non-application container : "
- + container.getContainerId().toString());
+ + container.getContainerId());
}
}
-
}
class ContainerEventDispatcher implements EventHandler<ContainerEvent> {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java
index d607079235cf0..6797165dfe09f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestContainerManagerSecurity.java
@@ -202,8 +202,6 @@ private void testNMTokens(Configuration conf) throws Exception {
ApplicationId appId = ApplicationId.newInstance(1, 1);
ApplicationAttemptId validAppAttemptId =
ApplicationAttemptId.newInstance(appId, 1);
- ApplicationAttemptId invalidAppAttemptId =
- ApplicationAttemptId.newInstance(appId, 2);
ContainerId validContainerId =
ContainerId.newInstance(validAppAttemptId, 0);
@@ -269,26 +267,14 @@ private void testNMTokens(Configuration conf) throws Exception {
testStartContainer(rpc, validAppAttemptId, validNode,
validContainerToken, invalidNMToken, true)));
- // using appAttempt-2 token for launching container for appAttempt-1.
- invalidNMToken =
- nmTokenSecretManagerRM.createNMToken(invalidAppAttemptId, validNode,
- user);
- sb = new StringBuilder("\nNMToken for application attempt : ");
- sb.append(invalidAppAttemptId.toString())
- .append(" was used for starting container with container token")
- .append(" issued for application attempt : ")
- .append(validAppAttemptId.toString());
- Assert.assertTrue(testStartContainer(rpc, validAppAttemptId, validNode,
- validContainerToken, invalidNMToken, true).contains(sb.toString()));
-
// using correct tokens. nmtoken for app attempt should get saved.
conf.setInt(YarnConfiguration.RM_CONTAINER_ALLOC_EXPIRY_INTERVAL_MS,
4 * 60 * 1000);
validContainerToken =
containerTokenSecretManager.createContainerToken(validContainerId,
validNode, user, r, Priority.newInstance(0), 0);
- testStartContainer(rpc, validAppAttemptId, validNode, validContainerToken,
- validNMToken, false);
+ Assert.assertTrue(testStartContainer(rpc, validAppAttemptId, validNode,
+ validContainerToken, validNMToken, false).isEmpty());
Assert.assertTrue(nmTokenSecretManagerNM
.isAppAttemptNMTokenKeyPresent(validAppAttemptId));
@@ -330,6 +316,18 @@ private void testNMTokens(Configuration conf) throws Exception {
Assert.assertTrue(testGetContainer(rpc, validAppAttemptId, validNode,
validContainerId, validNMToken, false).contains(sb.toString()));
+ // using appAttempt-1 NMtoken for launching container for appAttempt-2 should
+ // succeed.
+ ApplicationAttemptId attempt2 = ApplicationAttemptId.newInstance(appId, 2);
+ Token attempt1NMToken =
+ nmTokenSecretManagerRM
+ .createNMToken(validAppAttemptId, validNode, user);
+ org.apache.hadoop.yarn.api.records.Token newContainerToken =
+ containerTokenSecretManager.createContainerToken(
+ ContainerId.newInstance(attempt2, 1), validNode, user, r,
+ Priority.newInstance(0), 0);
+ Assert.assertTrue(testStartContainer(rpc, attempt2, validNode,
+ newContainerToken, attempt1NMToken, false).isEmpty());
}
private void waitForContainerToFinishOnNM(ContainerId containerId) {
|
81151dab07508e1657ddf252a11672c0b1868e7a
|
Valadoc
|
Improve {@inheritDoc}
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/content/blockcontent.vala b/src/libvaladoc/content/blockcontent.vala
index d3d8a984ab..54d9e567a4 100644
--- a/src/libvaladoc/content/blockcontent.vala
+++ b/src/libvaladoc/content/blockcontent.vala
@@ -37,6 +37,7 @@ public abstract class Valadoc.Content.BlockContent : ContentElement {
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
foreach (Block element in _content) {
+ element.parent = this;
element.check (api_root, container, file_path, reporter, settings);
}
}
diff --git a/src/libvaladoc/content/comment.vala b/src/libvaladoc/content/comment.vala
index 0c6f4496fe..6f036c0ba9 100644
--- a/src/libvaladoc/content/comment.vala
+++ b/src/libvaladoc/content/comment.vala
@@ -21,12 +21,14 @@
* Didier 'Ptitjes Villevalois <[email protected]>
*/
+using Valadoc.Taglets;
using Gee;
public class Valadoc.Content.Comment : BlockContent {
- public Gee.List<Taglet> taglets { get { return _taglets; } }
+ private Gee.LinkedList<InheritDoc> inheritdocs = new Gee.LinkedList<InheritDoc> ();
+ public Gee.List<Taglet> taglets { get { return _taglets; } }
private Gee.List<Taglet> _taglets;
internal Comment () {
@@ -34,6 +36,10 @@ public class Valadoc.Content.Comment : BlockContent {
_taglets = new ArrayList<Taglet> ();
}
+ internal void register_inheritdoc (InheritDoc taglet) {
+ inheritdocs.add (taglet);
+ }
+
public override void configure (Settings settings, ResourceLocator locator) {
}
@@ -41,8 +47,13 @@ public class Valadoc.Content.Comment : BlockContent {
base.check (api_root, container, file_path, reporter, settings);
foreach (Taglet element in _taglets) {
+ element.parent = this;
element.check (api_root, container, file_path, reporter, settings);
}
+
+ foreach (InheritDoc element in inheritdocs) {
+ element.transform (api_root, container, file_path, reporter, settings);
+ }
}
public override void accept (ContentVisitor visitor) {
@@ -70,5 +81,24 @@ public class Valadoc.Content.Comment : BlockContent {
return selected_taglets;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ assert (new_parent == null);
+
+ Comment comment = new Comment ();
+ comment.parent = new_parent;
+
+ foreach (Block element in content) {
+ Block copy = element.copy (comment) as Block;
+ comment.content.add (copy);
+ }
+
+ foreach (Taglet taglet in _taglets) {
+ Taglet copy = taglet.copy (comment) as Taglet;
+ comment.taglets.add (copy);
+ }
+
+ return comment;
+ }
}
diff --git a/src/libvaladoc/content/contentelement.vala b/src/libvaladoc/content/contentelement.vala
index be15e5bbdd..dbec72d103 100644
--- a/src/libvaladoc/content/contentelement.vala
+++ b/src/libvaladoc/content/contentelement.vala
@@ -25,6 +25,10 @@ using GLib;
public abstract class Valadoc.Content.ContentElement : Object {
+ public ContentElement parent { get; internal set; }
+
+ public abstract ContentElement copy (ContentElement? new_parent = null);
+
public virtual void configure (Settings settings, ResourceLocator locator) {
}
diff --git a/src/libvaladoc/content/embedded.vala b/src/libvaladoc/content/embedded.vala
index d287ca7ccf..bdfdbb6c3a 100644
--- a/src/libvaladoc/content/embedded.vala
+++ b/src/libvaladoc/content/embedded.vala
@@ -70,4 +70,19 @@ public class Valadoc.Content.Embedded : ContentElement, Inline, StyleAttributes
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Embedded embedded = new Embedded ();
+ embedded.parent = new_parent;
+
+ embedded.horizontal_align = horizontal_align;
+ embedded.vertical_align = vertical_align;
+ embedded._locator = _locator;
+ embedded.caption = caption;
+ embedded.package = package;
+ embedded.style = style;
+ embedded.url = url;
+
+ return embedded;
+ }
}
diff --git a/src/libvaladoc/content/headline.vala b/src/libvaladoc/content/headline.vala
index 36b19c23b0..3f7150c455 100644
--- a/src/libvaladoc/content/headline.vala
+++ b/src/libvaladoc/content/headline.vala
@@ -24,7 +24,7 @@
using Gee;
-public class Valadoc.Content.Headline : Block, InlineContent {
+public class Valadoc.Content.Headline : InlineContent, Block {
public int level { get; set; }
internal Headline () {
@@ -44,9 +44,21 @@ public class Valadoc.Content.Headline : Block, InlineContent {
visitor.visit_headline (this);
}
-
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Headline headline = new Headline ();
+ headline.parent = new_parent;
+ headline.level = level;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (headline) as Inline;
+ headline.content.add (copy);
+ }
+
+ return headline;
+ }
}
diff --git a/src/libvaladoc/content/inlinecontent.vala b/src/libvaladoc/content/inlinecontent.vala
index 119f0569d8..f3c47f1640 100644
--- a/src/libvaladoc/content/inlinecontent.vala
+++ b/src/libvaladoc/content/inlinecontent.vala
@@ -38,6 +38,7 @@ public abstract class Valadoc.Content.InlineContent : ContentElement {
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
foreach (Inline element in _content) {
+ element.parent = this;
element.check (api_root, container, file_path, reporter, settings);
}
}
diff --git a/src/libvaladoc/content/inlinetaglet.vala b/src/libvaladoc/content/inlinetaglet.vala
index 151395095f..6b7e81786c 100644
--- a/src/libvaladoc/content/inlinetaglet.vala
+++ b/src/libvaladoc/content/inlinetaglet.vala
@@ -51,6 +51,8 @@ public abstract class Valadoc.Content.InlineTaglet : ContentElement, Taglet, Inl
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
ContentElement element = get_content ();
+ element.parent = this;
+
element.check (api_root, container, file_path, reporter, settings);
}
diff --git a/src/libvaladoc/content/link.vala b/src/libvaladoc/content/link.vala
index e2648981ad..20fd095e99 100644
--- a/src/libvaladoc/content/link.vala
+++ b/src/libvaladoc/content/link.vala
@@ -35,6 +35,7 @@ public class Valadoc.Content.Link : InlineContent, Inline {
}
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ base.check (api_root, container, file_path, reporter, settings);
//TODO: check url
}
@@ -45,4 +46,17 @@ public class Valadoc.Content.Link : InlineContent, Inline {
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Link link = new Link ();
+ link.parent = new_parent;
+ link.url = url;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (link) as Inline;
+ link.content.add (copy);
+ }
+
+ return link;
+ }
}
diff --git a/src/libvaladoc/content/list.vala b/src/libvaladoc/content/list.vala
index e55489fe1e..0b04c03c79 100644
--- a/src/libvaladoc/content/list.vala
+++ b/src/libvaladoc/content/list.vala
@@ -112,6 +112,7 @@ public class Valadoc.Content.List : ContentElement, Block {
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
// Check individual list items
foreach (ListItem element in _items) {
+ element.parent = this;
element.check (api_root, container, file_path, reporter, settings);
}
}
@@ -129,4 +130,17 @@ public class Valadoc.Content.List : ContentElement, Block {
public override bool is_empty () {
return _items.size == 0;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Content.List list = new Content.List ();
+ list.parent = new_parent;
+ list.bullet = bullet;
+
+ foreach (ListItem item in items) {
+ ListItem copy = item.copy (list) as ListItem;
+ list.items.add (copy);
+ }
+
+ return list;
+ }
}
diff --git a/src/libvaladoc/content/listitem.vala b/src/libvaladoc/content/listitem.vala
index 98104b767b..00a112a894 100644
--- a/src/libvaladoc/content/listitem.vala
+++ b/src/libvaladoc/content/listitem.vala
@@ -42,4 +42,16 @@ public class Valadoc.Content.ListItem : BlockContent {
public override void accept_children (ContentVisitor visitor) {
base.accept_children (visitor);
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ ListItem item = new ListItem ();
+ item.parent = new_parent;
+
+ foreach (Block block in content) {
+ Block copy = block.copy (item) as Block;
+ item.content.add (copy);
+ }
+
+ return item;
+ }
}
diff --git a/src/libvaladoc/content/note.vala b/src/libvaladoc/content/note.vala
index 40bb930198..c8b24e47b4 100644
--- a/src/libvaladoc/content/note.vala
+++ b/src/libvaladoc/content/note.vala
@@ -37,5 +37,17 @@ public class Valadoc.Content.Note : BlockContent, Block {
public override void accept (ContentVisitor visitor) {
visitor.visit_note (this);
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Note note = new Note ();
+ note.parent = new_parent;
+
+ foreach (Block block in content) {
+ Block copy = block.copy (note) as Block;
+ note.content.add (copy);
+ }
+
+ return note;
+ }
}
diff --git a/src/libvaladoc/content/page.vala b/src/libvaladoc/content/page.vala
index c01bd88b9f..662ee89710 100644
--- a/src/libvaladoc/content/page.vala
+++ b/src/libvaladoc/content/page.vala
@@ -31,5 +31,19 @@ public class Valadoc.Content.Page : BlockContent {
public override void accept (ContentVisitor visitor) {
visitor.visit_page (this);
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ assert (new_parent == null);
+
+ Content.Page page = new Content.Page ();
+ page.parent = new_parent;
+
+ foreach (Block block in content) {
+ Block copy = block.copy (page) as Block;
+ page.content.add (copy);
+ }
+
+ return page;
+ }
}
diff --git a/src/libvaladoc/content/paragraph.vala b/src/libvaladoc/content/paragraph.vala
index 4998952d40..d50859d0bf 100644
--- a/src/libvaladoc/content/paragraph.vala
+++ b/src/libvaladoc/content/paragraph.vala
@@ -41,5 +41,21 @@ public class Valadoc.Content.Paragraph : InlineContent, Block, StyleAttributes {
public override void accept (ContentVisitor visitor) {
visitor.visit_paragraph (this);
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Paragraph p = new Paragraph ();
+ p.parent = new_parent;
+
+ p.horizontal_align = horizontal_align;
+ p.vertical_align = vertical_align;
+ p.style = style;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (p) as Inline;
+ p.content.add (copy);
+ }
+
+ return p;
+ }
}
diff --git a/src/libvaladoc/content/run.vala b/src/libvaladoc/content/run.vala
index 146d9c29e2..15a9501e07 100644
--- a/src/libvaladoc/content/run.vala
+++ b/src/libvaladoc/content/run.vala
@@ -126,5 +126,17 @@ public class Valadoc.Content.Run : InlineContent, Inline {
public override void accept (ContentVisitor visitor) {
visitor.visit_run (this);
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Run run = new Run (style);
+ run.parent = new_parent;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (run) as Inline;
+ run.content.add (copy);
+ }
+
+ return run;
+ }
}
diff --git a/src/libvaladoc/content/sourcecode.vala b/src/libvaladoc/content/sourcecode.vala
index 70851d3f88..86ad66fd80 100644
--- a/src/libvaladoc/content/sourcecode.vala
+++ b/src/libvaladoc/content/sourcecode.vala
@@ -154,4 +154,14 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline {
// empty source blocks are visible as well
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ SourceCode source_code = new SourceCode ();
+ source_code.parent = new_parent;
+
+ source_code.language = language;
+ source_code.code = code;
+
+ return source_code;
+ }
}
diff --git a/src/libvaladoc/content/symbollink.vala b/src/libvaladoc/content/symbollink.vala
index aff9476e26..a73b4880d6 100644
--- a/src/libvaladoc/content/symbollink.vala
+++ b/src/libvaladoc/content/symbollink.vala
@@ -47,5 +47,11 @@ public class Valadoc.Content.SymbolLink : ContentElement, Inline {
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ SymbolLink link = new SymbolLink (symbol, label);
+ link.parent = new_parent;
+ return link;
+ }
}
diff --git a/src/libvaladoc/content/table.vala b/src/libvaladoc/content/table.vala
index 17fa589e8b..962b063ec2 100644
--- a/src/libvaladoc/content/table.vala
+++ b/src/libvaladoc/content/table.vala
@@ -39,6 +39,7 @@ public class Valadoc.Content.Table : ContentElement, Block {
// Check individual rows
foreach (var row in _rows) {
+ row.parent = this;
row.check (api_root, container, file_path, reporter, settings);
}
}
@@ -56,5 +57,17 @@ public class Valadoc.Content.Table : ContentElement, Block {
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Table table = new Table ();
+ table.parent = new_parent;
+
+ foreach (var row in _rows) {
+ TableRow copy = row.copy (table) as TableRow;
+ table.rows.add (copy);
+ }
+
+ return table;
+ }
}
diff --git a/src/libvaladoc/content/tablecell.vala b/src/libvaladoc/content/tablecell.vala
index 733aad1ca6..bf83e7d301 100644
--- a/src/libvaladoc/content/tablecell.vala
+++ b/src/libvaladoc/content/tablecell.vala
@@ -50,5 +50,23 @@ public class Valadoc.Content.TableCell : InlineContent, StyleAttributes {
// empty cells are displayed as well
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ TableCell cell = new TableCell ();
+ cell.parent = new_parent;
+
+ cell.horizontal_align = horizontal_align;
+ cell.vertical_align = vertical_align;
+ cell.colspan = colspan;
+ cell.rowspan = rowspan;
+ cell.style = style;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (cell) as Inline;
+ cell.content.add (copy);
+ }
+
+ return cell;
+ }
}
diff --git a/src/libvaladoc/content/tablerow.vala b/src/libvaladoc/content/tablerow.vala
index 5cd59fd4bb..1ab62ccd8e 100644
--- a/src/libvaladoc/content/tablerow.vala
+++ b/src/libvaladoc/content/tablerow.vala
@@ -37,6 +37,7 @@ public class Valadoc.Content.TableRow : ContentElement {
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
// Check individual cells
foreach (var cell in _cells) {
+ cell.parent = this;
cell.check (api_root, container, file_path, reporter, settings);
}
}
@@ -54,5 +55,17 @@ public class Valadoc.Content.TableRow : ContentElement {
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ TableRow row = new TableRow ();
+ row.parent = new_parent;
+
+ foreach (TableCell cell in _cells) {
+ TableCell copy = cell.copy (row) as TableCell;
+ row.cells.add (copy);
+ }
+
+ return row;
+ }
}
diff --git a/src/libvaladoc/content/taglet.vala b/src/libvaladoc/content/taglet.vala
index 503cb7c4ca..a8fc4f144a 100644
--- a/src/libvaladoc/content/taglet.vala
+++ b/src/libvaladoc/content/taglet.vala
@@ -26,5 +26,13 @@ using Gee;
public interface Valadoc.Content.Taglet : ContentElement {
public abstract Rule? get_parser_rule (Rule run_rule);
+
+ public virtual Gee.List<Inline>? get_inheritable_documentation () {
+ return null;
+ }
+
+ public virtual bool inheritable (Taglet taglet) {
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/text.vala b/src/libvaladoc/content/text.vala
index 6d3877e87e..d1639399ac 100644
--- a/src/libvaladoc/content/text.vala
+++ b/src/libvaladoc/content/text.vala
@@ -48,5 +48,11 @@ public class Valadoc.Content.Text : ContentElement, Inline {
public override bool is_empty () {
return content == "";
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Text text = new Text (content);
+ text.parent = new_parent;
+ return text;
+ }
}
diff --git a/src/libvaladoc/content/warning.vala b/src/libvaladoc/content/warning.vala
index 3ab9b3c736..d98fbd765f 100644
--- a/src/libvaladoc/content/warning.vala
+++ b/src/libvaladoc/content/warning.vala
@@ -37,5 +37,17 @@ public class Valadoc.Content.Warning : BlockContent, Block {
public override void accept (ContentVisitor visitor) {
visitor.visit_warning (this);
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Warning warning = new Warning ();
+ warning.parent = new_parent;
+
+ foreach (Block block in content) {
+ Block copy = block.copy (warning) as Block;
+ warning.content.add (copy);
+ }
+
+ return warning;
+ }
}
diff --git a/src/libvaladoc/content/wikilink.vala b/src/libvaladoc/content/wikilink.vala
index 5d0d22c4e3..2592b879f1 100644
--- a/src/libvaladoc/content/wikilink.vala
+++ b/src/libvaladoc/content/wikilink.vala
@@ -25,17 +25,16 @@ using Gee;
public class Valadoc.Content.WikiLink : InlineContent, Inline {
- public WikiPage page { get; private set; }
+ public WikiPage page { get; internal set; }
public string name { get; set; }
internal WikiLink () {
base ();
}
- public override void configure (Settings settings, ResourceLocator locator) {
- }
-
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ base.check (api_root, container, file_path, reporter, settings);
+
page = api_root.wikitree.search (name);
if (page == null) {
string node_segment = (container is Api.Package)? "" : container.get_full_name () + ": ";
@@ -48,8 +47,22 @@ public class Valadoc.Content.WikiLink : InlineContent, Inline {
visitor.visit_wiki_link (this);
}
-
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ WikiLink link = new WikiLink ();
+ link.parent = new_parent;
+
+ link.page = page;
+ link.name = name;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (link) as Inline;
+ link.content.add (copy);
+ }
+
+ return link;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletdeprecated.vala b/src/libvaladoc/taglets/tagletdeprecated.vala
index 0d3c19290d..49636cafb2 100644
--- a/src/libvaladoc/taglets/tagletdeprecated.vala
+++ b/src/libvaladoc/taglets/tagletdeprecated.vala
@@ -41,5 +41,17 @@ public class Valadoc.Taglets.Deprecated : InlineContent, Taglet, Block {
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Deprecated deprecated = new Deprecated ();
+ deprecated.parent = new_parent;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (deprecated) as Inline;
+ deprecated.content.add (copy);
+ }
+
+ return deprecated;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletinheritdoc.vala b/src/libvaladoc/taglets/tagletinheritdoc.vala
index 653a448a10..e2e7fdd3e7 100644
--- a/src/libvaladoc/taglets/tagletinheritdoc.vala
+++ b/src/libvaladoc/taglets/tagletinheritdoc.vala
@@ -25,12 +25,37 @@ using Gee;
using Valadoc.Content;
public class Valadoc.Taglets.InheritDoc : InlineTaglet {
+ private Taglet? parent_taglet = null;
private Api.Node? _inherited;
+ private Comment root {
+ get {
+ ContentElement pos;
+ for (pos = this; pos.parent != null; pos = pos.parent);
+ // inheritDoc is only allowed in source comments
+ assert (pos is Comment);
+ return (Comment) pos;
+ }
+ }
+
public override Rule? get_parser_rule (Rule run_rule) {
return null;
}
+ private Taglet? find_parent_taglet () {
+ if (_inherited == null || _inherited.documentation == null) {
+ return null;
+ }
+
+ ContentElement pos;
+ for (pos = this.parent; pos != null && pos is Taglet == false; pos = pos.parent);
+ if (pos is Taglet) {
+ return (Taglet) pos;
+ }
+
+ return null;
+ }
+
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
// TODO Check that the container is an override of an abstract symbol
// Also retrieve that abstract symbol _inherited
@@ -49,6 +74,12 @@ public class Valadoc.Taglets.InheritDoc : InlineTaglet {
api_root.push_unbrowsable_documentation_dependency (_inherited);
}
+ parent_taglet = find_parent_taglet ();
+ if (parent_taglet == null) {
+ root.register_inheritdoc (this);
+ }
+
+
// TODO report error if inherited is null
// TODO postpone check after complete parse of the api tree comments
@@ -56,15 +87,133 @@ public class Valadoc.Taglets.InheritDoc : InlineTaglet {
//base.check (api_root, container, reporter);
}
- public override ContentElement produce_content () {
- if (_inherited != null && _inherited.documentation != null) {
- Paragraph inherited_paragraph = _inherited.documentation.content.get (0) as Paragraph;
+ private Run[]? split_run (Inline? separator) {
+ if (separator == null) {
+ return null;
+ }
- Run paragraph = new Run (Run.Style.NONE);
- foreach (var element in inherited_paragraph.content) {
- paragraph.content.add (element);
+ ContentElement parent = separator.parent;
+ Gee.List<Inline> parent_content = null;
+
+ if (parent is Run && ((Run) parent).style == Run.Style.NONE) {
+ parent_content = ((Run) parent).content;
+ } else if (parent is Paragraph) {
+ parent_content = ((Paragraph) parent).content;
+ }
+
+ if (parent_content != null) {
+ Run right_run = new Run (Run.Style.NONE);
+ Run left_run = new Run (Run.Style.NONE);
+ bool separated = false;
+
+ foreach (var current in parent_content) {
+ if (current == separator) {
+ separated = true;
+ } else if (separated) {
+ right_run.content.add (current);
+ current.parent = right_run;
+ } else {
+ left_run.content.add (current);
+ current.parent = left_run;
+ }
+ }
+
+ return { left_run, right_run };
+ }
+
+ return null;
+ }
+
+ internal void transform (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
+ ContentElement separator = this;
+ Run right_run = null;
+ Run left_run = null;
+ Run[]? parts;
+
+ while ((parts = split_run (separator as Inline)) != null) {
+ if (left_run != null) {
+ parts[0].content.add (left_run);
+ left_run.parent = parts[0];
+ }
+
+ if (right_run != null) {
+ parts[1].content.insert (0, right_run);
+ right_run.parent = parts[1];
+ }
+
+ separator = separator.parent;
+ right_run = parts[1];
+ left_run = parts[0];
+ }
+
+ if (separator is Paragraph == false || separator.parent is Comment == false) {
+ reporter.simple_error ("%s: %s: @inheritDoc: error: Parent documentation can't be copied to this location.", file_path, container.get_full_name ());
+ return ;
+ }
+
+ Comment comment = separator.parent as Comment;
+ assert (comment != null);
+
+ int insert_pos = comment.content.index_of ((Paragraph) separator);
+ int start_pos = insert_pos;
+ assert (insert_pos >= 0);
+
+ foreach (Block block in _inherited.documentation.content) {
+ comment.content.insert (insert_pos, (Block) block.copy (comment));
+ insert_pos++;
+ }
+
+ if (right_run != null) {
+ if (comment.content[insert_pos - 1] is Paragraph) {
+ ((Paragraph) comment.content[insert_pos - 1]).content.add (right_run);
+ right_run.parent = comment.content[insert_pos - 1];
+ } else {
+ Paragraph p = new Paragraph ();
+ p.content.add (right_run);
+ right_run.parent = p;
+ p.parent = comment;
+ comment.content.insert (insert_pos, p);
+ }
+ }
+
+ if (left_run != null) {
+ if (comment.content[start_pos] is Paragraph) {
+ ((Paragraph) comment.content[start_pos]).content.insert (0, left_run);
+ left_run.parent = comment.content[start_pos];
+ } else {
+ Paragraph p = new Paragraph ();
+ p.content.add (left_run);
+ left_run.parent = p;
+ p.parent = comment;
+ comment.content.insert (start_pos, p);
+ }
+ }
+
+ comment.content.remove ((Paragraph) separator);
+ }
+
+ private Run content_copy (Gee.List<Inline>? content) {
+ Run run = new Run (Run.Style.NONE);
+ run.parent = this;
+
+ if (content != null) {
+ foreach (Inline item in content) {
+ run.content.add ((Inline) item.copy (this));
+ }
+ }
+
+ return run;
+ }
+
+ public override ContentElement produce_content () {
+ if (_inherited != null && _inherited.documentation != null && parent_taglet != null) {
+ Gee.List<Taglet> parent_taglets = _inherited.documentation.find_taglets (null, parent_taglet.get_type ());
+ foreach (Taglet parent in parent_taglets) {
+ // we only care about the first match:
+ if (parent.inheritable (parent_taglet)) {
+ return content_copy (parent.get_inheritable_documentation ());
+ }
}
- return paragraph;
}
return new Text ("");
}
@@ -72,4 +221,16 @@ public class Valadoc.Taglets.InheritDoc : InlineTaglet {
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ InheritDoc doc = new InheritDoc ();
+ doc.parent = new_parent;
+
+ doc.settings = settings;
+ doc.locator = locator;
+
+ doc._inherited = _inherited;
+
+ return doc;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletlink.vala b/src/libvaladoc/taglets/tagletlink.vala
index d49aa4b84e..39e4948b5e 100644
--- a/src/libvaladoc/taglets/tagletlink.vala
+++ b/src/libvaladoc/taglets/tagletlink.vala
@@ -106,4 +106,18 @@ public class Valadoc.Taglets.Link : InlineTaglet {
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Link link = new Link ();
+ link.parent = new_parent;
+
+ link.settings = settings;
+ link.locator = locator;
+
+ link.symbol_name = symbol_name;
+ link._context = _context;
+ link._symbol = _symbol;
+
+ return link;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletparam.vala b/src/libvaladoc/taglets/tagletparam.vala
index 78e9d163d3..277d9b6aa3 100644
--- a/src/libvaladoc/taglets/tagletparam.vala
+++ b/src/libvaladoc/taglets/tagletparam.vala
@@ -104,4 +104,33 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
public override void accept (ContentVisitor visitor) {
visitor.visit_taglet (this);
}
+
+ public Gee.List<ContentElement>? get_inheritable_documentation () {
+ return content;
+ }
+
+ public bool inheritable (Taglet taglet) {
+ if (taglet is Taglets.Param == false) {
+ return false;
+ }
+
+ Taglets.Param t = (Taglets.Param) taglet;
+ return (parameter == t.parameter || parameter_name == t.parameter_name);
+ }
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Param param = new Param ();
+ param.parent = new_parent;
+
+ param.parameter_name = parameter_name;
+ param.parameter = parameter;
+ param.position = position;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (param) as Inline;
+ param.content.add (copy);
+ }
+
+ return param;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletreturn.vala b/src/libvaladoc/taglets/tagletreturn.vala
index e616791f64..d447e6eb5d 100644
--- a/src/libvaladoc/taglets/tagletreturn.vala
+++ b/src/libvaladoc/taglets/tagletreturn.vala
@@ -53,4 +53,24 @@ public class Valadoc.Taglets.Return : InlineContent, Taglet, Block {
public override void accept (ContentVisitor visitor) {
visitor.visit_taglet (this);
}
+
+ public Gee.List<ContentElement>? get_inheritable_documentation () {
+ return content;
+ }
+
+ public bool inheritable (Taglet taglet) {
+ return taglet is Taglets.Return;
+ }
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Return ret = new Return ();
+ ret.parent = new_parent;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (ret) as Inline;
+ ret.content.add (copy);
+ }
+
+ return ret;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletsee.vala b/src/libvaladoc/taglets/tagletsee.vala
index fe8f799b58..2d019988fa 100644
--- a/src/libvaladoc/taglets/tagletsee.vala
+++ b/src/libvaladoc/taglets/tagletsee.vala
@@ -63,4 +63,13 @@ public class Valadoc.Taglets.See : ContentElement, Taglet, Block {
public override bool is_empty () {
return false;
}
-}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ See see = new See ();
+ see.parent = new_parent;
+
+ see.symbol_name = symbol_name;
+ see.symbol = symbol;
+
+ return see;
+ }}
diff --git a/src/libvaladoc/taglets/tagletsince.vala b/src/libvaladoc/taglets/tagletsince.vala
index 49acafbc0d..10b87b93b3 100644
--- a/src/libvaladoc/taglets/tagletsince.vala
+++ b/src/libvaladoc/taglets/tagletsince.vala
@@ -48,4 +48,14 @@ public class Valadoc.Taglets.Since : ContentElement, Taglet, Block {
public override bool is_empty () {
return false;
}
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Since since = new Since ();
+ since.parent = new_parent;
+
+ since.version = version;
+
+ return since;
+ }
}
+
diff --git a/src/libvaladoc/taglets/tagletthrows.vala b/src/libvaladoc/taglets/tagletthrows.vala
index 2ba7fa0ce5..2423287107 100644
--- a/src/libvaladoc/taglets/tagletthrows.vala
+++ b/src/libvaladoc/taglets/tagletthrows.vala
@@ -81,5 +81,33 @@ public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block {
public override void accept (ContentVisitor visitor) {
visitor.visit_taglet (this);
}
+
+ public Gee.List<ContentElement>? get_inheritable_documentation () {
+ return content;
+ }
+
+ public bool inheritable (Taglet taglet) {
+ if (taglet is Taglets.Throws == false) {
+ return false;
+ }
+
+ Taglets.Throws t = (Taglets.Throws) taglet;
+ return (error_domain == t.error_domain || error_domain_name == t.error_domain_name);
+ }
+
+ public override ContentElement copy (ContentElement? new_parent = null) {
+ Throws tr = new Throws ();
+ tr.parent = new_parent;
+
+ tr.error_domain_name = error_domain_name;
+ tr.error_domain = error_domain;
+
+ foreach (Inline element in content) {
+ Inline copy = element.copy (tr) as Inline;
+ tr.content.add (copy);
+ }
+
+ return tr;
+ }
}
|
6cf1c05df962548294a2ec5059e6176ca24b8dfc
|
intellij-community
|
formatting of injected code refactored - 3--
|
p
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockBuilder.java b/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockBuilder.java
index 443caba5c1eb5..fba17948117c0 100644
--- a/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockBuilder.java
+++ b/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockBuilder.java
@@ -38,14 +38,16 @@ public abstract class InjectedLanguageBlockBuilder {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.xml.XmlInjectedLanguageBlockBuilder");
public Block createInjectedBlock(ASTNode node, Block originalBlock, Indent indent, int offset, TextRange range) {
- return new InjectedLanguageBlockWrapper(originalBlock, offset, range);
+ return new InjectedLanguageBlockWrapper(originalBlock, offset, range, indent);
}
public abstract CodeStyleSettings getSettings();
public abstract boolean canProcessFragment(String text, ASTNode injectionHost);
- public abstract Block createBlockNextToInjection(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, TextRange range);
+ public abstract Block createBlockBeforeInjection(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, TextRange range);
+
+ public abstract Block createBlockAfterInjection(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, TextRange range);
public boolean addInjectedBlocks(List<Block> result, final ASTNode injectionHost, Wrap wrap, Alignment alignment, Indent indent) {
final PsiFile[] injectedFile = new PsiFile[1];
@@ -85,7 +87,7 @@ public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List<PsiLan
int childOffset = range.getStartOffset();
if (startOffset != 0) {
final ASTNode leaf = injectionHost.findLeafElementAt(startOffset - 1);
- result.add(createBlockNextToInjection(leaf, wrap, alignment, indent, new TextRange(childOffset, childOffset + startOffset)));
+ result.add(createBlockBeforeInjection(leaf, wrap, alignment, indent, new TextRange(childOffset, childOffset + startOffset)));
}
addInjectedLanguageBlockWrapper(result, injectedFile[0].getNode(), indent, childOffset + startOffset,
@@ -93,7 +95,7 @@ public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List<PsiLan
if (endOffset != injectionHost.getTextLength()) {
final ASTNode leaf = injectionHost.findLeafElementAt(endOffset);
- result.add(createBlockNextToInjection(leaf, wrap, alignment, indent, new TextRange(childOffset + endOffset, range.getEndOffset())));
+ result.add(createBlockAfterInjection(leaf, wrap, alignment, indent, new TextRange(childOffset + endOffset, range.getEndOffset())));
}
return true;
}
diff --git a/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockWrapper.java b/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockWrapper.java
index 039e4909bd284..566400540370a 100644
--- a/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockWrapper.java
+++ b/platform/lang-impl/src/com/intellij/psi/formatter/common/InjectedLanguageBlockWrapper.java
@@ -27,6 +27,7 @@ public final class InjectedLanguageBlockWrapper implements Block {
private final Block myOriginal;
private final int myOffset;
private final TextRange myRange;
+ @Nullable private final Indent myIndent;
private List<Block> myBlocks;
/**
@@ -40,15 +41,17 @@ public final class InjectedLanguageBlockWrapper implements Block {
* @param original block inside injected code
* @param offset start offset of injected code inside the main document
* @param range range of code inside injected document which is really placed in the main document
+ * @param indent
*/
- public InjectedLanguageBlockWrapper(final @NotNull Block original, final int offset, @Nullable TextRange range) {
+ public InjectedLanguageBlockWrapper(final @NotNull Block original, final int offset, @Nullable TextRange range, @Nullable Indent indent) {
myOriginal = original;
myOffset = offset;
myRange = range;
+ myIndent = indent;
}
public Indent getIndent() {
- return myOriginal.getIndent();
+ return myIndent != null ? myIndent : myOriginal.getIndent();
}
@Nullable
@@ -58,7 +61,10 @@ public Alignment getAlignment() {
@NotNull
public TextRange getTextRange() {
- final TextRange range = myOriginal.getTextRange();
+ TextRange range = myOriginal.getTextRange();
+ if (myRange != null) {
+ range = range.intersection(myRange);
+ }
int start = myOffset + range.getStartOffset() - (myRange != null ? myRange.getStartOffset() : 0);
return TextRange.from(start, range.getLength());
@@ -80,7 +86,7 @@ private List<Block> buildBlocks() {
final ArrayList<Block> result = new ArrayList<Block>(list.size());
if (myRange == null) {
for (Block block : list) {
- result.add(new InjectedLanguageBlockWrapper(block, myOffset, myRange));
+ result.add(new InjectedLanguageBlockWrapper(block, myOffset, myRange, null));
}
}
else {
@@ -93,7 +99,7 @@ private void collectBlocksIntersectingRange(final List<Block> list, final List<B
for (Block block : list) {
final TextRange textRange = block.getTextRange();
if (range.contains(textRange)) {
- result.add(new InjectedLanguageBlockWrapper(block, myOffset, range));
+ result.add(new InjectedLanguageBlockWrapper(block, myOffset, range, null));
}
else if (textRange.intersectsStrict(range)) {
collectBlocksIntersectingRange(block.getSubBlocks(), result, range);
diff --git a/xml/impl/src/com/intellij/psi/formatter/xml/AnotherLanguageBlockWrapper.java b/xml/impl/src/com/intellij/psi/formatter/xml/AnotherLanguageBlockWrapper.java
index 155b675fe4153..005519dab9561 100644
--- a/xml/impl/src/com/intellij/psi/formatter/xml/AnotherLanguageBlockWrapper.java
+++ b/xml/impl/src/com/intellij/psi/formatter/xml/AnotherLanguageBlockWrapper.java
@@ -37,7 +37,7 @@ public AnotherLanguageBlockWrapper(final ASTNode node,
final int offset,
@Nullable TextRange range) {
super(node, original.getWrap(), original.getAlignment(), policy);
- myInjectedBlock = new InjectedLanguageBlockWrapper(original, offset, range);
+ myInjectedBlock = new InjectedLanguageBlockWrapper(original, offset, range, null);
myIndent = indent;
}
diff --git a/xml/impl/src/com/intellij/psi/formatter/xml/XmlInjectedLanguageBlockBuilder.java b/xml/impl/src/com/intellij/psi/formatter/xml/XmlInjectedLanguageBlockBuilder.java
index da40e1071fcf6..ad97addfdf1ca 100644
--- a/xml/impl/src/com/intellij/psi/formatter/xml/XmlInjectedLanguageBlockBuilder.java
+++ b/xml/impl/src/com/intellij/psi/formatter/xml/XmlInjectedLanguageBlockBuilder.java
@@ -42,7 +42,12 @@ public Block createInjectedBlock(ASTNode node, Block originalBlock, Indent inden
}
@Override
- public Block createBlockNextToInjection(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, TextRange range) {
+ public Block createBlockBeforeInjection(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, TextRange range) {
+ return new XmlBlock(node, wrap, alignment, myXmlFormattingPolicy, indent, range);
+ }
+
+ @Override
+ public Block createBlockAfterInjection(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, TextRange range) {
return new XmlBlock(node, wrap, alignment, myXmlFormattingPolicy, indent, range);
}
|
d158a03f09a1df7df66d53a8eda24762f5707718
|
intellij-community
|
editorPaintStart useless in our case--
|
p
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/lang-impl/src/com/intellij/execution/console/ConsoleGutterComponent.java b/platform/lang-impl/src/com/intellij/execution/console/ConsoleGutterComponent.java
index 3f88997bdad18..e9881c3b60073 100644
--- a/platform/lang-impl/src/com/intellij/execution/console/ConsoleGutterComponent.java
+++ b/platform/lang-impl/src/com/intellij/execution/console/ConsoleGutterComponent.java
@@ -3,8 +3,6 @@
import com.intellij.codeInsight.hint.TooltipController;
import com.intellij.codeInsight.hint.TooltipGroup;
import com.intellij.ide.ui.UISettings;
-import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.impl.ApplicationImpl;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.editor.colors.EditorFontType;
@@ -120,40 +118,34 @@ public Dimension getPreferredSize() {
@Override
public void paint(Graphics g) {
- ((ApplicationImpl)ApplicationManager.getApplication()).editorPaintStart();
- try {
- Rectangle clip = g.getClipBounds();
- if (clip.height <= 0 || maxContentWidth == 0) {
+ Rectangle clip = g.getClipBounds();
+ if (clip.height <= 0 || maxContentWidth == 0) {
+ return;
+ }
+
+ if (atLineStart) {
+ // don't paint in the overlapped region
+ if (clip.x >= maxContentWidth) {
return;
}
- if (atLineStart) {
- // don't paint in the overlapped region
- if (clip.x >= maxContentWidth) {
- return;
- }
-
- g.setColor(editor.getBackgroundColor());
- g.fillRect(clip.x, clip.y, Math.min(clip.width, maxContentWidth - clip.x), clip.height);
- }
+ g.setColor(editor.getBackgroundColor());
+ g.fillRect(clip.x, clip.y, Math.min(clip.width, maxContentWidth - clip.x), clip.height);
+ }
- UISettings.setupAntialiasing(g);
+ UISettings.setupAntialiasing(g);
- Graphics2D g2 = (Graphics2D)g;
- Object hint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
- if (!UIUtil.isRetina()) {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
- }
+ Graphics2D g2 = (Graphics2D)g;
+ Object hint = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
+ if (!UIUtil.isRetina()) {
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
+ }
- try {
- paintAnnotations(g, clip);
- }
- finally {
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, hint);
- }
+ try {
+ paintAnnotations(g, clip);
}
finally {
- ((ApplicationImpl)ApplicationManager.getApplication()).editorPaintFinish();
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, hint);
}
}
|
f26b7b2321ba561c947da92510e95e22f059351c
|
ReactiveX-RxJava
|
Conditionals: Fix all but 2 tests--
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java b/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java
index f6c4f09ad0..44bb0c02c8 100644
--- a/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java
+++ b/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java
@@ -15,6 +15,7 @@
*/
package rx.operators;
+import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
@@ -33,8 +34,10 @@
import rx.Observer;
import rx.Statement;
import rx.Subscription;
+import rx.observers.TestObserver;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;
+import rx.util.functions.Action1;
import rx.util.functions.Func0;
public class OperationConditionalsTest {
@@ -108,7 +111,7 @@ public T call() {
<T> void observe(Observable<? extends T> source, T... values) {
Observer<T> o = mock(Observer.class);
- Subscription s = source.subscribe(o);
+ Subscription s = source.subscribe(new TestObserver<T>(o));
InOrder inOrder = inOrder(o);
@@ -127,7 +130,7 @@ <T> void observe(Observable<? extends T> source, T... values) {
<T> void observeSequence(Observable<? extends T> source, Iterable<? extends T> values) {
Observer<T> o = mock(Observer.class);
- Subscription s = source.subscribe(o);
+ Subscription s = source.subscribe(new TestObserver<T>(o));
InOrder inOrder = inOrder(o);
@@ -146,7 +149,7 @@ <T> void observeSequence(Observable<? extends T> source, Iterable<? extends T> v
<T> void observeError(Observable<? extends T> source, Class<? extends Throwable> error, T... valuesBeforeError) {
Observer<T> o = mock(Observer.class);
- Subscription s = source.subscribe(o);
+ Subscription s = source.subscribe(new TestObserver<T>(o));
InOrder inOrder = inOrder(o);
@@ -165,7 +168,7 @@ <T> void observeError(Observable<? extends T> source, Class<? extends Throwable>
<T> void observeSequenceError(Observable<? extends T> source, Class<? extends Throwable> error, Iterable<? extends T> valuesBeforeError) {
Observer<T> o = mock(Observer.class);
- Subscription s = source.subscribe(o);
+ Subscription s = source.subscribe(new TestObserver<T>(o));
InOrder inOrder = inOrder(o);
@@ -400,6 +403,7 @@ public Boolean call() {
@Test
public void testDoWhileManyTimes() {
+ fail("deadlocking");
Observable<Integer> source1 = Observable.from(1, 2, 3).subscribeOn(Schedulers.currentThread());
List<Integer> expected = new ArrayList<Integer>(numRecursion * 3);
|
a29e41b9fa93162b7731ed2d45a2ac368384decd
|
spring-framework
|
Fix Jackson @JSONView when using XML- serialization--Issue: SPR-12149-
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMappingJacksonResponseBodyAdvice.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMappingJacksonResponseBodyAdvice.java
index dd87024c59f6..185a151d9999 100644
--- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMappingJacksonResponseBodyAdvice.java
+++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMappingJacksonResponseBodyAdvice.java
@@ -19,6 +19,7 @@
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
@@ -36,7 +37,7 @@ public abstract class AbstractMappingJacksonResponseBodyAdvice implements Respon
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
- return MappingJackson2HttpMessageConverter.class.equals(converterType);
+ return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
}
@Override
|
74fdcdcf5f41f420cf46f06ecfebce84ec8f36eb
|
camel
|
CAMEL-656: Polished dataset and timer component.- Added @deprecation to not used method. Removed unused imports.--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@712497 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/component/dataset/DataSet.java b/camel-core/src/main/java/org/apache/camel/component/dataset/DataSet.java
index ea6509d94af44..b6333e8b7994c 100644
--- a/camel-core/src/main/java/org/apache/camel/component/dataset/DataSet.java
+++ b/camel-core/src/main/java/org/apache/camel/component/dataset/DataSet.java
@@ -29,8 +29,6 @@ public interface DataSet {
/**
* Populates a message exchange when using the DataSet as a source of messages
- *
- * @param exchange
*/
void populateMessage(Exchange exchange, long messageIndex) throws Exception;
diff --git a/camel-core/src/main/java/org/apache/camel/component/dataset/DataSetConsumer.java b/camel-core/src/main/java/org/apache/camel/component/dataset/DataSetConsumer.java
index 7e46571866b64..e90e5e7cce751 100644
--- a/camel-core/src/main/java/org/apache/camel/component/dataset/DataSetConsumer.java
+++ b/camel-core/src/main/java/org/apache/camel/component/dataset/DataSetConsumer.java
@@ -80,7 +80,7 @@ protected void sendMessages(long startIndex, long endIndex) {
}
}
} catch (Exception e) {
- LOG.error(e);
+ handleException(e);
}
}
diff --git a/camel-core/src/main/java/org/apache/camel/component/timer/TimerConsumer.java b/camel-core/src/main/java/org/apache/camel/component/timer/TimerConsumer.java
index 7ecc6b080f3a3..e20923af74b96 100644
--- a/camel-core/src/main/java/org/apache/camel/component/timer/TimerConsumer.java
+++ b/camel-core/src/main/java/org/apache/camel/component/timer/TimerConsumer.java
@@ -101,7 +101,7 @@ protected void sendTimerExchange() {
try {
getProcessor().process(exchange);
} catch (Exception e) {
- getExceptionHandler().handleException(e);
+ handleException(e);
}
}
}
diff --git a/camel-core/src/main/java/org/apache/camel/model/AggregatorType.java b/camel-core/src/main/java/org/apache/camel/model/AggregatorType.java
index 57748c2ff1248..de74b3770d39a 100644
--- a/camel-core/src/main/java/org/apache/camel/model/AggregatorType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/AggregatorType.java
@@ -34,9 +34,7 @@
import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.Route;
-import org.apache.camel.RuntimeCamelException;
import org.apache.camel.builder.ExpressionClause;
-import org.apache.camel.builder.xml.DefaultNamespaceContext;
import org.apache.camel.model.language.ExpressionType;
import org.apache.camel.processor.Aggregator;
import org.apache.camel.processor.FilterProcessor;
@@ -368,8 +366,11 @@ public List<ProcessorType<?>> getOutputs() {
public void setOutputs(List<ProcessorType<?>> outputs) {
this.outputs = outputs;
- }
+ }
+ /**
+ * @deprecated not used. Will be removed in Camel 2.0.
+ */
protected FilterProcessor createFilterProcessor(RouteContext routeContext) throws Exception {
Processor childProcessor = routeContext.createProcessor(this);
return new FilterProcessor(getExpression().createPredicate(routeContext), childProcessor);
|
2b6613770cbf5e6d5ac6a99dae5325a64a35d2f4
|
tapiji
|
Replaces new PDEUtils merged from stable branch with old PDE Utils.
We prefer using the new PDEUtils class written by Stefan Reiterer. But since this class brings us a direct dependency to the PDE package, we must replace it with the old implementation. Otherwise, the translator cannot use it, because it runs outside the PDE environment.
|
a
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipse.babel.core/META-INF/MANIFEST.MF b/org.eclipse.babel.core/META-INF/MANIFEST.MF
index f4f76730..6d20cfa6 100644
--- a/org.eclipse.babel.core/META-INF/MANIFEST.MF
+++ b/org.eclipse.babel.core/META-INF/MANIFEST.MF
@@ -27,7 +27,6 @@ Export-Package: org.eclipse.babel.core.configuration;uses:="org.eclipse.babel.co
Require-Bundle: org.eclipse.core.databinding,
org.eclipse.core.resources,
org.eclipse.core.runtime,
- org.eclipse.pde.core;bundle-version="3.7.1",
org.eclipse.jdt.core;bundle-version="3.6.2";resolution:=optional,
org.eclipselabs.tapiji.translator.rap.supplemental;bundle-version="0.0.2";resolution:=optional
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
index cd4a9d88..69ede279 100644
--- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
+++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java
@@ -1,245 +1,290 @@
-/*******************************************************************************
- * Copyright (c) 2012 Stefan Reiterer.
- * 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
*
- * Contributors:
- * Stefan Reiterer - initial API and implementation
- ******************************************************************************/
-
+ * 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.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.Arrays;
-import java.util.Collections;
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.runtime.CoreException;
-import org.eclipse.osgi.service.resolver.BundleDescription;
-import org.eclipse.osgi.service.resolver.HostSpecification;
-import org.eclipse.pde.core.plugin.IFragmentModel;
-import org.eclipse.pde.core.plugin.IPluginBase;
-import org.eclipse.pde.core.plugin.IPluginModelBase;
-import org.eclipse.pde.core.plugin.PluginRegistry;
+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$
- // The same as PDE.PLUGIN_NATURE, because the PDE provided constant is not accessible (internal class)
- private static final String PLUGIN_NATURE = "org.eclipse.pde.PluginNature";
-
- /**
- * Get the project's plug-in Id if the given project is an eclipse plug-in.
+ /**
+ * Returns the plugin-id of the project if it is a plugin project. Else
+ * null is returned.
*
- * @param project the workspace project.
- * @return the project's plug-in Id. Null if the project is no plug-in project.
+ * @param project the project
+ * @return the plugin-id or null
*/
public static String getPluginId(IProject project) {
-
- if (project == null || !isPluginProject(project)) {
- return null;
- }
-
- IPluginModelBase pluginModelBase = PluginRegistry.findModel(project);
-
- if (pluginModelBase == null) {
- // plugin not found in registry
+ if (project == null)
return null;
- }
-
- IPluginBase pluginBase = pluginModelBase.getPluginBase();
-
- return pluginBase.getId();
+ 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) {
- if (isFragment(pluginProject) && pluginProject.isOpen()) {
- return new IProject[] {pluginProject};
- }
-
- IProject[] workspaceProjects = pluginProject.getWorkspace().getRoot().getProjects();
- String hostPluginId = getPluginId(pluginProject);
-
- if (hostPluginId == null) {
- // project is not a plugin project
+ * 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]);
}
- List<IProject> fragmentProjects = new ArrayList<IProject>();
- for (IProject project : workspaceProjects) {
- if (!project.isOpen() || getFragmentId(project, hostPluginId) == null) {
- // project is not open or it is no fragment where given project is the host project.
+ IProject[] projects = pluginProject.getWorkspace().getRoot().getProjects();
+ for (int i = 0; i < projects.length; i++) {
+ IProject project = projects[i];
+ if (!project.isOpen())
continue;
- }
- fragmentProjects.add(project);
- }
-
- if (fragmentProjects.isEmpty()) {
- return null;
+ if (getFragmentId(project, pluginId) == null)
+ continue;
+ fragmentIds.add(project);
}
-
- return fragmentProjects.toArray(new IProject[0]);
- }
+
+ if (fragmentIds.size() > 0) return fragmentIds.toArray(new IProject[0]);
+ else return null;
+ }
- /**
- * Check if the given plug-in project is a fragment.
- *
- * @param pluginProject the plug-in project in the workspace.
- * @return true if it is a fragment, otherwise false.
- */
- public static boolean isFragment(IProject pluginProject) {
- if (pluginProject == null) {
+ public static boolean isFragment(IProject pluginProject){
+ String pluginId = PDEUtils.getPluginId(pluginProject);
+ if (pluginId == null)
return false;
- }
-
- IPluginModelBase pModel = PluginRegistry.findModel(pluginProject);
-
- if (pModel == null) {
- // this project is not a plugin/fragment
+ 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 pModel.isFragmentModel();
- }
-
- /**
- * Get all fragments for the given host project.
- *
- * @param hostProject the host plug-in project in the workspace.
- * @return a list of all fragment projects for the given host project which are in the same workspace as the host project.
- */
- public static List<IProject> getFragments(IProject hostProject) {
- // Check preconditions
- String hostId = getPluginId(hostProject);
- if (hostProject == null || hostId == null) {
- // no valid host project given.
- return Collections.emptyList();
- }
-
- // Get the fragments of the host project
- IPluginModelBase pModelBase = PluginRegistry.findModel(hostProject);
- BundleDescription desc = pModelBase.getBundleDescription();
-
- ArrayList<IPluginModelBase> fragmentModels = new ArrayList<IPluginModelBase>();
- if (desc == null) {
- // There is no bundle description for the host project
- return Collections.emptyList();
- }
-
- BundleDescription[] f = desc.getFragments();
- for (BundleDescription candidateDesc : f) {
- IPluginModelBase candidate = PluginRegistry.findModel(candidateDesc);
- if (candidate instanceof IFragmentModel) {
- fragmentModels.add(candidate);
- }
- }
-
- // Get the fragment project which is in the current workspace
- ArrayList<IProject> fragments = getFragmentsAsWorkspaceProjects(hostProject, fragmentModels);
-
- return fragments;
- }
-
- /**
+
+ 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
+ * @param project the project
+ * @param hostPluginId the host plugin id
* @return the plugin-id or null
*/
- public static String getFragmentId(IProject project, String hostPluginId) {
- if (!isFragment(project) || hostPluginId == null) {
- return 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();
+ }
}
-
- IPluginModelBase pluginModelBase = PluginRegistry.findModel(project);
- if (pluginModelBase instanceof IFragmentModel) {
- IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase;
- BundleDescription description = fragmentModel.getBundleDescription();
- HostSpecification hostSpecification = description.getHost();
-
- if (hostPluginId.equals(hostSpecification.getName())) {
- return getPluginId(project);
- }
+ 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 host plugin project of the specified project if it contains a
- * fragment.
+ * Returns the file content as UTF8 string.
*
- * @param fragment
- * the fragment project
- * @return the host plugin project or null
+ * @param file
+ * @param charset
+ * @return
*/
- public static IProject getFragmentHost(IProject fragment) {
- if (!isFragment(fragment)) {
- return null;
- }
-
- IPluginModelBase pluginModelBase = PluginRegistry.findModel(fragment);
- if (pluginModelBase instanceof IFragmentModel) {
- IFragmentModel fragmentModel = (IFragmentModel) pluginModelBase;
- BundleDescription description = fragmentModel.getBundleDescription();
- HostSpecification hostSpecification = description.getHost();
-
- IPluginModelBase hostProject = PluginRegistry.findModel(hostSpecification.getName());
- IProject[] projects = fragment.getWorkspace().getRoot().getProjects();
- ArrayList<IProject> hostProjects = getPluginProjects(Arrays.asList(hostProject), projects);
-
- if (hostProjects.size() != 1) {
- // hostproject not in workspace
- return null;
- } else {
- return hostProjects.get(0);
- }
+ 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();
}
-
- return null;
}
- private static ArrayList<IProject> getFragmentsAsWorkspaceProjects(IProject hostProject, ArrayList<IPluginModelBase> fragmentModels) {
- IProject[] projects = hostProject.getWorkspace().getRoot().getProjects();
-
- ArrayList<IProject> fragments = getPluginProjects(fragmentModels, projects);
-
- return fragments;
- }
+ 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 ArrayList<IProject> getPluginProjects(List<IPluginModelBase> fragmentModels, IProject[] projects) {
- ArrayList<IProject> fragments = new ArrayList<IProject>();
- for (IProject project : projects) {
- IPluginModelBase pModel = PluginRegistry.findModel(project);
-
- if (fragmentModels.contains(pModel)) {
- fragments.add(project);
+ 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();
}
}
-
- return fragments;
- }
-
- private static boolean isPluginProject(IProject project) {
- try {
- return project.hasNature(PLUGIN_NATURE);
- } catch (CoreException ce) {
- //Logger.logError(ce);
+ }
+
+ 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 false;
- }
-}
\ No newline at end of file
+ return null;
+ }
+
+}
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 a0a2e99b..c3cc8562 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
@@ -245,15 +245,15 @@ private int calculateKeyLine(String key, IFile file) {
@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;
+ 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;
|
d26352162c497083a294b999126f6a23bb5a45f3
|
tapiji
|
Adapts the namespace of all TapiJI plug-ins to org.eclipselabs.tapiji.*.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/at.ac.tuwien.inso.eclipse.i18n/.project b/at.ac.tuwien.inso.eclipse.i18n/.project
index 5c19dd35..cbf1d6df 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/.project
+++ b/at.ac.tuwien.inso.eclipse.i18n/.project
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
- <name>at.ac.tuwien.inso.eclipse.i18n</name>
+ <name>org.eclipselabs.tapiji.tools.core</name>
<comment></comment>
<projects>
</projects>
diff --git a/at.ac.tuwien.inso.eclipse.i18n/META-INF/MANIFEST.MF b/at.ac.tuwien.inso.eclipse.i18n/META-INF/MANIFEST.MF
index c68ef854..7317d1aa 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/META-INF/MANIFEST.MF
+++ b/at.ac.tuwien.inso.eclipse.i18n/META-INF/MANIFEST.MF
@@ -1,9 +1,9 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: TapiJI Tools
-Bundle-SymbolicName: at.ac.tuwien.inso.eclipse.i18n;singleton:=true
+Bundle-SymbolicName: org.eclipselabs.tapiji.tools.core;singleton:=true
Bundle-Version: 0.0.1.qualifier
-Bundle-Activator: at.ac.tuwien.inso.eclipse.i18n.Activator
+Bundle-Activator: org.eclipselabs.tapiji.tools.core.Activator
Bundle-Vendor: Vienna University of Technology
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
@@ -13,7 +13,7 @@ Require-Bundle: org.eclipse.ui,
org.eclipse.core.resources,
org.eclipse.jface.text;bundle-version="3.5.2",
com.essiembre.eclipse.i18n.resourcebundle;bundle-version="0.7.7",
- at.ac.tuwien.inso.eclipse.rbe;bundle-version="0.0.1"
+ org.eclipselabs.tapiji.translator.rbe;bundle-version="0.0.1"
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Bundle-ActivationPolicy: lazy
Import-Package: org.eclipse.core.filebuffers,
@@ -23,9 +23,9 @@ Import-Package: org.eclipse.core.filebuffers,
org.eclipse.jface.text,
org.eclipse.jface.text.contentassist,
org.eclipse.ui.ide
-Export-Package: at.ac.tuwien.inso.eclipse.i18n.builder,
- at.ac.tuwien.inso.eclipse.i18n.builder.quickfix,
- at.ac.tuwien.inso.eclipse.i18n.extensions,
- at.ac.tuwien.inso.eclipse.i18n.model.manager,
- at.ac.tuwien.inso.eclipse.i18n.ui.dialogs,
- at.ac.tuwien.inso.eclipse.i18n.util
+Export-Package: org.eclipselabs.tapiji.tools.core.builder,
+ org.eclipselabs.tapiji.tools.core.builder.quickfix,
+ org.eclipselabs.tapiji.tools.core.extensions,
+ org.eclipselabs.tapiji.tools.core.model.manager,
+ org.eclipselabs.tapiji.tools.core.ui.dialogs,
+ org.eclipselabs.tapiji.tools.core.util
diff --git a/at.ac.tuwien.inso.eclipse.i18n/plugin.xml b/at.ac.tuwien.inso.eclipse.i18n/plugin.xml
index fb5a513d..6e36a340 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/plugin.xml
+++ b/at.ac.tuwien.inso.eclipse.i18n/plugin.xml
@@ -1,20 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
- <extension-point id="at.ac.tuwien.inso.eclipse.i18n.builderExtension" name="BuilderExtension" schema="schema/at.ac.tuwien.inso.eclipse.i18n.builderExtension.exsd"/>
+ <extension-point id="org.eclipselabs.tapiji.tools.core.builderExtension" name="BuilderExtension" schema="schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd"/>
<extension
point="org.eclipse.ui.views">
<category
name="Internatinoalization"
- id="at.ac.tuwien.inso.eclipse.i18n">
+ id="org.eclipselabs.tapiji.tools.core">
</category>
<view
name="Resource-Bundle"
icon="icons/resourcebundle.gif"
- category="at.ac.tuwien.inso.eclipse.i18n"
- class="at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview.MessagesView"
- id="at.ac.tuwien.inso.eclipse.i18n.views.MessagesView">
+ category="org.eclipselabs.tapiji.tools.core"
+ class="org.eclipselabs.tapiji.tools.core.ui.views.messagesview.MessagesView"
+ id="org.eclipselabs.tapiji.tools.core.views.MessagesView">
</view>
</extension>
<extension
@@ -22,54 +22,48 @@
<perspectiveExtension
targetID="org.eclipse.jdt.ui.JavaPerspective">
<view
+ id="org.eclipselabs.tapiji.tools.core.views.MessagesView"
ratio="0.5"
- relative="org.eclipse.ui.views.TaskList"
relationship="right"
- id="at.ac.tuwien.inso.eclipse.i18n.views.MessagesView">
+ relative="org.eclipse.ui.views.TaskList">
</view>
</perspectiveExtension>
</extension>
+
<extension
- id="stringLiteralAuditor"
+ id="I18NBuilder"
point="org.eclipse.core.resources.builders">
- <builder
- hasNature="true">
- <run
- class="at.ac.tuwien.inso.eclipse.i18n.builder.StringLiteralAuditor">
- </run>
+ <builder hasNature="true">
+ <run class="org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor" />
</builder>
</extension>
+
<extension
- id="stringLiteralAuditor"
- name="Constant String Literal Auditor"
+ id="org.eclipselabs.tapiji.tools.core.nature"
+ name="Internationalization Nature"
point="org.eclipse.core.resources.natures">
<runtime>
- <run
- class="at.ac.tuwien.inso.eclipse.i18n.builder.InternationalizationNature">
- </run>
+ <run class="org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature" />
</runtime>
- <builder
- id="at.ac.tuwien.inso.eclipse.i18n.stringLiteralAuditor">
- </builder>
- <requires-nature
- id="org.eclipse.jdt.core.javanature">
- </requires-nature>
+ <builder id="org.eclipselabs.tapiji.tools.core.I18NBuilder" />
+ <requires-nature id="org.eclipse.jdt.core.javanature"/>
</extension>
+
<extension
point="org.eclipse.ui.menus">
<menuContribution
locationURI="popup:org.eclipse.ui.popup.any?before=additions">
<menu
- id="at.ac.tuwien.inso.eclipse.i18n.ui.menus.Internationalization"
+ id="org.eclipselabs.tapiji.tools.core.ui.menus.Internationalization"
label="Internationalization"
tooltip="Java Internationalization assistance">
</menu>
</menuContribution>
<menuContribution
- locationURI="popup:at.ac.tuwien.inso.eclipse.i18n.ui.menus.Internationalization?after=additions">
+ locationURI="popup:org.eclipselabs.tapiji.tools.core.ui.menus.Internationalization?after=additions">
<dynamic
- class="at.ac.tuwien.inso.eclipse.i18n.ui.menus.InternationalizationMenu"
- id="at.ac.tuwien.inso.eclipse.i18n.ui.menus.ExcludeResource">
+ class="org.eclipselabs.tapiji.tools.core.ui.menus.InternationalizationMenu"
+ id="org.eclipselabs.tapiji.tools.core.ui.menus.ExcludeResource">
</dynamic>
</menuContribution>
</extension>
@@ -117,14 +111,14 @@
<extension
point="org.eclipse.ui.ide.markerResolution">
<markerResolutionGenerator
- class="at.ac.tuwien.inso.eclipse.i18n.builder.ViolationResolutionGenerator"
- markerType="at.ac.tuwien.inso.eclipse.i18n.StringLiteralAuditMarker">
+ class="org.eclipselabs.tapiji.tools.core.builder.ViolationResolutionGenerator"
+ markerType="org.eclipselabs.tapiji.tools.core.StringLiteralAuditMarker">
</markerResolutionGenerator>
</extension>
<extension
point="org.eclipse.jdt.ui.javaElementFilters">
<filter
- class="at.ac.tuwien.inso.eclipse.i18n.ui.filters.PropertiesFileFilter"
+ class="org.eclipselabs.tapiji.tools.core.ui.filters.PropertiesFileFilter"
description="Filters only resource bundles"
enabled="false"
id="ResourceBundleFilter"
@@ -135,8 +129,8 @@
point="org.eclipse.ui.decorators">
<decorator
adaptable="true"
- class="at.ac.tuwien.inso.eclipse.i18n.ui.decorators.ExcludedResource"
- id="at.ac.tuwien.inso.eclipse.i18n.decorators.ExcludedResource"
+ class="org.eclipselabs.tapiji.tools.core.ui.decorators.ExcludedResource"
+ id="org.eclipselabs.tapiji.tools.core.decorators.ExcludedResource"
label="Resource is excluded from Internationalization"
lightweight="false"
state="true">
diff --git a/at.ac.tuwien.inso.eclipse.i18n/schema/at.ac.tuwien.inso.eclipse.i18n.builderExtension.exsd b/at.ac.tuwien.inso.eclipse.i18n/schema/at.ac.tuwien.inso.eclipse.i18n.builderExtension.exsd
deleted file mode 100644
index 1b29f093..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/schema/at.ac.tuwien.inso.eclipse.i18n.builderExtension.exsd
+++ /dev/null
@@ -1,102 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!-- Schema file written by PDE -->
-<schema targetNamespace="at.ac.tuwien.inso.eclipse.i18n" xmlns="http://www.w3.org/2001/XMLSchema">
-<annotation>
- <appinfo>
- <meta.schema plugin="at.ac.tuwien.inso.eclipse.i18n" id="at.ac.tuwien.inso.eclipse.i18n.builderExtension" name="BuilderExtension"/>
- </appinfo>
- <documentation>
- Enables plug-ins to contribute resource auditors for finding Internationalization errors.
- </documentation>
- </annotation>
-
- <element name="extension">
- <annotation>
- <appinfo>
- <meta.element />
- </appinfo>
- </annotation>
- <complexType>
- <choice minOccurs="0" maxOccurs="unbounded">
- <element ref="i18nResourceAuditor"/>
- </choice>
- <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="i18nResourceAuditor">
- <complexType>
- <attribute name="class" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- <appinfo>
- <meta.attribute kind="java" basedOn="at.ac.tuwien.inso.eclipse.i18n.extensions.I18nResourceAuditor:"/>
- </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/at.ac.tuwien.inso.eclipse.i18n/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd b/at.ac.tuwien.inso.eclipse.i18n/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd
new file mode 100644
index 00000000..48ac0875
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/schema/org.eclipselabs.tapiji.tools.core.builderExtension.exsd
@@ -0,0 +1,224 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipselabs.tapiji.tools.core" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="org.eclipselabs.tapiji.tools.core" id="builderExtension" name="BuilderExtension"/>
+ </appinfo>
+ <documentation>
+ The TapiJI core plug-in does not contribute any coding assistances into the source code editor. Analogically, it does not provide logic for finding Internationalization problems within sources resources. Moreover, it offers a platform for contributing source code analysis and problem resolution proposals for Internationalization problems in a uniform way. For this purpose, the TapiJI core plug-in provides the extension point org.eclipselabs.tapiji.tools.core.builderExtension that allows other plug-ins to register Internationalization related coding assistances. This concept realizes a loose coupling between basic Internationalization functionality and coding dialect specific help. Once the TapiJI core plug-in is installed, it allows an arbitrary number of extensions to provide their own assistances based on the TapiJI Tools suite.
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
+ <complexType>
+ <choice minOccurs="0" maxOccurs="unbounded">
+ <element ref="i18nResourceAuditor"/>
+ </choice>
+ <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="i18nResourceAuditor">
+ <complexType>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn="org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor:"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ 0.0.1
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="examples"/>
+ </appinfo>
+ <documentation>
+ The following example demonstrates registration of Java Programming dialect specific Internationalization assistance.
+
+<pre>
+<extension point="org.eclipselabs.tapiji.tools.core.builderExtension">
+ <i18nResourceAuditor
+ class="auditor.JavaResourceAuditor">
+ </i18nResourceAuditor>
+</extension>
+</pre>
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="apiinfo"/>
+ </appinfo>
+ <documentation>
+ Extending plug-ins need to extend the abstract class <strong>org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor</strong>.
+
+<pre>
+package org.eclipselabs.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 {
+ /**
+ * 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;
+ }
+}
+
+</pre>
+
+
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="implementation"/>
+ </appinfo>
+ <documentation>
+ <ul>
+ <li>Java Internationalization help: <span style="font-family:monospace">org.eclipselabs.tapiji.tools.java</span></li>
+ <li>JSF Internaization help: <span style="font-family:monospace">org.eclipselabs.tapiji.tools.jsf</span></li>
+</ul>
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="copyright"/>
+ </appinfo>
+ <documentation>
+ Copyright (c) 2011 Stefan Strobl and Martin Reiterer 2011. All rights reserved.
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/I18nResourceAuditor.java b/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/I18nResourceAuditor.java
deleted file mode 100644
index c7d7258b..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/I18nResourceAuditor.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package at.ac.tuwien.inso.eclipse.i18n.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 I18nResourceAuditor {
-
- public abstract void audit (IResource resource);
-
- public abstract String[] getFileEndings();
-
- public abstract List<ILocation> getConstantStringLiterals();
-
- public abstract List<ILocation> getBrokenResourceReferences();
-
- public abstract List<ILocation> getBrokenBundleReferences();
-
- public abstract String getContextId();
-
- public abstract List<IMarkerResolution> getMarkerResolutions(IMarker marker, int cause);
-
- public boolean isResourceOfType (IResource resource) {
- for (String ending : getFileEndings()) {
- if (resource.getFileExtension().equalsIgnoreCase(ending))
- return true;
- }
- return false;
- }
-
-}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/ILocation.java b/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/ILocation.java
deleted file mode 100644
index 4f29efc9..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/ILocation.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package at.ac.tuwien.inso.eclipse.i18n.extensions;
-
-import org.eclipse.core.resources.IFile;
-
-public interface ILocation {
- public IFile getFile();
-
- public void setFile(IFile file);
-
- public int getStartPos();
-
- public void setStartPos(int startPos);
-
- public int getEndPos();
-
- public void setEndPos(int endPos);
-
- public String getLiteral();
-
- public Object getData ();
-
- public void setData (Object data);
-}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceBundleChangedListener.java b/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceBundleChangedListener.java
deleted file mode 100644
index bdc0faf3..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceBundleChangedListener.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package at.ac.tuwien.inso.eclipse.i18n.model;
-
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleChangedEvent;
-
-public interface IResourceBundleChangedListener {
-
- public void resourceBundleChanged (ResourceBundleChangedEvent event);
-
-}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceExclusionListener.java b/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceExclusionListener.java
deleted file mode 100644
index dc2c8ff7..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceExclusionListener.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package at.ac.tuwien.inso.eclipse.i18n.model;
-
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceExclusionEvent;
-
-public interface IResourceExclusionListener {
-
- public void exclusionChanged(ResourceExclusionEvent event);
-
-}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleDetector.java b/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleDetector.java
deleted file mode 100644
index 394fd9b6..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleDetector.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package at.ac.tuwien.inso.eclipse.i18n.model.manager;
-
-public class ResourceBundleDetector {
-
-}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/DialogFactory.java b/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/DialogFactory.java
deleted file mode 100644
index 9a46b7f4..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/DialogFactory.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.dialogs;
-
-public class DialogFactory {
-
-}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/markers/StringLiterals.java b/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/markers/StringLiterals.java
deleted file mode 100644
index acb1c357..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/markers/StringLiterals.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.markers;
-
-public class StringLiterals {
-
-}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/listener/IResourceSelectionListener.java b/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/listener/IResourceSelectionListener.java
deleted file mode 100644
index 174f517d..00000000
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/listener/IResourceSelectionListener.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.listener;
-
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.event.ResourceSelectionEvent;
-
-public interface IResourceSelectionListener {
-
- public void selectionChanged (ResourceSelectionEvent e);
-
-}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/Activator.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/Activator.java
similarity index 75%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/Activator.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/Activator.java
index f9aa573f..ae587f38 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/Activator.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/Activator.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n;
+package org.eclipselabs.tapiji.tools.core;
import java.text.MessageFormat;
import java.util.MissingResourceException;
@@ -6,9 +6,9 @@
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
import org.osgi.framework.BundleContext;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
/**
* The activator class controls the plug-in life cycle
@@ -16,10 +16,10 @@
public class Activator extends AbstractUIPlugin {
// The plug-in ID
- public static final String PLUGIN_ID = "at.ac.tuwien.inso.eclipse.i18n";
+ public static final String PLUGIN_ID = "org.eclipselabs.tapiji.tools.core";
// The builder extension id
- public static final String BUILDER_EXTENSION_ID = "at.ac.tuwien.inso.eclipse.i18n.builderExtension";
+ public static final String BUILDER_EXTENSION_ID = "org.eclipselabs.tapiji.tools.core.builderExtension";
// The shared instance
private static Activator plugin;
@@ -73,31 +73,10 @@ public static Activator getDefault() {
public static ImageDescriptor getImageDescriptor(String path) {
if (path.indexOf("icons/") < 0)
path = "icons/" + path;
+
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
-// /**
-// * Gets an image descriptor.
-// * @param name image name
-// * @return image descriptor
-// */
-// public static ImageDescriptor getImageDescriptor(String name) {
-// if (name.startsWith("/icons/")) {
-// return imageDescriptorFromPlugin(PLUGIN_ID, name);
-// } else {
-// String iconPath = name.startsWith("/icons/") ? "" : "icons/"; //$NON-NLS-1$
-// try {
-// URL installURL = Activator.getDefault().getBundle().getEntry(
-// "/"); //$NON-NLS-1$
-// URL url = new URL(installURL, iconPath + name);
-// return ImageDescriptor.createFromURL(url);
-// } catch (MalformedURLException e) {
-// // should not happen
-// return ImageDescriptor.getMissingImageDescriptor();
-// }
-// }
-// }
-
/**
* Returns the string from the plugin's resource bundle,
* or 'key' if not found.
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/Logger.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/Logger.java
new file mode 100644
index 00000000..c6660809
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/Logger.java
@@ -0,0 +1,31 @@
+package org.eclipselabs.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/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/InternationalizationNature.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java
similarity index 80%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/InternationalizationNature.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java
index 92a26b3d..b3c4c79a 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/InternationalizationNature.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/InternationalizationNature.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder;
+package org.eclipselabs.tapiji.tools.core.builder;
import java.util.ArrayList;
import java.util.Arrays;
@@ -12,18 +12,19 @@
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
+import org.eclipselabs.tapiji.tools.core.Activator;
+import org.eclipselabs.tapiji.tools.core.Logger;
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
public class InternationalizationNature implements IProjectNature {
- private static final String NATURE_ID = Activator.PLUGIN_ID + ".stringLiteralAuditor";
+ private static final String NATURE_ID = Activator.PLUGIN_ID + ".nature";
private IProject project;
@Override
public void configure() throws CoreException {
StringLiteralAuditor.addBuilderToProject(project);
- new Job ("Audit source files for constant string literals") {
+ new Job ("Audit source files") {
@Override
protected IStatus run(IProgressMonitor monitor) {
@@ -33,7 +34,7 @@ protected IStatus run(IProgressMonitor monitor) {
null,
monitor);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
return Status.OK_STATUS;
}
@@ -65,7 +66,7 @@ public static void addNature(IProject project) {
try {
description = project.getDescription();
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
return;
}
@@ -83,15 +84,24 @@ public static void addNature(IProject project) {
try {
project.setDescription(description, null);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
+ public static boolean supportsNature (IProject project) {
+ try {
+ return project.isOpen() &&
+ project.hasNature("org.eclipse.jdt.core.javanature");
+ } catch (CoreException e) {
+ return false;
+ }
+ }
+
public static boolean hasNature (IProject project) {
try {
return project.isOpen () && project.hasNature(NATURE_ID);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
return false;
}
}
@@ -105,7 +115,7 @@ public static void removeNature (IProject project) {
try {
description = project.getDescription();
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
return;
}
@@ -123,7 +133,7 @@ public static void removeNature (IProject project) {
try {
project.setDescription(description, null);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/StringLiteralAuditor.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java
similarity index 53%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/StringLiteralAuditor.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java
index 11ef0200..255ae573 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/StringLiteralAuditor.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/StringLiteralAuditor.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder;
+package org.eclipselabs.tapiji.tools.core.builder;
import java.util.ArrayList;
import java.util.Arrays;
@@ -12,104 +12,112 @@
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.IConfigurationElement;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
+import org.eclipselabs.tapiji.tools.core.Activator;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.builder.analyzer.RBAuditor;
+import org.eclipselabs.tapiji.tools.core.builder.analyzer.ResourceBundleDetectionVisitor;
+import org.eclipselabs.tapiji.tools.core.builder.analyzer.ResourceFinder;
+import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor;
+import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
+import org.eclipselabs.tapiji.tools.core.extensions.IMarkerConstants;
+import org.eclipselabs.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
-import at.ac.tuwien.inso.eclipse.i18n.builder.analyzer.RBAuditor;
-import at.ac.tuwien.inso.eclipse.i18n.builder.analyzer.ResourceBundleDetectionVisitor;
-import at.ac.tuwien.inso.eclipse.i18n.builder.analyzer.ResourceFinder;
-import at.ac.tuwien.inso.eclipse.i18n.extensions.I18nResourceAuditor;
-import at.ac.tuwien.inso.eclipse.i18n.extensions.ILocation;
-import at.ac.tuwien.inso.eclipse.i18n.extensions.IMarkerConstants;
-import at.ac.tuwien.inso.eclipse.i18n.model.exception.NoSuchResourceAuditorException;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.util.EditorUtils;
public class StringLiteralAuditor extends IncrementalProjectBuilder {
public static final String BUILDER_ID = Activator.PLUGIN_ID
- + ".stringLiteralAuditor";
-
+ + ".I18NBuilder";
+
private static I18nResourceAuditor[] resourceAuditors;
+ private static Set<String> supportedFileEndings;
static {
List<I18nResourceAuditor> auditors = new ArrayList<I18nResourceAuditor>();
+ supportedFileEndings = new HashSet<String>();
// init default auditors
auditors.add(new RBAuditor());
-
+
// lookup registered auditor extensions
- IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID);
-
+ IConfigurationElement[] config = Platform.getExtensionRegistry()
+ .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID);
+
try {
for (IConfigurationElement e : config) {
- auditors.add((I18nResourceAuditor)e.createExecutableExtension("class"));
+ I18nResourceAuditor a = (I18nResourceAuditor) e.createExecutableExtension("class");
+ auditors.add(a);
+ supportedFileEndings.addAll(Arrays.asList(a.getFileEndings()));
}
} catch (CoreException ex) {
- ex.printStackTrace();
+ Logger.logError(ex);
}
-
- resourceAuditors = auditors.toArray(new I18nResourceAuditor[auditors.size()]);
+
+ resourceAuditors = auditors.toArray(new I18nResourceAuditor[auditors
+ .size()]);
+ }
+
+ public StringLiteralAuditor() {
}
-
- public StringLiteralAuditor() { }
- public static I18nResourceAuditor getI18nAuditorByContext(String contextId) throws NoSuchResourceAuditorException {
+ public static I18nResourceAuditor getI18nAuditorByContext(String contextId)
+ throws NoSuchResourceAuditorException {
for (I18nResourceAuditor auditor : resourceAuditors) {
if (auditor.getContextId().equals(contextId))
return auditor;
}
throw new NoSuchResourceAuditorException();
}
-
- private Set<String> getSupportedFileExt () {
- // TODO memorize
-
- Set<String> ext = new HashSet<String> ();
- for (I18nResourceAuditor ra : resourceAuditors) {
- for (String ending : ra.getFileEndings())
- ext.add(ending);
- }
- return ext;
+
+ private Set<String> getSupportedFileExt() {
+ return supportedFileEndings;
}
-
- public static boolean isResourceAuditable (IResource resource, Set<String> supportedExtensions) {
+
+ public static boolean isResourceAuditable(IResource resource,
+ Set<String> supportedExtensions) {
for (String ext : supportedExtensions) {
- if (resource.getType() == IResource.FILE && !resource.isDerived() &&
- (resource.getFileExtension().equalsIgnoreCase(ext))) {
+ if (resource.getType() == IResource.FILE && !resource.isDerived()
+ && (resource.getFileExtension().equalsIgnoreCase(ext))) {
return true;
}
}
return false;
}
-
+
@Override
- protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
+ protected IProject[] build(final int kind, Map args, IProgressMonitor monitor)
throws CoreException {
- // TODO: progress monitor
- // TODO: 553 - IWorkspaceRunnable
+ ResourcesPlugin.getWorkspace().run(
+ new IWorkspaceRunnable() {
+ public void run(IProgressMonitor monitor) throws CoreException {
+ if (kind == FULL_BUILD) {
+ fullBuild(monitor);
+ } else {
+ // only perform audit if the resource deta is not empty
+ IResourceDelta resDelta = getDelta(getProject());
- if (kind == FULL_BUILD) {
- fullBuild(monitor);
- } else {
- // only perform audit if the resource deta is not empty
- IResourceDelta resDelta = getDelta(getProject());
+ if (resDelta == null)
+ return;
- if (resDelta == null)
- return null;
+ if (resDelta.getAffectedChildren() == null)
+ return;
- if (resDelta.getAffectedChildren() == null)
- return null;
-
- incrementalBuild(monitor, resDelta);
- }
+ incrementalBuild(monitor, resDelta);
+ }
+ }
+ },
+ monitor);
return null;
}
@@ -121,20 +129,22 @@ private void incrementalBuild(IProgressMonitor monitor,
ResourceFinder csrav = new ResourceFinder(getSupportedFileExt());
resDelta.accept(csrav);
auditResources(csrav.getResources(), monitor, getProject());
-
+
// check if a resource bundle has been added or deleted
// TODO check only ADD and DELETE deltas
- resDelta.accept(new ResourceBundleDetectionVisitor(ResourceBundleManager.getManager(getProject())));
+ resDelta.accept(new ResourceBundleDetectionVisitor(
+ ResourceBundleManager.getManager(getProject())));
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
-
- public void buildResource (IResource resource, IProgressMonitor monitor) {
+
+ public void buildResource(IResource resource, IProgressMonitor monitor) {
if (isResourceAuditable(resource, getSupportedFileExt())) {
List<IResource> resources = new ArrayList<IResource>();
resources.add(resource);
- // TODO: create instance of progressmonitor and hand it over to auditResources
+ // TODO: create instance of progressmonitor and hand it over to
+ // auditResources
auditResources(resources, monitor, getProject());
}
}
@@ -144,14 +154,15 @@ public void buildProject(IProgressMonitor monitor, IProject proj) {
ResourceFinder csrav = new ResourceFinder(getSupportedFileExt());
proj.accept(csrav);
auditResources(csrav.getResources(), monitor, proj);
-
+
// check if a resource bundle has been added or deleted
- proj.accept(new ResourceBundleDetectionVisitor(ResourceBundleManager.getManager(proj)));
+ proj.accept(new ResourceBundleDetectionVisitor(
+ ResourceBundleManager.getManager(proj)));
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
-
+
private void fullBuild(IProgressMonitor monitor) {
buildProject(monitor, getProject());
}
@@ -163,58 +174,98 @@ private void auditResources(List<IResource> resources,
if (monitor == null) {
monitor = new NullProgressMonitor();
}
-
- monitor.beginTask("Audit Resources for Internationalization problems", work);
-
+
+ monitor.beginTask("Audit resource file for Internationalization problems",
+ work);
+
for (IResource resource : resources) {
- if(monitor.isCanceled())
+ monitor.subTask("'" + resource.getFullPath().toOSString() + "'");
+ if (monitor.isCanceled())
throw new OperationCanceledException();
-
+
if (!EditorUtils.deleteAuditMarkersForResource(resource))
continue;
if (ResourceBundleManager.isResourceExcluded(resource))
continue;
-
+
for (I18nResourceAuditor ra : resourceAuditors) {
try {
+ if (monitor.isCanceled()) {
+ monitor.done();
+ break;
+ }
+
if (ra.isResourceOfType(resource)) {
ra.audit(resource);
-
- 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) {
- System.out.println ("Error during auditing resource: " + resource.getFullPath());
+ Logger.logError("Error during auditing '" + resource.getFullPath() + "'", e);
}
}
-
+
if (monitor != null)
monitor.worked(1);
}
+
+ for (I18nResourceAuditor ra : resourceAuditors) {
+ 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);
+ }
+ }
monitor.done();
}
@@ -237,7 +288,8 @@ protected void clean(IProgressMonitor monitor) throws CoreException {
}
public static void addBuilderToProject(IProject project) {
- System.out.println("addBuilderToProject");
+ Logger.logInfo("Internationalization-Builder registered for '" + project.getName() + "'");
+
// Only for open projects
if (!project.isOpen())
return;
@@ -246,7 +298,7 @@ public static void addBuilderToProject(IProject project) {
try {
description = project.getDescription();
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
return;
}
@@ -269,7 +321,7 @@ public static void addBuilderToProject(IProject project) {
try {
project.setDescription(description, null);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
@@ -277,19 +329,19 @@ public static void removeBuilderFromProject(IProject project) {
// Only for open projects
if (!project.isOpen())
return;
-
+
try {
project.deleteMarkers(EditorUtils.MARKER_ID, false,
IResource.DEPTH_INFINITE);
} catch (CoreException e1) {
- e1.printStackTrace();
+ Logger.logError(e1);
}
IProjectDescription description = null;
try {
description = project.getDescription();
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
return;
}
@@ -314,7 +366,7 @@ public static void removeBuilderFromProject(IProject project) {
try {
project.setDescription(description, null);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/ViolationResolutionGenerator.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java
similarity index 74%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/ViolationResolutionGenerator.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java
index f70e3193..323fc889 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/ViolationResolutionGenerator.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/ViolationResolutionGenerator.java
@@ -1,13 +1,13 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder;
+package org.eclipselabs.tapiji.tools.core.builder;
import java.util.List;
import org.eclipse.core.resources.IMarker;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.IMarkerResolutionGenerator2;
+import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor;
+import org.eclipselabs.tapiji.tools.core.model.exception.NoSuchResourceAuditorException;
-import at.ac.tuwien.inso.eclipse.i18n.extensions.I18nResourceAuditor;
-import at.ac.tuwien.inso.eclipse.i18n.model.exception.NoSuchResourceAuditorException;
public class ViolationResolutionGenerator implements IMarkerResolutionGenerator2 {
@@ -23,7 +23,7 @@ public IMarkerResolution[] getResolutions(IMarker marker) {
// find resolution generator for the given context
try {
I18nResourceAuditor auditor = StringLiteralAuditor.getI18nAuditorByContext(contextId);
- List<IMarkerResolution> resolutions = auditor.getMarkerResolutions(marker, marker.getAttribute("cause", -1));
+ List<IMarkerResolution> resolutions = auditor.getMarkerResolutions(marker);
return resolutions.toArray(new IMarkerResolution[resolutions.size()]);
} catch (NoSuchResourceAuditorException e) {}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/RBAuditor.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java
similarity index 74%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/RBAuditor.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java
index 047dd847..187bc2c9 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/RBAuditor.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/RBAuditor.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder.analyzer;
+package org.eclipselabs.tapiji.tools.core.builder.analyzer;
import java.util.ArrayList;
import java.util.List;
@@ -6,10 +6,10 @@
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.ui.IMarkerResolution;
+import org.eclipselabs.tapiji.tools.core.extensions.I18nResourceAuditor;
+import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.extensions.I18nResourceAuditor;
-import at.ac.tuwien.inso.eclipse.i18n.extensions.ILocation;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
public class RBAuditor extends I18nResourceAuditor {
@@ -44,8 +44,7 @@ public String getContextId() {
}
@Override
- public List<IMarkerResolution> getMarkerResolutions(IMarker marker,
- int cause) {
+ public List<IMarkerResolution> getMarkerResolutions(IMarker marker) {
return null;
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/ResourceBundleDetectionVisitor.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
similarity index 75%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/ResourceBundleDetectionVisitor.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
index a9aaa2e2..5ad9daa7 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/ResourceBundleDetectionVisitor.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceBundleDetectionVisitor.java
@@ -1,13 +1,14 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder.analyzer;
+package org.eclipselabs.tapiji.tools.core.builder.analyzer;
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;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.util.ResourceUtils;
public class ResourceBundleDetectionVisitor implements IResourceVisitor,
IResourceDeltaVisitor {
@@ -22,7 +23,7 @@ public ResourceBundleDetectionVisitor(ResourceBundleManager manager) {
public boolean visit(IResource resource) throws CoreException {
try {
if (ResourceUtils.isResourceBundle(resource)) {
- System.out.println("resource bundle found: " + resource.getName());
+ Logger.logInfo("Loading Resource-Bundle file '" + resource.getName() + "'");
if (!ResourceBundleManager.isResourceExcluded(resource))
manager.addBundleResource(resource);
return false;
@@ -43,5 +44,5 @@ public boolean visit(IResourceDelta delta) throws CoreException {
} else
return true;
}
-
+
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/ResourceFinder.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java
similarity index 76%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/ResourceFinder.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java
index 4920ca0b..98e0af7b 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/analyzer/ResourceFinder.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/analyzer/ResourceFinder.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder.analyzer;
+package org.eclipselabs.tapiji.tools.core.builder.analyzer;
import java.util.ArrayList;
import java.util.List;
@@ -9,8 +9,9 @@
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.runtime.CoreException;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
-import at.ac.tuwien.inso.eclipse.i18n.builder.StringLiteralAuditor;
public class ResourceFinder implements IResourceVisitor,
IResourceDeltaVisitor {
@@ -26,7 +27,7 @@ public ResourceFinder(Set<String> ext) {
@Override
public boolean visit(IResource resource) throws CoreException {
if (StringLiteralAuditor.isResourceAuditable(resource, supportedExtensions)) {
- System.out.println("audit necessary for " + resource.getName());
+ Logger.logInfo("Audit necessary for resource '" + resource.getFullPath().toOSString() + "'");
javaResources.add(resource);
return false;
} else
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/CreateResourceBundle.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
similarity index 89%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/CreateResourceBundle.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
index 988ce315..ae50a221 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/CreateResourceBundle.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundle.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder.quickfix;
+package org.eclipselabs.tapiji.tools.core.builder.quickfix;
import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
@@ -22,11 +22,11 @@
import org.eclipse.ui.IMarkerResolution2;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.wizards.IWizardDescriptor;
-
-import at.ac.tuwien.inso.eclipse.i18n.builder.StringLiteralAuditor;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.util.ResourceUtils;
-import at.ac.tuwien.inso.eclipse.rbe.ui.wizards.IResourceBundleWizard;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
+import org.eclipselabs.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard;
public class CreateResourceBundle implements ICompletionProposal,
IMarkerResolution2 {
@@ -163,18 +163,18 @@ private void runAction () {
textFileBuffer.commit(null, false);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
} finally {
try {
bufferManager.disconnect(path, null);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
}
}
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/CreateResourceBundleEntry.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundleEntry.java
similarity index 82%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/CreateResourceBundleEntry.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundleEntry.java
index 280cdb0a..8434f6cd 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/CreateResourceBundleEntry.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/CreateResourceBundleEntry.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder.quickfix;
+package org.eclipselabs.tapiji.tools.core.builder.quickfix;
import java.util.List;
import java.util.Locale;
@@ -16,10 +16,11 @@
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IMarkerResolution2;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
-import at.ac.tuwien.inso.eclipse.i18n.builder.StringLiteralAuditor;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.CreateResourceBundleEntryDialog;
public class CreateResourceBundleEntry implements IMarkerResolution2 {
@@ -70,13 +71,13 @@ public void run(IMarker marker) {
if (dialog.open() != InputDialog.OK)
return;
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
} finally {
try {
(new StringLiteralAuditor()).buildResource(resource, null);
bufferManager.disconnect(path, null);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/IncludeResource.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java
similarity index 90%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/IncludeResource.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java
index 92b307aa..85d59483 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/builder/quickfix/IncludeResource.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/builder/quickfix/IncludeResource.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.builder.quickfix;
+package org.eclipselabs.tapiji.tools.core.builder.quickfix;
import java.util.Set;
@@ -11,8 +11,8 @@
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
public class IncludeResource implements IMarkerResolution2 {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java
new file mode 100644
index 00000000..fc35d4c4
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/I18nResourceAuditor.java
@@ -0,0 +1,97 @@
+package org.eclipselabs.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 {
+ /**
+ * 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/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java
new file mode 100644
index 00000000..7d567598
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/ILocation.java
@@ -0,0 +1,50 @@
+package org.eclipselabs.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/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/IMarkerConstants.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java
similarity index 76%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/IMarkerConstants.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java
index 47875085..19e24e57 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/extensions/IMarkerConstants.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/extensions/IMarkerConstants.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.extensions;
+package org.eclipselabs.tapiji.tools.core.extensions;
public interface IMarkerConstants {
public static final int CAUSE_BROKEN_REFERENCE = 0;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java
new file mode 100644
index 00000000..576d65af
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceBundleChangedListener.java
@@ -0,0 +1,9 @@
+package org.eclipselabs.tapiji.tools.core.model;
+
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+
+public interface IResourceBundleChangedListener {
+
+ public void resourceBundleChanged (ResourceBundleChangedEvent event);
+
+}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceDescriptor.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java
similarity index 84%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceDescriptor.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java
index 7209b189..8fda62ba 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/IResourceDescriptor.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceDescriptor.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model;
+package org.eclipselabs.tapiji.tools.core.model;
public interface IResourceDescriptor {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java
new file mode 100644
index 00000000..881cacb5
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/IResourceExclusionListener.java
@@ -0,0 +1,9 @@
+package org.eclipselabs.tapiji.tools.core.model;
+
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceExclusionEvent;
+
+public interface IResourceExclusionListener {
+
+ public void exclusionChanged(ResourceExclusionEvent event);
+
+}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/ResourceDescriptor.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java
similarity index 91%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/ResourceDescriptor.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java
index a5af3e0e..32fc17f9 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/ResourceDescriptor.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/ResourceDescriptor.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model;
+package org.eclipselabs.tapiji.tools.core.model;
import org.eclipse.core.resources.IResource;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/SLLocation.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java
similarity index 77%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/SLLocation.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java
index ebb583c5..cb633c54 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/SLLocation.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/SLLocation.java
@@ -1,10 +1,10 @@
-package at.ac.tuwien.inso.eclipse.i18n.model;
+package org.eclipselabs.tapiji.tools.core.model;
import java.io.Serializable;
import org.eclipse.core.resources.IFile;
+import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-import at.ac.tuwien.inso.eclipse.i18n.extensions.ILocation;
public class SLLocation implements Serializable, ILocation {
@@ -13,7 +13,7 @@ public class SLLocation implements Serializable, ILocation {
private int startPos = -1;
private int endPos = -1;
private String literal;
- private Object data;
+ private Serializable data;
public SLLocation(IFile file, int startPos, int endPos, String literal) {
super();
@@ -43,10 +43,10 @@ public void setEndPos(int endPos) {
public String getLiteral() {
return literal;
}
- public Object getData () {
+ public Serializable getData () {
return data;
}
- public void setData (Object data) {
+ public void setData (Serializable data) {
this.data = data;
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/exception/NoSuchResourceAuditorException.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
similarity index 51%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/exception/NoSuchResourceAuditorException.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
index 6697f594..08f79a7e 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/exception/NoSuchResourceAuditorException.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model.exception;
+package org.eclipselabs.tapiji.tools.core.model.exception;
public class NoSuchResourceAuditorException extends Exception {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/exception/ResourceBundleException.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java
similarity index 77%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/exception/ResourceBundleException.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java
index 23e6024d..93b43daf 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/exception/ResourceBundleException.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/exception/ResourceBundleException.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model.exception;
+package org.eclipselabs.tapiji.tools.core.model.exception;
public class ResourceBundleException extends Exception {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleChangedEvent.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
similarity index 89%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleChangedEvent.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
index 738f9d82..73d90d42 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleChangedEvent.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model.manager;
+package org.eclipselabs.tapiji.tools.core.model.manager;
import org.eclipse.core.resources.IProject;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java
new file mode 100644
index 00000000..c275308e
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleDetector.java
@@ -0,0 +1,5 @@
+package org.eclipselabs.tapiji.tools.core.model.manager;
+
+public class ResourceBundleDetector {
+
+}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleManager.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java
similarity index 91%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleManager.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java
index 50e7498a..b754e220 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceBundleManager.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceBundleManager.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model.manager;
+package org.eclipselabs.tapiji.tools.core.model.manager;
import java.io.FileReader;
import java.io.FileWriter;
@@ -30,20 +30,21 @@
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.XMLMemento;
-
-import at.ac.tuwien.inso.eclipse.i18n.builder.StringLiteralAuditor;
-import at.ac.tuwien.inso.eclipse.i18n.builder.analyzer.ResourceBundleDetectionVisitor;
-import at.ac.tuwien.inso.eclipse.i18n.model.IResourceBundleChangedListener;
-import at.ac.tuwien.inso.eclipse.i18n.model.IResourceDescriptor;
-import at.ac.tuwien.inso.eclipse.i18n.model.IResourceExclusionListener;
-import at.ac.tuwien.inso.eclipse.i18n.model.ResourceDescriptor;
-import at.ac.tuwien.inso.eclipse.i18n.model.exception.ResourceBundleException;
-import at.ac.tuwien.inso.eclipse.i18n.util.EditorUtils;
-import at.ac.tuwien.inso.eclipse.i18n.util.FileUtils;
-import at.ac.tuwien.inso.eclipse.i18n.util.ResourceUtils;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor;
+import org.eclipselabs.tapiji.tools.core.builder.analyzer.ResourceBundleDetectionVisitor;
+import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipselabs.tapiji.tools.core.model.IResourceDescriptor;
+import org.eclipselabs.tapiji.tools.core.model.IResourceExclusionListener;
+import org.eclipselabs.tapiji.tools.core.model.ResourceDescriptor;
+import org.eclipselabs.tapiji.tools.core.model.exception.ResourceBundleException;
+import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
+import org.eclipselabs.tapiji.tools.core.util.FileUtils;
+import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup;
import com.essiembre.eclipse.rbe.api.BundleFactory;
import com.essiembre.eclipse.rbe.api.PropertiesGenerator;
@@ -403,12 +404,8 @@ public static Set<IProject> getAllSupportedProjects () {
Set<IProject> projs = new HashSet<IProject>();
for (IProject p : projects) {
- try {
- if (p.hasNature(StringLiteralAuditor.BUILDER_ID))
- projs.add(p);
- } catch (CoreException e) {
- //e.printStackTrace();
- }
+ if (InternationalizationNature.hasNature(p))
+ projs.add(p);
}
return projs;
}
@@ -427,7 +424,7 @@ public String getKeyHoverString(String rbName, String key) {
Locale l = entry.getBundle().getLocale();
String value = entry.getValue();
hoverText += "<b><i>" + (!(l.getDisplayName().equals("")) ? l.getDisplayName() : "Default") + "</i></b><br/>" +
- value + "<br/><br/>";
+ value.replace("\n", "<br/>") + "<br/><br/>";
}
return hoverText + "</body></html>";
@@ -489,7 +486,7 @@ public void excludeResource (IResource res, IProgressMonitor monitor) {
@Override
public boolean visit(IResource resource) throws CoreException {
- System.out.println (" -> excluding Resource " + resource.getName());
+ Logger.logInfo("Excluding resource '" + resource.getFullPath().toOSString() + "'");
resourceSubTree.add(resource);
return true;
}
@@ -504,12 +501,12 @@ public boolean visit(IResource resource) throws CoreException {
monitor.worked(1);
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
} finally {
monitor.done();
}
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
@@ -550,12 +547,12 @@ public boolean visit(IResource resource) throws CoreException {
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
} finally {
monitor.done();
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
}
(new StringLiteralAuditor()).buildResource(res, null);
@@ -754,7 +751,7 @@ public void addResourceBundleEntry(String resourceBundleId, String key,
editorContent);
// (new StringLiteralAuditor()).buildProject(null, this.getProject());
} catch (CoreException ce) {
- ce.printStackTrace();
+ Logger.logError(ce);
} catch (OperationCanceledException oce) {
// do nothing
}
@@ -781,7 +778,7 @@ public void saveResourceBundle (String resourceBundleId, IBundleGroup newBundleG
FileUtils.saveTextFile(this.getResourceBundleFile(resourceBundleId, b.getLocale()),
editorContent);
} catch (CoreException ce) {
- ce.printStackTrace();
+ Logger.logError(ce);
} catch (OperationCanceledException oce) {
}
}
@@ -814,7 +811,7 @@ public void removeResourceBundleEntry (String resourceBundleId, List<String> key
FileUtils.saveTextFile(this.getResourceBundleFile(resourceBundleId, locale),
editorContent);
} catch (CoreException ce) {
- ce.printStackTrace();
+ Logger.logError(ce);
} catch (OperationCanceledException oce) {
// do nothing
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceExclusionEvent.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
similarity index 85%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceExclusionEvent.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
index 3c40e55e..0cda211c 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/manager/ResourceExclusionEvent.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/manager/ResourceExclusionEvent.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model.manager;
+package org.eclipselabs.tapiji.tools.core.model.manager;
import java.util.Collection;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/view/MessagesViewState.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java
similarity index 95%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/view/MessagesViewState.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java
index a2f0183a..9f6cde42 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/view/MessagesViewState.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/view/MessagesViewState.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model.view;
+package org.eclipselabs.tapiji.tools.core.model.view;
import java.util.ArrayList;
import java.util.List;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/view/SortInfo.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java
similarity index 91%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/view/SortInfo.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java
index 54192aaa..cc521b9f 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/model/view/SortInfo.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/model/view/SortInfo.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.model.view;
+package org.eclipselabs.tapiji.tools.core.model.view;
import java.util.List;
import java.util.Locale;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/decorators/ExcludedResource.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java
similarity index 73%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/decorators/ExcludedResource.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java
index 071a4e68..e0b12ca0 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/decorators/ExcludedResource.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.decorators;
+package org.eclipselabs.tapiji.tools.core.ui.decorators;
import java.util.ArrayList;
import java.util.List;
@@ -6,17 +6,20 @@
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;
+import org.eclipselabs.tapiji.tools.core.Activator;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipselabs.tapiji.tools.core.model.IResourceExclusionListener;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceExclusionEvent;
+import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-import at.ac.tuwien.inso.eclipse.i18n.builder.InternationalizationNature;
-import at.ac.tuwien.inso.eclipse.i18n.model.IResourceExclusionListener;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceExclusionEvent;
-import at.ac.tuwien.inso.eclipse.i18n.util.ImageUtils;
-import at.ac.tuwien.inso.eclipse.i18n.util.OverlayIcon;
public class ExcludedResource implements ILabelDecorator,
IResourceExclusionListener {
@@ -44,7 +47,7 @@ public boolean decorate(Object element) {
needsDecoration = true;
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
return needsDecoration;
@@ -80,7 +83,9 @@ public void exclusionChanged(ResourceExclusionEvent event) {
@Override
public Image decorateImage(Image image, Object element) {
if (decorate(element)) {
- OverlayIcon overlayIcon = new OverlayIcon(image, OVERLAY_IMAGE_OFF, OverlayIcon.TOP_RIGHT);
+ DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(image,
+ Activator.getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF),
+ IDecoration.TOP_RIGHT);
return overlayIcon.createImage();
} else {
return image;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/CreateResourceBundleEntryDialog.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
similarity index 92%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/CreateResourceBundleEntryDialog.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
index f0ac7a19..dc3b664a 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/CreateResourceBundleEntryDialog.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.dialogs;
+package org.eclipselabs.tapiji.tools.core.ui.dialogs;
import java.util.Collection;
import java.util.Locale;
@@ -21,11 +21,12 @@
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.model.exception.ResourceBundleException;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.util.LocaleUtils;
+import org.eclipselabs.tapiji.tools.core.util.ResourceUtils;
-import at.ac.tuwien.inso.eclipse.i18n.model.exception.ResourceBundleException;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.util.LocaleUtils;
-import at.ac.tuwien.inso.eclipse.i18n.util.ResourceUtils;
public class CreateResourceBundleEntryDialog extends TitleAreaDialog {
@@ -60,7 +61,7 @@ public CreateResourceBundleEntryDialog(Shell parentShell,
super(parentShell);
this.manager = manager;
this.availableBundles = manager.getResourceBundleNames();
- this.selectedKey = preselectedKey;
+ this.selectedKey = preselectedKey != null ? preselectedKey.trim() : preselectedKey;
this.selectedDefaultText = preselectedMessage;
this.selectedRB = preselectedBundle;
this.selectedLocale = preselectedLocale;
@@ -288,7 +289,7 @@ protected void okPressed() {
try {
manager.addResourceBundleEntry (selectedRB, selectedKey, locale, selectedDefaultText);
} catch (ResourceBundleException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/DialogFactory.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/DialogFactory.java
new file mode 100644
index 00000000..d69aef76
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/DialogFactory.java
@@ -0,0 +1,5 @@
+package org.eclipselabs.tapiji.tools.core.ui.dialogs;
+
+public class DialogFactory {
+
+}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/GenerateBundleAccessorDialog.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
similarity index 96%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/GenerateBundleAccessorDialog.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
index 96ad0f42..389121ba 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/GenerateBundleAccessorDialog.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.dialogs;
+package org.eclipselabs.tapiji.tools.core.ui.dialogs;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/InsertResourceBundleReferenceDialog.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/InsertResourceBundleReferenceDialog.java
similarity index 93%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/InsertResourceBundleReferenceDialog.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/InsertResourceBundleReferenceDialog.java
index b539cfe1..06aa242b 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/InsertResourceBundleReferenceDialog.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/InsertResourceBundleReferenceDialog.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.dialogs;
+package org.eclipselabs.tapiji.tools.core.ui.dialogs;
import java.util.Collection;
import java.util.Iterator;
@@ -22,12 +22,12 @@
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.ResourceSelector;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipselabs.tapiji.tools.core.util.LocaleUtils;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.ResourceSelector;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.event.ResourceSelectionEvent;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.listener.IResourceSelectionListener;
-import at.ac.tuwien.inso.eclipse.i18n.util.LocaleUtils;
public class InsertResourceBundleReferenceDialog extends TitleAreaDialog {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/ResourceBundleSelectionDialog.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
similarity index 89%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/ResourceBundleSelectionDialog.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
index 82427734..5d73db2e 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/dialogs/ResourceBundleSelectionDialog.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.dialogs;
+package org.eclipselabs.tapiji.tools.core.ui.dialogs;
import java.util.List;
@@ -10,9 +10,9 @@
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.ListDialog;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.util.ImageUtils;
public class ResourceBundleSelectionDialog extends ListDialog {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/filters/PropertiesFileFilter.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
similarity index 88%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/filters/PropertiesFileFilter.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
index 57a94b29..cf92e76f 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/filters/PropertiesFileFilter.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.filters;
+package org.eclipselabs.tapiji.tools.core.ui.filters;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.Viewer;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java
new file mode 100644
index 00000000..8d6e57cd
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java
@@ -0,0 +1,5 @@
+package org.eclipselabs.tapiji.tools.core.ui.markers;
+
+public class StringLiterals {
+
+}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/menus/InternationalizationMenu.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java
similarity index 83%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/menus/InternationalizationMenu.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java
index 13f3a3df..3cd08bbe 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/menus/InternationalizationMenu.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.menus;
+package org.eclipselabs.tapiji.tools.core.ui.menus;
import java.util.Collection;
import java.util.HashSet;
@@ -27,10 +27,10 @@
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;
+import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.ui.dialogs.GenerateBundleAccessorDialog;
-import at.ac.tuwien.inso.eclipse.i18n.builder.InternationalizationNature;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.GenerateBundleAccessorDialog;
public class InternationalizationMenu extends ContributionItem {
private boolean excludeMode = true;
@@ -38,11 +38,8 @@ public class InternationalizationMenu extends ContributionItem {
private MenuItem mnuToggleInt;
private MenuItem excludeResource;
- //private MenuItem generateAccessor;
- public InternationalizationMenu() {
- // TODO Auto-generated constructor stub
- }
+ public InternationalizationMenu() {}
public InternationalizationMenu(String id) {
super(id);
@@ -50,7 +47,8 @@ public InternationalizationMenu(String id) {
@Override
public void fill(Menu menu, int index) {
- if (getSelectedProjects().size() == 0)
+ if (getSelectedProjects().size() == 0 ||
+ !projectsSupported())
return;
// Toggle Internatinalization
@@ -63,22 +61,6 @@ public void widgetSelected(SelectionEvent e) {
}
});
-
- // Add Separator
- //new MenuItem (menu, SWT.SEPARATOR);
-
- // Generate Accessor
- /*generateAccessor = new MenuItem (menu, index);
- generateAccessor.setText("Generate Bundle-Accessor ...");
- generateAccessor.setEnabled(false);
- generateAccessor.addSelectionListener(new SelectionAdapter () {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- runGenRBAccessor();
- }
-
- });*/
// Exclude Resource
excludeResource = new MenuItem (menu, index+1);
@@ -170,6 +152,16 @@ private Collection<IProject> getSelectedProjects () {
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) {
@@ -214,13 +206,6 @@ private Collection<IResource> getSelectedResources () {
if (selection instanceof IStructuredSelection) {
for (Iterator<?> iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
Object elem = iter.next();
- /*if (!(elem instanceof IResource || elem instanceof IJavaElement)) {
- if (!(elem instanceof IAdaptable))
- continue;
- elem = ((IAdaptable) elem).getAdapter (IResource.class);
- if (!(elem instanceof IResource || elem instanceof IJavaElement))
- continue;
- }*/
if (elem instanceof IProject)
continue;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/MessagesView.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java
similarity index 94%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/MessagesView.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java
index 8ba3ed16..91b5f783 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/MessagesView.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview;
+package org.eclipselabs.tapiji.tools.core.ui.views.messagesview;
import java.util.ArrayList;
import java.util.List;
@@ -30,22 +30,23 @@
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
+import org.eclipselabs.tapiji.tools.core.Activator;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.model.view.MessagesViewState;
+import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree;
+import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
-import at.ac.tuwien.inso.eclipse.i18n.model.IResourceBundleChangedListener;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleChangedEvent;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.model.view.MessagesViewState;
-import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.ResourceBundleSelectionDialog;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.PropertyKeySelectionTree;
-import at.ac.tuwien.inso.eclipse.i18n.util.ImageUtils;
public class MessagesView extends ViewPart implements IResourceBundleChangedListener {
/**
* The ID of the view as specified by the extension.
*/
- public static final String ID = "at.ac.tuwien.inso.eclipse.i18n.views.MessagesView";
+ public static final String ID = "org.eclipselabs.tapiji.tools.core.views.MessagesView";
// View State
private IMemento memento;
@@ -241,7 +242,7 @@ protected void redrawTreeViewer () {
contributeToActionBars();
hookContextMenu();
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
}
parent.setRedraw(true);
parent.layout(true);
@@ -472,7 +473,7 @@ public void run() {
public void run() {
try {
redrawTreeViewer();
- } catch (Exception e) { e.printStackTrace(); }
+ } catch (Exception e) { Logger.logError(e); }
}
});
@@ -480,7 +481,7 @@ public void run() {
}).start();
}
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
}
\ No newline at end of file
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/ResourceBundleEntry.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
similarity index 92%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/ResourceBundleEntry.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
index 87913322..b86f66c2 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/ResourceBundleEntry.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview;
+package org.eclipselabs.tapiji.tools.core.ui.views.messagesview;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.viewers.ISelectionChangedListener;
@@ -10,8 +10,8 @@
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.PropertyKeySelectionTree;
public class ResourceBundleEntry extends ContributionItem implements
ISelectionChangedListener {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
similarity index 78%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
index b9723b5a..e9da5e5b 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview.dnd;
+package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd;
import java.util.Collection;
@@ -9,14 +9,14 @@
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TreeItem;
-
-import at.ac.tuwien.inso.eclipse.i18n.model.exception.ResourceBundleException;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider.ResKeyTreeContentProvider;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.model.exception.ResourceBundleException;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
import com.essiembre.eclipse.rbe.api.BundleFactory;
import com.essiembre.eclipse.rbe.api.ValuedKeyTreeItem;
@@ -63,7 +63,7 @@ private void addBundleEntry (final String keyPrefix,
if (removeOld) {
bundleGroup.removeKey(kti.getId());
}
- } catch (Exception e) { e.printStackTrace(); }
+ } catch (Exception e) { Logger.logError(e); }
}
@@ -106,14 +106,14 @@ public void run() {
try {
manager.saveResourceBundle(contentProvider.getBundleId(), bundleGroup);
} catch (ResourceBundleException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
target.refresh();
} else
event.detail = DND.DROP_NONE;
- } catch (Exception e) { e.printStackTrace(); }
+ } catch (Exception e) { Logger.logError(e); }
}
});
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/KeyTreeItemTransfer.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
similarity index 87%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
index 0c5982be..b1796f38 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview.dnd;
+package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -11,8 +11,8 @@
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.TransferData;
-
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
public class KeyTreeItemTransfer extends ByteArrayTransfer {
@@ -42,7 +42,7 @@ public void javaToNative(Object object, TransferData transferData) {
super.javaToNative(buffer, transferData);
} catch (IOException e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
@@ -53,7 +53,7 @@ public Object nativeToJava(TransferData transferData) {
try {
buffer = (byte[]) super.nativeToJava(transferData);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
buffer = null;
}
if (buffer == null)
@@ -69,7 +69,7 @@ public Object nativeToJava(TransferData transferData) {
//}
readIn.close();
} catch (Exception ex) {
- ex.printStackTrace();
+ Logger.logError(ex);
return null;
}
return terms.toArray(new IKeyTreeItem[terms.size()]);
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/MessagesDragSource.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
similarity index 85%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/MessagesDragSource.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
index d20359e6..57e5fdb7 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/MessagesDragSource.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java
@@ -1,11 +1,10 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview.dnd;
+package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd;
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 at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
public class MessagesDragSource implements DragSourceListener {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/MessagesDropTarget.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
similarity index 81%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/MessagesDropTarget.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
index 06c8239b..c0bb6e3d 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/views/messagesview/dnd/MessagesDropTarget.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview.dnd;
+package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.viewers.TreeViewer;
@@ -8,10 +8,9 @@
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TreeItem;
-
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.CreateResourceBundleEntryDialog;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IValuedKeyTreeItem;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IValuedKeyTreeItem;
public class MessagesDropTarget extends DropTargetAdapter {
private final TreeViewer target;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/MVTextTransfer.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java
similarity index 63%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/MVTextTransfer.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java
index abba0453..c0af7f62 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/MVTextTransfer.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets;
+package org.eclipselabs.tapiji.tools.core.ui.widgets;
import org.eclipse.swt.dnd.TextTransfer;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/PropertyKeySelectionTree.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
similarity index 88%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/PropertyKeySelectionTree.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
index 040a2215..e4a8b78b 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/PropertyKeySelectionTree.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets;
+package org.eclipselabs.tapiji.tools.core.ui.widgets;
import java.util.ArrayList;
@@ -47,28 +47,28 @@
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
-
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
-import at.ac.tuwien.inso.eclipse.i18n.model.IResourceBundleChangedListener;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleChangedEvent;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.model.view.SortInfo;
-import at.ac.tuwien.inso.eclipse.i18n.ui.dialogs.CreateResourceBundleEntryDialog;
-import at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview.dnd.KeyTreeItemDropTarget;
-import at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview.dnd.MessagesDragSource;
-import at.ac.tuwien.inso.eclipse.i18n.ui.views.messagesview.dnd.MessagesDropTarget;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.filter.ExactMatcher;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.filter.FuzzyMatcher;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider.ResKeyTreeContentProvider;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider.ResKeyTreeLabelProvider;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.sorter.ValuedKeyTreeItemSorter;
-import at.ac.tuwien.inso.eclipse.i18n.util.EditorUtils;
-import at.ac.tuwien.inso.eclipse.i18n.util.FileUtils;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.updater.IKeyTreeUpdater;
+import org.eclipselabs.tapiji.tools.core.Activator;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.model.view.SortInfo;
+import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog;
+import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.KeyTreeItemDropTarget;
+import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDragSource;
+import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDropTarget;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.ExactMatcher;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.FuzzyMatcher;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.sorter.ValuedKeyTreeItemSorter;
+import org.eclipselabs.tapiji.tools.core.util.EditorUtils;
+import org.eclipselabs.tapiji.tools.core.util.FileUtils;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.updater.IKeyTreeUpdater;
import com.essiembre.eclipse.rbe.api.BundleFactory;
import com.essiembre.eclipse.rbe.api.KeyTreeFactory;
@@ -584,7 +584,7 @@ public void deleteSelectedItems () {
try {
manager.removeResourceBundleEntry(getResourceBundle(), keys);
} catch (Exception ex) {
- ex.printStackTrace();
+ Logger.logError(ex);
}
}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/ResourceSelector.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java
similarity index 83%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/ResourceSelector.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java
index a88890a7..59d213ee 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/ResourceSelector.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets;
+package org.eclipselabs.tapiji.tools.core.ui.widgets;
import java.util.HashSet;
import java.util.Iterator;
@@ -18,17 +18,16 @@
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
-
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.event.ResourceSelectionEvent;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.listener.IResourceSelectionListener;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider.ResKeyTreeContentProvider;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider.ResKeyTreeLabelProvider;
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider.ValueKeyTreeLabelProvider;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.updater.IKeyTreeUpdater;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ValueKeyTreeLabelProvider;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.updater.IKeyTreeUpdater;
import com.essiembre.eclipse.rbe.api.KeyTreeFactory;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/event/ResourceSelectionEvent.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
similarity index 86%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/event/ResourceSelectionEvent.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
index 5d3a0621..349c385c 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/event/ResourceSelectionEvent.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.event;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.event;
public class ResourceSelectionEvent {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/ExactMatcher.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
similarity index 89%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/ExactMatcher.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
index c14e3f30..03636402 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/ExactMatcher.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java
@@ -1,12 +1,11 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.filter;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.filter;
import java.util.Locale;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
-
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IValuedKeyTreeItem;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IValuedKeyTreeItem;
public class ExactMatcher extends ViewerFilter {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/FilterInfo.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
similarity index 93%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/FilterInfo.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
index dbbd3825..cb02d50f 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/FilterInfo.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.filter;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.filter;
import java.util.ArrayList;
import java.util.HashMap;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/FuzzyMatcher.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
similarity index 87%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/FuzzyMatcher.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
index 8a80a0d0..fc7a3083 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/FuzzyMatcher.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java
@@ -1,11 +1,10 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.filter;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.filter;
import java.util.Locale;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
-
-import at.ac.tuwien.inso.eclipse.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
+import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer;
import com.essiembre.eclipse.rbe.api.AnalyzerFactory;
import com.essiembre.eclipse.rbe.api.ValuedKeyTreeItem;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/StringMatcher.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
similarity index 96%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/StringMatcher.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
index fbf38d0d..d48ea0e9 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/filter/StringMatcher.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.filter;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.filter;
import java.util.Vector;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
new file mode 100644
index 00000000..7cb6f96d
--- /dev/null
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java
@@ -0,0 +1,9 @@
+package org.eclipselabs.tapiji.tools.core.ui.widgets.listener;
+
+import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent;
+
+public interface IResourceSelectionListener {
+
+ public void selectionChanged (ResourceSelectionEvent e);
+
+}
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/KeyTreeContentProvider.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeContentProvider.java
similarity index 91%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/KeyTreeContentProvider.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeContentProvider.java
index 19b95527..f3524491 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/KeyTreeContentProvider.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeContentProvider.java
@@ -18,15 +18,14 @@
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
-
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
/**
* Content provider for key tree viewer.
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/KeyTreeLabelProvider.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
similarity index 92%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/KeyTreeLabelProvider.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
index bf24ce51..bf52c3f0 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/KeyTreeLabelProvider.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java
@@ -18,7 +18,7 @@
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ILabelProvider;
@@ -28,10 +28,9 @@
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
-
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
-import at.ac.tuwien.inso.eclipse.i18n.util.FontUtils;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.tools.core.Activator;
+import org.eclipselabs.tapiji.tools.core.util.FontUtils;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
/**
* Label provider for key tree viewer.
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/LightKeyTreeLabelProvider.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
similarity index 83%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/LightKeyTreeLabelProvider.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
index 61a16c58..b718f1c7 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/LightKeyTreeLabelProvider.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ResKeyTreeContentProvider.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
similarity index 84%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ResKeyTreeContentProvider.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
index 2f36b1d1..f0b24521 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ResKeyTreeContentProvider.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java
@@ -1,14 +1,14 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IValuedKeyTreeItem;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IValuedKeyTreeItem;
import com.essiembre.eclipse.rbe.api.ValuedKeyTreeItem;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ResKeyTreeLabelProvider.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
similarity index 87%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ResKeyTreeLabelProvider.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
index 57b95b16..52caad6a 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ResKeyTreeLabelProvider.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
import java.util.ArrayList;
import java.util.List;
@@ -11,13 +11,12 @@
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
-
-import at.ac.tuwien.inso.eclipse.i18n.ui.widgets.filter.FilterInfo;
-import at.ac.tuwien.inso.eclipse.i18n.util.FontUtils;
-import at.ac.tuwien.inso.eclipse.i18n.util.ImageUtils;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IValuedKeyTreeItem;
+import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.FilterInfo;
+import org.eclipselabs.tapiji.tools.core.util.FontUtils;
+import org.eclipselabs.tapiji.tools.core.util.ImageUtils;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IValuedKeyTreeItem;
import com.essiembre.eclipse.rbe.api.ValuedKeyTreeItem;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
similarity index 82%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ValueKeyTreeLabelProvider.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
index d89bbb40..d7bad038 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/provider/ValueKeyTreeLabelProvider.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.provider;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.provider;
import org.eclipse.jface.viewers.ITableColorProvider;
import org.eclipse.jface.viewers.ITableFontProvider;
@@ -6,10 +6,9 @@
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
-
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle;
-import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle;
+import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem;
public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
similarity index 85%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
index 49d8dd01..d4ff7d44 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java
@@ -1,13 +1,12 @@
-package at.ac.tuwien.inso.eclipse.i18n.ui.widgets.sorter;
+package org.eclipselabs.tapiji.tools.core.ui.widgets.sorter;
import java.util.Locale;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
-
-import at.ac.tuwien.inso.eclipse.i18n.model.view.SortInfo;
-import at.ac.tuwien.inso.eclipse.rbe.model.tree.IValuedKeyTreeItem;
+import org.eclipselabs.tapiji.tools.core.model.view.SortInfo;
+import org.eclipselabs.tapiji.translator.rbe.model.tree.IValuedKeyTreeItem;
import com.essiembre.eclipse.rbe.api.ValuedKeyTreeItem;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/EditorUtils.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java
similarity index 86%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/EditorUtils.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java
index 012fdf79..e5d060f5 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/EditorUtils.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/EditorUtils.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.util;
+package org.eclipselabs.tapiji.tools.core.util;
import java.text.MessageFormat;
@@ -8,9 +8,10 @@
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.ide.IDE;
+import org.eclipselabs.tapiji.tools.core.Activator;
+import org.eclipselabs.tapiji.tools.core.Logger;
+import org.eclipselabs.tapiji.tools.core.extensions.ILocation;
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
-import at.ac.tuwien.inso.eclipse.i18n.extensions.ILocation;
public class EditorUtils {
@@ -41,7 +42,7 @@ public static void openEditor (IWorkbenchPage page, IFile file, String editor) {
// TODO open resourcebundleeditor
IDE.openEditor(page, file, editor);
} catch (Exception e) {
- e.printStackTrace();
+ Logger.logError(e);
}
}
@@ -66,12 +67,11 @@ public static void reportToMarker(String string, ILocation problem, int cause, S
// TODO: init attributes
marker.setAttribute("stringLiteral", string);
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
return;
}
-
- System.out.println("WARNING: " + string + " (" + problem.getStartPos()
- + "," + problem.getEndPos() + ")");
+
+ Logger.logInfo(string);
}
public static boolean deleteAuditMarkersForResource(IResource resource) {
@@ -81,7 +81,7 @@ public static boolean deleteAuditMarkersForResource(IResource resource) {
IResource.DEPTH_INFINITE);
}
} catch (CoreException e) {
- e.printStackTrace();
+ Logger.logError(e);
return false;
}
return true;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/FileUtils.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java
similarity index 85%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/FileUtils.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java
index b99182ac..8d1ff250 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/FileUtils.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/FileUtils.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.util;
+package org.eclipselabs.tapiji.tools.core.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -10,8 +10,9 @@
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.OperationCanceledException;
+import org.eclipselabs.tapiji.tools.core.Activator;
+import org.eclipselabs.tapiji.tools.core.Logger;
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
public class FileUtils {
@@ -34,7 +35,7 @@ protected static String readFileAsString(File filePath) {
fileReader.close();
} catch (Exception e) {
// TODO log error output
- e.printStackTrace();
+ Logger.logError(e);
}
return content;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/FontUtils.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java
similarity index 93%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/FontUtils.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java
index cc3974e6..5dc4382a 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/FontUtils.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/FontUtils.java
@@ -1,12 +1,12 @@
-package at.ac.tuwien.inso.eclipse.i18n.util;
+package org.eclipselabs.tapiji.tools.core.util;
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.tools.core.Activator;
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
public class FontUtils {
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/ImageUtils.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java
similarity index 93%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/ImageUtils.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java
index f4672356..30437257 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/ImageUtils.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/ImageUtils.java
@@ -1,9 +1,9 @@
-package at.ac.tuwien.inso.eclipse.i18n.util;
+package org.eclipselabs.tapiji.tools.core.util;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
+import org.eclipselabs.tapiji.tools.core.Activator;
-import at.ac.tuwien.inso.eclipse.i18n.Activator;
/**
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/LocaleUtils.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java
similarity index 85%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/LocaleUtils.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java
index ec016577..6994f21e 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/LocaleUtils.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/LocaleUtils.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.util;
+package org.eclipselabs.tapiji.tools.core.util;
import java.util.Locale;
import java.util.Set;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/OverlayIcon.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java
similarity index 92%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/OverlayIcon.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java
index a76fcfe7..eec56b99 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/OverlayIcon.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/OverlayIcon.java
@@ -1,4 +1,4 @@
-package at.ac.tuwien.inso.eclipse.i18n.util;
+package org.eclipselabs.tapiji.tools.core.util;
import org.eclipse.jface.resource.CompositeImageDescriptor;
import org.eclipse.swt.graphics.Image;
diff --git a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/ResourceUtils.java b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java
similarity index 89%
rename from at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/ResourceUtils.java
rename to at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java
index 7dcc9499..004d599d 100644
--- a/at.ac.tuwien.inso.eclipse.i18n/src/at/ac/tuwien/inso/eclipse/i18n/util/ResourceUtils.java
+++ b/at.ac.tuwien.inso.eclipse.i18n/src/org/eclipselabs/tapiji/tools/core/util/ResourceUtils.java
@@ -1,8 +1,8 @@
-package at.ac.tuwien.inso.eclipse.i18n.util;
+package org.eclipselabs.tapiji.tools.core.util;
import org.eclipse.core.resources.IResource;
+import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager;
-import at.ac.tuwien.inso.eclipse.i18n.model.manager.ResourceBundleManager;
public class ResourceUtils {
|
fa63d0a22133e1b785f500a1268edc66a2c3f14a
|
drools
|
JBRULES-2849 workaround bug in JDK 5 concerning- alternatives in lookbehind assertions
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/lang/dsl/AntlrDSLMappingEntry.java b/drools-compiler/src/main/java/org/drools/lang/dsl/AntlrDSLMappingEntry.java
index e8575ecf7c4..1678803a4e0 100644
--- a/drools-compiler/src/main/java/org/drools/lang/dsl/AntlrDSLMappingEntry.java
+++ b/drools-compiler/src/main/java/org/drools/lang/dsl/AntlrDSLMappingEntry.java
@@ -71,7 +71,11 @@ public void setKeyPattern(final String keyPat) {
if ( !keyPattern.startsWith( "^" ) ) {
// making it start after a non word char or at line start
- keyPattern = "(?<=\\W|^)" + keyPattern;
+ // JDK 5 (java version 1.5.0_22) is buggy: doesn't handle alternatives within
+ // zero-width lookbehind assertions. As a workaround, we use an alternative of
+ // zero-width lookbehind assertions, slightly longer, but simpler than anything else.
+ // keyPattern = "(?<=\\W|^)" + keyPattern; // works in JDK >=6
+ keyPattern = "(?:(?<=^)|(?<=\\W))" + keyPattern;
}
// If the pattern ends with a pure variable whose pattern could create
diff --git a/drools-compiler/src/test/java/org/drools/lang/dsl/DSLMappingEntryTest.java b/drools-compiler/src/test/java/org/drools/lang/dsl/DSLMappingEntryTest.java
index 5d9c07fdc06..1329cf4a4e0 100755
--- a/drools-compiler/src/test/java/org/drools/lang/dsl/DSLMappingEntryTest.java
+++ b/drools-compiler/src/test/java/org/drools/lang/dsl/DSLMappingEntryTest.java
@@ -9,6 +9,10 @@
public class DSLMappingEntryTest extends TestCase {
+ // Due to a bug in JDK 5, a workaround for zero-widht lookbehind has to be used.
+ // JDK works correctly with "(?<=^|\\W)"
+ private static final String lookbehind = "(?:(?<=^)|(?<=\\W))";
+
protected void setUp() throws Exception {
super.setUp();
}
@@ -39,7 +43,7 @@ public void testPatternCalculation() throws IOException {
final String inputKey = "The Customer name is {name} and surname is {surname} and it has US$ 50,00 on his {pocket}";
final String inputValue = "Customer( name == \"{name}\", surname == \"{surname}\", money > $money )";
- final String expectedKeyP = "(?<=\\W|^)The\\s+Customer\\s+name\\s+is\\s+(.*?)\\s+and\\s+surname\\s+is\\s+(.*?)\\s+and\\s+it\\s+has\\s+US\\$\\s+50,00\\s+on\\s+his\\s+(.*?)$";
+ final String expectedKeyP = lookbehind + "The\\s+Customer\\s+name\\s+is\\s+(.*?)\\s+and\\s+surname\\s+is\\s+(.*?)\\s+and\\s+it\\s+has\\s+US\\$\\s+50,00\\s+on\\s+his\\s+(.*?)$";
final String expectedValP = "Customer( name == \"{name}\", surname == \"{surname}\", money > $money )";
final DSLMappingEntry entry = createEntry( inputKey,
@@ -59,7 +63,7 @@ public void testPatternCalculation2() throws IOException {
final String inputKey = "-name is {name}";
final String inputValue = "name == \"{name}\"";
- final String expectedKeyP = "(?<=\\W|^)-\\s*name\\s+is\\s+(.*?)$";
+ final String expectedKeyP = lookbehind + "-\\s*name\\s+is\\s+(.*?)$";
final String expectedValP = "name == \"{name}\"";
final DSLMappingEntry entry = createEntry( inputKey,
@@ -80,7 +84,7 @@ public void testPatternCalculation3() throws IOException {
final String inputKey = "- name is {name}";
final String inputValue = "name == \"{name}\"";
- final String expectedKeyP = "(?<=\\W|^)-\\s*name\\s+is\\s+(.*?)$";
+ final String expectedKeyP = lookbehind + "-\\s*name\\s+is\\s+(.*?)$";
final String expectedValP = "name == \"{name}\"";
final DSLMappingEntry entry = createEntry( inputKey,
@@ -173,7 +177,7 @@ public void testExpandWithBrackets() throws IOException {
DSLMappingEntry entry5 = this.createEntry( "When the credit rating is {rating:regex:\\d{3}}",
"applicant:Applicant(credit=={rating})" );
- assertEquals( "(?<=\\W|^)When\\s+the\\s+credit\\s+rating\\s+is\\s+(\\d{3})(?=\\W|$)",
+ assertEquals( lookbehind + "When\\s+the\\s+credit\\s+rating\\s+is\\s+(\\d{3})(?=\\W|$)",
entry5.getKeyPattern().toString() );
assertEquals( "applicant:Applicant(credit=={rating})",
entry5.getValuePattern() );
@@ -181,7 +185,7 @@ public void testExpandWithBrackets() throws IOException {
DSLMappingEntry entry6 = this.createEntry( "This is a sentence with line breaks",
"Cheese\\n(price == 10)" );
- assertEquals( "(?<=\\W|^)This\\s+is\\s+a\\s+sentence\\s+with\\s+line\\s+breaks(?=\\W|$)",
+ assertEquals( lookbehind + "This\\s+is\\s+a\\s+sentence\\s+with\\s+line\\s+breaks(?=\\W|$)",
entry6.getKeyPattern().toString() );
assertEquals( "Cheese\n(price == 10)",
entry6.getValuePattern());
@@ -189,14 +193,14 @@ public void testExpandWithBrackets() throws IOException {
DSLMappingEntry entry7 = this.createEntry( "Bedingung-\\#19-MKM4",
"eval ( $p.getTempVal(\"\\#UML-ATZ-1\") < $p.getZvUmlStfr() )" );
- assertEquals( "(?<=\\W|^)Bedingung-#19-MKM4(?=\\W|$)",
+ assertEquals( lookbehind + "Bedingung-#19-MKM4(?=\\W|$)",
entry7.getKeyPattern().toString() );
assertEquals( "eval ( $p.getTempVal(\"#UML-ATZ-1\") < $p.getZvUmlStfr() )",
entry7.getValuePattern());
DefaultExpander ex = makeExpander( entry1, entry2, entry3, entry4,
entry5, entry6, entry7 );
- StringBuilder sb = new StringBuilder( "rule x\n" + "when\n" );
+ StringBuilder sb = new StringBuilder( "rule x\n" ).append( "when\n" );
sb.append( "attr name is in [ 'Edson', 'Bob' ]" ).append( "\n" );
sb.append( "he (is) a $xx handsome man" ).append( "\n" );
diff --git a/drools-compiler/src/test/java/org/drools/lang/dsl/DSLTokenizedMappingFileTest.java b/drools-compiler/src/test/java/org/drools/lang/dsl/DSLTokenizedMappingFileTest.java
index 681dc64c446..47b02fbfc60 100644
--- a/drools-compiler/src/test/java/org/drools/lang/dsl/DSLTokenizedMappingFileTest.java
+++ b/drools-compiler/src/test/java/org/drools/lang/dsl/DSLTokenizedMappingFileTest.java
@@ -8,6 +8,11 @@
import junit.framework.TestCase;
public class DSLTokenizedMappingFileTest extends TestCase {
+
+ // Due to a bug in JDK 5, a workaround for zero-widht lookbehind has to be used.
+ // JDK works correctly with "(?<=^|\\W)"
+ private static final String lookbehind = "(?:(?<=^)|(?<=\\W))";
+
private DSLMappingFile file = null;
private final String filename = "test_metainfo.dsl";
@@ -62,7 +67,7 @@ public void testParseFileWithBrackets() {
entry.getSection() );
assertEquals( DSLMappingEntry.EMPTY_METADATA,
entry.getMetaData() );
- assertEquals( "(?<=\\W|^)ATTRIBUTE\\s+\"(.*?)\"\\s+IS\\s+IN\\s+[(.*?)](?=\\W|$)",
+ assertEquals( lookbehind + "ATTRIBUTE\\s+\"(.*?)\"\\s+IS\\s+IN\\s+[(.*?)](?=\\W|$)",
entry.getKeyPattern().toString() );
//Attribute( {attr} in ({list}) )
assertEquals( "Attribute( {attr} in ({list}) )",
@@ -97,7 +102,7 @@ public void testParseFileWithEscaptedBrackets() {
assertEquals( DSLMappingEntry.EMPTY_METADATA,
entry.getMetaData() );
- assertEquals( "(?<=\\W|^)ATTRIBUTE\\s+\"(.*?)\"\\s+IS\\s+IN\\s+\\[(.*?)\\](?=\\W|$)",
+ assertEquals( lookbehind + "ATTRIBUTE\\s+\"(.*?)\"\\s+IS\\s+IN\\s+\\[(.*?)\\](?=\\W|$)",
entry.getKeyPattern().toString() );
//Attribute( {attr} in ({list}) )
assertEquals( "Attribute( {attr} in ({list}) )",
@@ -166,7 +171,7 @@ public void testParseFileWithEscaptedEquals() {
entry.getSection() );
assertEquals( DSLMappingEntry.EMPTY_METADATA,
entry.getMetaData() );
- assertEquals( "(?<=\\W|^)something:\\=(.*?)$",
+ assertEquals( lookbehind + "something:\\=(.*?)$",
entry.getKeyPattern().toString() );
assertEquals( "Attribute( something == \"{value}\" )",
entry.getValuePattern() );
|
156c9987bf61d60b25226d08218bf26a766451de
|
Delta Spike
|
add tail to show all build results
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/buildall.sh b/deltaspike/buildall.sh
index 840fefbfa..038ed1c9c 100755
--- a/deltaspike/buildall.sh
+++ b/deltaspike/buildall.sh
@@ -31,3 +31,6 @@ mvn clean install -Ptomee-build-managed -Dtomee.version=1.6.0-SNAPSHOT -Dopenej
mvn clean install -Ptomee-build-managed -Dtomee.version=1.5.2 -Dopenejb.version=4.5.2 -Dopenejb.owb.version=1.1.8 | tee mvn-tomee_1_5_2.log
mvn clean install -Pjbossas-build-managed-7 | tee mvn-jbossas_7.log
+
+# and now for the result check
+tail mvn-*.log | less
|
02ffd6ae37a11cb0acc920bada87c994559d396b
|
drools
|
BZ-1044973 - Guided rule editor does not let the- user to set objects as a parameters for method calls that have objects super- type as a parameter--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/ActionCallMethodBuilder.java b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/ActionCallMethodBuilder.java
index 8a5938ec0a4..08156a0452e 100644
--- a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/ActionCallMethodBuilder.java
+++ b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/ActionCallMethodBuilder.java
@@ -116,16 +116,27 @@ private String getDataType( String param,
}
private MethodInfo getMethodInfo() {
- String variableType = boundParams.get( variable );
- if ( variableType != null ) {
- List<MethodInfo> methods = getMethodInfosForType( model,
- dmo,
- variableType );
- if ( methods != null ) {
- for ( MethodInfo method : methods ) {
- if ( method.getName().equals( methodName ) ) {
- return method;
+ String variableType = boundParams.get(variable);
+ if (variableType != null) {
+ List<MethodInfo> methods = getMethodInfosForType(model,
+ dmo,
+ variableType);
+ if (methods != null) {
+
+ ArrayList<MethodInfo> methodInfos = getMethodInfos(methodName, methods);
+
+ if (methodInfos.size() > 1) {
+ // Now if there were more than one method with the same name
+ // we need to start figuring out what is the correct one.
+ for (MethodInfo methodInfo : methodInfos) {
+ if (compareParameters(methodInfo.getParams())) {
+ return methodInfo;
+ }
}
+ } else if (!methodInfos.isEmpty()){
+ // Not perfect, but works on most cases.
+ // There is no check if the parameter types match.
+ return methodInfos.get(0);
}
}
}
@@ -133,4 +144,27 @@ private MethodInfo getMethodInfo() {
return null;
}
+ private ArrayList<MethodInfo> getMethodInfos(String methodName, List<MethodInfo> methods) {
+ ArrayList<MethodInfo> result = new ArrayList<MethodInfo>();
+ for (MethodInfo method : methods) {
+ if (method.getName().equals(methodName)) {
+ result.add(method);
+ }
+ }
+ return result;
+ }
+
+ private boolean compareParameters(List<String> methodParams) {
+ if (methodParams.size() != parameters.length) {
+ return false;
+ } else {
+ for (int index = 0; index < methodParams.size(); index++) {
+ if (!methodParams.get(index).equals(boundParams.get(parameters[index]))) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+
}
diff --git a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
index 9bf47778577..a1de643d986 100644
--- a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
+++ b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
@@ -3273,7 +3273,6 @@ public void testDSLExpansionRHS() {
}
@Test
- @Ignore(" Still does not know the difference between indexOf(int) and indexOf(String) ")
public void testFunctionCalls() {
String drl =
"package org.mortgages\n" +
@@ -3289,21 +3288,19 @@ public void testFunctionCalls() {
+ "end\n";
Map<String, List<MethodInfo>> methodInformation = new HashMap<String, List<MethodInfo>>();
- List<MethodInfo> mapMethodInformation1 = new ArrayList<MethodInfo>();
- mapMethodInformation1.add( new MethodInfo( "indexOf",
+ List<MethodInfo> mapMethodInformation = new ArrayList<MethodInfo>();
+ mapMethodInformation.add( new MethodInfo( "indexOf",
Arrays.asList( new String[]{ "String" } ),
"int",
null,
"String" ) );
- List<MethodInfo> mapMethodInformation2 = new ArrayList<MethodInfo>();
- mapMethodInformation2.add( new MethodInfo( "indexOf",
+ mapMethodInformation.add( new MethodInfo( "indexOf",
Arrays.asList( new String[]{ "Integer" } ),
"int",
null,
"String" ) );
- methodInformation.put( "java.lang.String", mapMethodInformation2 );
- methodInformation.put( "java.lang.String", mapMethodInformation1 );
+ methodInformation.put( "java.lang.String", mapMethodInformation );
when( dmo.getProjectMethodInformation() ).thenReturn( methodInformation );
|
c2d25218b429e6041c3652025788701e795db22e
|
Delta Spike
|
DELTASPIKE-312 remove GlobalAlternatives handling for OWB and fix tests
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java
index e76a257f8..f0a7959b4 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java
@@ -59,7 +59,7 @@ public class ExcludeExtension implements Extension, Deactivatable
{
private static final Logger LOG = Logger.getLogger(ExcludeExtension.class.getName());
- private static Boolean isOwbDetected = false;
+ private static Boolean isWeldDetected = false;
private boolean isActivated = true;
private boolean isGlobalAlternativeActivated = true;
@@ -77,7 +77,7 @@ protected void init(@Observes BeforeBeanDiscovery beforeBeanDiscovery)
isCustomProjectStageBeanFilterActivated =
ClassDeactivationUtils.isActivated(CustomProjectStageBeanFilter.class);
- isOwbDetected = isOpenWebBeans();
+ isWeldDetected = isWeld();
}
/**
@@ -100,11 +100,7 @@ protected void vetoBeans(@Observes ProcessAnnotatedType processAnnotatedType, Be
//we need to do it before the exclude logic to keep the @Exclude support for global alternatives
if (isGlobalAlternativeActivated)
{
- if (isOwbDetected)
- {
- activateGlobalAlternativesOwb(processAnnotatedType, beanManager);
- }
- else
+ if (isWeldDetected)
{
activateGlobalAlternativesWeld(processAnnotatedType, beanManager);
}
@@ -239,84 +235,6 @@ private void activateGlobalAlternativesWeld(ProcessAnnotatedType processAnnotate
}
}
- //see OWB-643
- //just #veto the original implementation and remove @Alternative from the ProcessAnnotatedType of
- // the configured alternative doesn't work with OWB (due to OWB-643)
- private void activateGlobalAlternativesOwb(ProcessAnnotatedType processAnnotatedType,
- BeanManager beanManager)
- {
- //the current bean is the bean with a potential global alternative
- Class<Object> currentBean = processAnnotatedType.getAnnotatedType().getJavaClass();
-
- if (currentBean.isInterface())
- {
- return;
- }
-
- Set<Class> beanBaseTypes = resolveBeanTypes(currentBean);
-
- boolean isAlternativeBeanImplementation = currentBean.isAnnotationPresent(Alternative.class);
-
- List<Annotation> qualifiersOfCurrentBean =
- resolveQualifiers(processAnnotatedType.getAnnotatedType().getAnnotations(), beanManager);
-
- String configuredBeanName;
- List<Annotation> qualifiersOfConfiguredBean;
- Class<Object> alternativeBeanClass;
- Set<Annotation> alternativeBeanAnnotations;
-
- for (Class currentType : beanBaseTypes)
- {
- alternativeBeanAnnotations = new HashSet<Annotation>();
-
- configuredBeanName = ConfigResolver.getPropertyValue(currentType.getName());
- if (configuredBeanName != null && configuredBeanName.length() > 0)
- {
- alternativeBeanClass = ClassUtils.tryToLoadClassForName(configuredBeanName);
-
- if (alternativeBeanClass == null)
- {
- throw new IllegalStateException("Can't find class " + configuredBeanName + " which is configured" +
- " for " + currentType.getName());
- }
- alternativeBeanAnnotations.addAll(Arrays.asList(alternativeBeanClass.getAnnotations()));
- qualifiersOfConfiguredBean = resolveQualifiers(alternativeBeanAnnotations, beanManager);
- }
- else
- {
- continue;
- }
-
- //current bean is annotated with @Alternative and of the same type as the configured bean
- if (isAlternativeBeanImplementation && alternativeBeanClass.equals(currentBean))
- {
- if (doQualifiersMatch(qualifiersOfCurrentBean, qualifiersOfConfiguredBean))
- {
- //veto if the current annotated-type is a global alternative - it replaced the original type already
- processAnnotatedType.veto();
- break;
- }
- }
- else
- {
- if (!alternativeBeanClass.isAnnotationPresent(Alternative.class))
- {
- continue;
- }
-
- if (doQualifiersMatch(qualifiersOfCurrentBean, qualifiersOfConfiguredBean))
- {
- AnnotatedTypeBuilder<Object> annotatedTypeBuilder
- = new AnnotatedTypeBuilder<Object>().readFromType(alternativeBeanClass);
-
- //just to avoid issues with switching between app-servers,...
- annotatedTypeBuilder.removeFromClass(Alternative.class);
- processAnnotatedType.setAnnotatedType(annotatedTypeBuilder.create());
- }
- }
- }
- }
-
private boolean doQualifiersMatch(List<Annotation> qualifiersOfCurrentBean,
List<Annotation> qualifiersOfConfiguredBean)
{
@@ -524,13 +442,13 @@ private void veto(ProcessAnnotatedType processAnnotatedType, String vetoType)
processAnnotatedType.getAnnotatedType().getJavaClass());
}
- private boolean isOpenWebBeans()
+ private boolean isWeld()
{
IllegalStateException runtimeException = new IllegalStateException();
for (StackTraceElement element : runtimeException.getStackTrace())
{
- if (element.toString().contains("org.apache.webbeans."))
+ if (element.toString().contains("org.jboss.weld"))
{
return true;
}
diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java
index 287fae222..60ca097f9 100644
--- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java
+++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/GlobalAlternativeTest.java
@@ -31,7 +31,9 @@
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
@@ -40,7 +42,6 @@
import org.junit.runner.RunWith;
import javax.inject.Inject;
-import java.util.List;
/**
* Tests for @Alternative across BDAs
@@ -67,6 +68,14 @@ public class GlobalAlternativeTest
@Deployment
public static WebArchive deploy()
{
+ Asset beansXml = new StringAsset(
+ "<beans><alternatives>" +
+ "<class>" + BaseInterface1AlternativeImplementation.class.getName() + "</class>" +
+ "<class>" + SubBaseBean2.class.getName() + "</class>" +
+ "<class>" + AlternativeBaseBeanB.class.getName() + "</class>" +
+ "</alternatives></beans>"
+ );
+
JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, "excludeIntegrationTest.jar")
.addPackage(GlobalAlternativeTest.class.getPackage())
.addPackage(QualifierA.class.getPackage())
@@ -75,7 +84,7 @@ public static WebArchive deploy()
return ShrinkWrap.create(WebArchive.class, "globalAlternative.war")
.addAsLibraries(ArchiveUtils.getDeltaSpikeCoreArchive(new String[]{"META-INF.config"}))
.addAsLibraries(testJar)
- .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
+ .addAsWebInfResource(beansXml, "beans.xml");
}
/**
@@ -84,10 +93,9 @@ public static WebArchive deploy()
@Test
public void alternativeImplementationWithClassAsBaseType()
{
- List<BaseBean1> testBeans = BeanProvider.getContextualReferences(BaseBean1.class, true);
+ BaseBean1 testBean = BeanProvider.getContextualReference(BaseBean1.class);
- Assert.assertEquals(1, testBeans.size());
- Assert.assertEquals(SubBaseBean2.class.getName(), testBeans.get(0).getClass().getName());
+ Assert.assertEquals(SubBaseBean2.class.getName(), testBean.getClass().getName());
}
/**
diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean1.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean1.java
index b6c904808..4156b2521 100644
--- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean1.java
+++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean1.java
@@ -21,8 +21,6 @@
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Alternative;
-/**
- */
@Alternative
@Dependent
public class SubBaseBean1 extends BaseBean1
diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean2.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean2.java
index 7d5ca9999..05e1c1aba 100644
--- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean2.java
+++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/alternative/global/SubBaseBean2.java
@@ -21,8 +21,6 @@
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Alternative;
-/**
- */
@Alternative
@Dependent
public class SubBaseBean2 extends SubBaseBean1
|
23cc3054f8069da9679d50084be8262bc944c071
|
Vala
|
girparser: Handle delegate aliases
Fixes bug 667751
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/tests/Makefile.am b/tests/Makefile.am
index f7dca48076..6a36a4dd39 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -185,6 +185,7 @@ TESTS = \
dbus/bug596862.vala \
dbus/bug602003.test \
gir/bug651773.test \
+ gir/bug667751.test \
$(NULL)
check-TESTS: $(TESTS)
diff --git a/tests/gir/bug667751.test b/tests/gir/bug667751.test
new file mode 100644
index 0000000000..dfba91609f
--- /dev/null
+++ b/tests/gir/bug667751.test
@@ -0,0 +1,33 @@
+GIR
+
+Input:
+
+<alias name="RemoteConnectionCommitFunc"
+ c:type="NMRemoteConnectionCommitFunc">
+ <type name="RemoteConnectionResultFunc"
+ c:type="NMRemoteConnectionResultFunc"/>
+</alias>
+
+<callback name="RemoteConnectionResultFunc"
+ c:type="NMRemoteConnectionResultFunc">
+ <return-value transfer-ownership="none">
+ <type name="none" c:type="void"/>
+ </return-value>
+ <parameters>
+ <parameter name="error" transfer-ownership="none">
+ <doc xml:whitespace="preserve">on failure, a descriptive error</doc>
+ <type name="GLib.Error" c:type="GError*"/>
+ </parameter>
+ <parameter name="user_data" transfer-ownership="none" closure="1">
+ <doc xml:whitespace="preserve">user data passed to function which began the operation</doc>
+ <type name="gpointer" c:type="gpointer"/>
+ </parameter>
+ </parameters>
+</callback>
+
+Output:
+
+[CCode (cheader_filename = "test.h", cname = "NMRemoteConnectionResultFunc", instance_pos = 1.9)]
+public delegate void RemoteConnectionCommitFunc (GLib.Error error);
+[CCode (cheader_filename = "test.h", cname = "NMRemoteConnectionResultFunc", instance_pos = 1.9)]
+public delegate void RemoteConnectionResultFunc (GLib.Error error);
diff --git a/vala/valagirparser.vala b/vala/valagirparser.vala
index 8a2fb1b21b..8956fa58c5 100644
--- a/vala/valagirparser.vala
+++ b/vala/valagirparser.vala
@@ -1,7 +1,7 @@
/* valagirparser.vala
*
* Copyright (C) 2008-2012 Jürg Billeter
- * Copyright (C) 2011 Luca Bruno
+ * Copyright (C) 2011-2014 Luca Bruno
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
@@ -524,7 +524,7 @@ public class Vala.GirParser : CodeVisitor {
public Node (string? name) {
this.name = name;
}
-
+
public void add_member (Node node) {
var nodes = scope[node.name];
if (nodes == null) {
@@ -772,7 +772,7 @@ public class Vala.GirParser : CodeVisitor {
}
}
}
-
+
if (symbol is Class && girdata != null) {
var class_struct = girdata["glib:type-struct"];
if (class_struct != null) {
@@ -3289,16 +3289,23 @@ public class Vala.GirParser : CodeVisitor {
to guess it from the base type */
DataType base_type = null;
Symbol type_sym = null;
+ Node base_node = null;
bool simple_type = false;
if (alias.base_type is UnresolvedType) {
base_type = alias.base_type;
- type_sym = resolve_symbol (alias.parent, ((UnresolvedType) base_type).unresolved_symbol);
+ base_node = resolve_node (alias.parent, ((UnresolvedType) base_type).unresolved_symbol);
+ if (base_node != null) {
+ type_sym = base_node.symbol;
+ }
} else if (alias.base_type is PointerType && ((PointerType) alias.base_type).base_type is VoidType) {
// gpointer, if it's a struct make it a simpletype
simple_type = true;
} else {
base_type = alias.base_type;
type_sym = base_type.data_type;
+ if (type_sym != null) {
+ base_node = resolve_node (alias.parent, parse_symbol_from_string (type_sym.get_full_name (), alias.source_reference));
+ }
}
if (type_sym is Struct && ((Struct) type_sym).is_simple_type ()) {
@@ -3325,10 +3332,41 @@ public class Vala.GirParser : CodeVisitor {
cl.comment = alias.comment;
cl.external = true;
alias.symbol = cl;
+ } else if (type_sym is Delegate) {
+ var orig = (Delegate) type_sym;
+ if (base_node != null) {
+ base_node.process (this);
+ orig = (Delegate) base_node.symbol;
+ }
+
+ var deleg = new Delegate (alias.name, orig.return_type.copy (), alias.source_reference);
+ deleg.access = orig.access;
+ deleg.has_target = orig.has_target;
+
+ foreach (var param in orig.get_parameters ()) {
+ deleg.add_parameter (param.copy ());
+ }
+
+ foreach (var error_type in orig.get_error_types ()) {
+ deleg.add_error_type (error_type.copy ());
+ }
+
+ foreach (var attribute in orig.attributes) {
+ deleg.attributes.append (attribute);
+ }
+
+ deleg.external = true;
+
+ alias.symbol = deleg;
}
}
void process_callable (Node node) {
+ if (node.element_type == "alias" && node.symbol is Delegate) {
+ // processed in parse_alias
+ return;
+ }
+
var s = node.symbol;
List<ParameterInfo> parameters = node.parameters;
diff --git a/vala/valaparameter.vala b/vala/valaparameter.vala
index e65703dc28..2a89e69912 100644
--- a/vala/valaparameter.vala
+++ b/vala/valaparameter.vala
@@ -102,7 +102,7 @@ public class Vala.Parameter : Variable {
public Parameter copy () {
if (!ellipsis) {
- var result = new Parameter (name, variable_type, source_reference);
+ var result = new Parameter (name, variable_type.copy (), source_reference);
result.params_array = params_array;
result.direction = this.direction;
result.initializer = this.initializer;
|
e25f5b51c796426f45c626de7487186ba64d1b9b
|
Vala
|
gdk-pixbuf-2.0: GdkPixbufDestroyNotify doesn't have a length parameter
Fixes bug 613855.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gdk-pixbuf-2.0.vapi b/vapi/gdk-pixbuf-2.0.vapi
index 15f621261b..e1071f1889 100644
--- a/vapi/gdk-pixbuf-2.0.vapi
+++ b/vapi/gdk-pixbuf-2.0.vapi
@@ -199,7 +199,7 @@ namespace Gdk {
ENCODING_MASK
}
[CCode (cheader_filename = "gdk-pixbuf/gdk-pixdata.h")]
- public delegate void PixbufDestroyNotify (uchar[] pixels);
+ public delegate void PixbufDestroyNotify ([CCode (array_length = false)] uchar[] pixels);
[CCode (cheader_filename = "gdk-pixbuf/gdk-pixdata.h")]
public delegate bool PixbufSaveFunc (string buf, size_t count, GLib.Error error);
[CCode (cheader_filename = "gdk-pixbuf/gdk-pixdata.h")]
diff --git a/vapi/packages/gdk-pixbuf-2.0/gdk-pixbuf-2.0.metadata b/vapi/packages/gdk-pixbuf-2.0/gdk-pixbuf-2.0.metadata
index 22700900e5..264af3fbd5 100644
--- a/vapi/packages/gdk-pixbuf-2.0/gdk-pixbuf-2.0.metadata
+++ b/vapi/packages/gdk-pixbuf-2.0/gdk-pixbuf-2.0.metadata
@@ -20,6 +20,7 @@ gdk_pixbuf_scale_simple transfer_ownership="1"
gdk_pixbuf_rotate_simple transfer_ownership="1"
gdk_pixbuf_flip transfer_ownership="1"
gdk_pixbuf_loader_write.buf no_array_length="1"
+GdkPixbufDestroyNotify.pixels no_array_length="1"
GdkPixdata is_value_type="1"
GdkPixdata.pixel_data is_array="1"
gdk_pixdata_deserialize.stream is_array="1" array_length_pos="0.9"
|
45e386a75716885ff1c65211532d8cf7c3950306
|
iee$iee
|
rewritten expression type detection - improved performance, flexibility
|
p
|
https://github.com/iee/iee
|
diff --git a/org.eclipse.iee.p2-repo/pom.xml b/org.eclipse.iee.p2-repo/pom.xml
index e4140806..a61309ca 100644
--- a/org.eclipse.iee.p2-repo/pom.xml
+++ b/org.eclipse.iee.p2-repo/pom.xml
@@ -57,6 +57,10 @@
<id>net.sourceforge.cssparser:cssparser:0.9.11</id>
<source>true</source>
</artifact>
+ <artifact>
+ <id>gov.nist.math:jama:1.0.3</id>
+ <source>true</source>
+ </artifact>
</artifacts>
</configuration>
</execution>
diff --git a/org.eclipse.iee.translator.antlr/META-INF/MANIFEST.MF b/org.eclipse.iee.translator.antlr/META-INF/MANIFEST.MF
index 94a9dc2b..2d866229 100644
--- a/org.eclipse.iee.translator.antlr/META-INF/MANIFEST.MF
+++ b/org.eclipse.iee.translator.antlr/META-INF/MANIFEST.MF
@@ -15,5 +15,7 @@ Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Export-Package: org.eclipse.iee.translator.antlr.java,
org.eclipse.iee.translator.antlr.math,
org.eclipse.iee.translator.antlr.translator
-Import-Package: org.slf4j;version="1.7.2",
+Import-Package: Jama,
+ com.google.common.collect;version="16.0.1",
+ org.slf4j;version="1.7.2",
org.stringtemplate.v4
diff --git a/org.eclipse.iee.translator.antlr/antlr4/org/eclipse/iee/translator/antlr/math/Math.g4 b/org.eclipse.iee.translator.antlr/antlr4/org/eclipse/iee/translator/antlr/math/Math.g4
index 2e4e551a..76599db0 100644
--- a/org.eclipse.iee.translator.antlr/antlr4/org/eclipse/iee/translator/antlr/math/Math.g4
+++ b/org.eclipse.iee.translator.antlr/antlr4/org/eclipse/iee/translator/antlr/math/Math.g4
@@ -27,7 +27,7 @@ standardFunction:
;
variableAssignment:
- name=expression '=' value=expression
+ name=MATH_NAME '=' value=expression
;
expression:
diff --git a/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/JavaTranslator.java b/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/JavaTranslator.java
index a8c6420d..ffbbdc9e 100644
--- a/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/JavaTranslator.java
+++ b/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/JavaTranslator.java
@@ -1,8 +1,10 @@
package org.eclipse.iee.translator.antlr.translator;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@@ -16,8 +18,10 @@
import org.eclipse.iee.translator.antlr.math.MathLexer;
import org.eclipse.iee.translator.antlr.math.MathParser;
import org.eclipse.iee.translator.antlr.math.MathParser.IntervalParameterContext;
+import org.eclipse.iee.translator.antlr.math.MathParser.MatrixElementContext;
+import org.eclipse.iee.translator.antlr.math.MathParser.PrimaryExprContext;
import org.eclipse.iee.translator.antlr.math.MathParser.ValueParameterContext;
-import org.eclipse.jdt.core.IBuffer;
+import org.eclipse.iee.translator.antlr.math.MathParser.VariableAssignmentContext;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
@@ -29,10 +33,7 @@
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
-import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.core.dom.Expression;
-import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import org.slf4j.Logger;
@@ -41,6 +42,8 @@
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupDir;
+import Jama.Matrix;
+
public class JavaTranslator {
private static final Logger logger = LoggerFactory.getLogger(JavaTranslator.class);
@@ -50,47 +53,41 @@ public enum VariableType {
}
private ICompilationUnit fCompilationUnit;
+
private IType fClass;
+
private IMethod fMethod;
private int fPosition;
- private List<String> fDoubleFields = new ArrayList<>();
-
- private List<String> fIntegerFields = new ArrayList<>();
-
- private List<String> fMatrixFields = new ArrayList<>();
-
- private List<String> fOtherFields = new ArrayList<>();
+ private Map<String, String> fFields = new HashMap<>();
private Set<String> fOtherSourceClasses = new HashSet<>();
+
private Set<String> fMethodClasses = new HashSet<>();
+
private Set<String> fInnerClasses = new HashSet<>();
- private VariableType fVariableType = null;
- private String fVariableTypeString = "";
-
- private boolean fNewVariable;
- private boolean fVariableAssignment;
-
- private boolean fFunctionDefinition;
- private List<String> fDeterminedFunctionParams = new ArrayList<>();
- private List<String> fDeterminedFunctionVariables = new ArrayList<>();
-
- private List<String> fFoundedVariables = new ArrayList<>();
- private List<String> fInternalFunctionsParams = new ArrayList<>();
-
- private class JavaMathVisitor extends MathBaseVisitor<String> {
+ private static class JavaMathVisitor extends MathBaseVisitor<String> {
// statement rule
/*
* Help variables
*/
+ private boolean fFunctionDefinition;
+ private List<String> fDeterminedFunctionParams = new ArrayList<>();
+ private List<String> fDeterminedFunctionVariables = new ArrayList<>();
+
+ private List<String> fFoundedVariables = new ArrayList<>();
+ private List<String> fInternalFunctionsParams = new ArrayList<>();
- Boolean fVisitVariableName = false;
- Boolean fVisitedMatrixElement = false;
- Boolean fNewMatrix = false;
- Boolean fMatrixExpression = false;
+ private ExternalTranslationContext fExternalContext;
+ private TypeVisitior fTypeVisitor;
+
+ public JavaMathVisitor(ExternalTranslationContext externalContext) {
+ fExternalContext = externalContext;
+ fTypeVisitor = new TypeVisitior(fExternalContext);
+ }
public String visitFunctionDefinition(
MathParser.FunctionDefinitionContext ctx) {
@@ -133,49 +130,24 @@ public String visitFunctionDefinition(
public String visitVariableAssignment(
MathParser.VariableAssignmentContext ctx) {
- fVariableAssignment = true;
-
- fVisitVariableName = true;
- String name = visit(ctx.name);
- fVisitVariableName = false;
-
String value = visit(ctx.value);
-
- if (fVisitedMatrixElement) {
- fVariableType = VariableType.DOUBLE;
- return name += value + ");";
+
+ if (ctx.name instanceof PrimaryExprContext
+ && ((PrimaryExprContext) ctx.name).primary() instanceof MatrixElementContext) {
+ MatrixElementContext elt = (MatrixElementContext) ((PrimaryExprContext) ctx.name).primary();
+ String rowIndex = visit(elt.rowIdx).replaceAll("\\.0", "");
+ String columnIndex = visit(elt.columnIdx).replaceAll("\\.0", "");
+ return translateName(elt.name.getText()) + ".set(" + rowIndex + "," + columnIndex + "," + value + ")";
}
-
- if (fClass == null)
- return name + "=" + value + ";";
-
+
+
+ String name = translateName(ctx.name.getText());
+
String assignment = "";
- if (fDoubleFields.contains(name) || fMatrixFields.contains(name)
- || fIntegerFields.contains(name)) {
- if (fDoubleFields.contains(name))
- fVariableType = VariableType.DOUBLE;
- else if (fMatrixFields.contains(name))
- fVariableType = VariableType.MATRIX;
- else if (fIntegerFields.contains(name))
- fVariableType = VariableType.INT;
- else if (fOtherFields.contains(name))
- fVariableType = VariableType.OTHER;
-
- assignment += name + "=" + value + ";";
- } else {
- if ((fNewMatrix || fMatrixExpression || (fMatrixFields
- .contains(value)) && !name.matches(value))) {
- assignment += "Matrix ";
- fVariableType = VariableType.MATRIX;
- } else {
- fNewVariable = true;
- }
- assignment += name + "=";
- assignment += value + ";";
-
- }
+ assignment += name + "=" + value;
+
return assignment;
}
@@ -200,11 +172,11 @@ public String visitStandardFunction(
List<String> fieldsNames = new ArrayList<>();
List<String> params = new ArrayList<>();
- if (fMethodClasses.contains(firstLetterUpperCase(name))) {
+ if (fExternalContext.containsMethod(name)) {
new_ = "new ";
name_ = firstLetterUpperCase(name);
- IType type = fMethod.getType(firstLetterUpperCase(name), 1);
+ IType type = fExternalContext.getMethodType(name);
try {
IField[] fields = type.getFields();
for (int i = 0; i < fields.length; i++) {
@@ -224,11 +196,11 @@ public String visitStandardFunction(
e.printStackTrace();
}
- } else if (fInnerClasses.contains(firstLetterUpperCase(name))) {
+ } else if (fExternalContext.containsClass(name)) {
new_ = "this.new ";
name_ = firstLetterUpperCase(name);
- IType type = fClass.getType(firstLetterUpperCase(name), 1);
+ IType type = fExternalContext.getClassType(name);
try {
IField[] fields = type.getFields();
for (int i = 0; i < fields.length; i++) {
@@ -247,7 +219,7 @@ public String visitStandardFunction(
e.printStackTrace();
}
- } else if (fOtherSourceClasses.contains(firstLetterUpperCase(name))) {
+ } else if (fExternalContext.containsOtherSourceClass(name)) {
new_ = "new ";
name_ = firstLetterUpperCase(name);
@@ -482,12 +454,11 @@ public String visitAdd(MathParser.AddContext ctx) {
String right = visit(ctx.right);
String sign = ctx.sign.getText();
- if (getType(fPosition, "myTmp=" + left + ";").matches("Matrix")
- && getType(fPosition, "myTmp=" + right + ";").matches(
- "Matrix")) {
- // XXX: temporary solution
- fMatrixExpression = true;
-
+
+ VariableType leftType = ctx.left.accept(fTypeVisitor);
+ VariableType rightType = ctx.right.accept(fTypeVisitor);
+
+ if (leftType.equals(VariableType.MATRIX) && rightType.equals(VariableType.MATRIX)) {
if (sign.matches(Pattern.quote("+")))
return left + ".plus(" + right + ")";
if (sign.matches(Pattern.quote("-")))
@@ -502,12 +473,11 @@ public String visitMult(MathParser.MultContext ctx) {
String right = visit(ctx.right);
String sign = ctx.sign.getText();
- boolean leftMatrix = getType(fPosition, "myTmp=" + left + ";").matches("Matrix");
- boolean rightMatrix = getType(fPosition, "myTmp=" + right + ";").matches("Matrix");
+ VariableType leftType = ctx.left.accept(fTypeVisitor);
+ VariableType rightType = ctx.right.accept(fTypeVisitor);
+ boolean leftMatrix = leftType.equals(VariableType.MATRIX);
+ boolean rightMatrix = rightType.equals(VariableType.MATRIX);
if (leftMatrix || rightMatrix) {
- // XXX: temporary solution
- fMatrixExpression = true;
-
if (!leftMatrix && rightMatrix) {
String tmp = right;
right = left;
@@ -546,11 +516,8 @@ public String visitPower(MathParser.PowerContext ctx) {
String left = visit(ctx.left);
String right = visit(ctx.right);
- if (getType(fPosition, "myTmp=" + left + ";").matches("Matrix")
- && right.matches("T")) {
- // XXX: temporary solution
- fMatrixExpression = true;
-
+ VariableType type = ctx.left.accept(fTypeVisitor);
+ if (type.equals(VariableType.MATRIX) && right.matches("T")) {
return left + ".transpose()";
}
@@ -558,13 +525,10 @@ public String visitPower(MathParser.PowerContext ctx) {
}
public String visitMatrix(MathParser.MatrixContext ctx) {
-
- fNewMatrix = true;
-
String matrix = "";
int i;
- matrix += "new Matrix(new double[][]{";
+ matrix += "new Jama.Matrix(new double[][]{";
int rowsCount = ctx.rows.size();
for (i = 0; i < rowsCount; i++) {
@@ -640,7 +604,7 @@ public String visitFloatNumber(MathParser.FloatNumberContext ctx) {
}
public String visitIntNumber(MathParser.IntNumberContext ctx) {
- return ctx.getText() + ".0";
+ return ctx.getText();
}
public String visitMatrixDefinition(
@@ -653,14 +617,8 @@ public String visitMatrixElement(MathParser.MatrixElementContext ctx) {
String rowIndex = visit(ctx.rowIdx).replaceAll("\\.0", "");
String columnIndex = visit(ctx.columnIdx).replaceAll("\\.0", "");
- if (fVisitVariableName) {
- fVisitedMatrixElement = true;
-
- return translateName(ctx.name.getText()) + ".set(" + rowIndex
- + "," + columnIndex + ",";
- } else
- return translateName(ctx.name.getText()) + ".get(" + rowIndex
- + "," + columnIndex + ")";
+ return translateName(ctx.name.getText()) + ".get(" + rowIndex
+ + "," + columnIndex + ")";
}
public String visitPrimaryFunction(MathParser.PrimaryFunctionContext ctx) {
@@ -686,20 +644,82 @@ public static String translate(String expression) {
}
private String translateIntl(String expression) {
- String result = "";
+ ParserRuleContext tree = parseTree(expression);
+
+ return treeToString(tree);
+ }
+ private ParserRuleContext parseTree(String expression) {
ANTLRInputStream input = new ANTLRInputStream(expression);
MathLexer lexer = new MathLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
MathParser parser = new MathParser(tokens);
parser.setBuildParseTree(true);
ParserRuleContext tree = parser.statement();
+ return tree;
+ }
- JavaMathVisitor mathVisitor = new JavaMathVisitor();
+ private String treeToString(ParserRuleContext tree) {
+ String result;
+ JavaMathVisitor mathVisitor = createVisitor();
result = mathVisitor.visit(tree);
return result;
}
+ private JavaMathVisitor createVisitor() {
+ JavaMathVisitor mathVisitor = new JavaMathVisitor(createContext());
+ return mathVisitor;
+ }
+
+ private ExternalTranslationContext createContext() {
+ return new ExternalTranslationContext() {
+
+ @Override
+ public boolean containsMethod(String name) {
+ return fMethodClasses.contains(firstLetterUpperCase(name));
+ }
+
+ @Override
+ public IType getMethodType(String name) {
+ return fMethod.getType(firstLetterUpperCase(name), 1);
+ }
+
+ @Override
+ public boolean containsClass(String name) {
+ return fInnerClasses.contains(firstLetterUpperCase(name));
+ }
+
+ @Override
+ public IType getClassType(String name) {
+ return fClass.getType(firstLetterUpperCase(name), 1);
+ }
+
+ @Override
+ public boolean containsOtherSourceClass(String name) {
+ return fOtherSourceClasses.contains(firstLetterUpperCase(name));
+ }
+
+ @Override
+ public String translateName(String text) {
+ return JavaTranslator.translateName(text);
+ }
+
+ @Override
+ public VariableType getVariableType(String variable) {
+ String type = fFields.get(variable);
+ if ("double".equals(type)) {
+ return VariableType.DOUBLE;
+ } else if (Matrix.class.getName().equals(type)) {
+ return VariableType.MATRIX;
+ } else if ("int".equals(type)) {
+ return VariableType.INT;
+ } else {
+ return VariableType.OTHER;
+ }
+ }
+ };
+ }
+
public static String translate(String inputExpression,
ICompilationUnit compilationUnit, int position, String containerId) {
@@ -741,105 +761,59 @@ private String translateIntl(String inputExpression,
parse();
logger.debug("expr: " + expression);
- result = translateIntl(expression);
-
- /*
- * Try get recognize variable type from expression
- */
+ ParserRuleContext tree = parseTree(expression);
+ result = treeToString(tree);
- if (fNewVariable) {
- result = getType(fPosition, result) + " " + result;
+ String name = null;
+ if (tree.getChild(0) instanceof VariableAssignmentContext) {
+ VariableAssignmentContext assignment = (VariableAssignmentContext) tree.getChild(0);
+ name = translateName(assignment.name.getText());
}
-
- if (!fVariableAssignment)
- getType(position, "myTmp=" + result + ";");
-
+
/*
* Generate output code, if necessary
*/
+ VariableType type = tree.accept(new TypeVisitior(createContext()));
if (inputExpression.charAt(inputExpression.length() - 1) == '=') {
- if (!fVariableAssignment) {
- String output = generateOutputCode(result, containerId, false);
- result = output;
+ String output = generateOutputCode(type, result, containerId);
+ if (name != null && !fFields.containsKey(name)) {
+ result = getName(type) + " " + name + ";" + output;
} else {
- String output = generateOutputCode(inputExpression,
- containerId, true);
- result += output;
+ result = output;
}
- }
+ } else {
+ if (name != null && !fFields.containsKey(name)) {
+ result = getName(type) + " " + result + ";";
+ }
+ }
return result;
}
- private String generateOutputCode(String expression,
- String containerId, boolean isInputExpression) {
- String expr = expression;
-
- String[] parts;
-
- if (isInputExpression) {
- parts = expr.replaceAll(Pattern.quote("{"), "")
- .replaceAll(Pattern.quote("}"), "").split("=");
- } else
- parts = expr.split("=");
-
- if (parts.length >= 1) {
- String variable = expression;
- if (parts.length > 1 && isInputExpression)
- variable = expression.substring(0, expression.indexOf('='));
-
- variable = variable.trim();
- if (isInputExpression) {
- variable = variable.replaceAll(Pattern.quote("{"), "");
- variable = variable.replaceAll(Pattern.quote("}"), "");
- }
-
- VariableType varType = fVariableType;
-
- if (varType == null) {
- if (fDoubleFields.contains(variable))
- varType = VariableType.DOUBLE;
- else if (fIntegerFields.contains(variable))
- varType = VariableType.INT;
- else if (fMatrixFields.contains(variable))
- varType = VariableType.MATRIX;
- else
- return "";
- }
-
- logger.debug("Type:" + varType.toString());
+ private String generateOutputCode(VariableType type, String expression, String containerId) {
STGroup group = createSTGroup();
-
- if (varType != VariableType.MATRIX) {
-
- String type = "";
- if (varType == VariableType.DOUBLE)
- type = "double";
- else if (varType == VariableType.INT)
- type = "int";
-
- ST template = group.getInstanceOf("variable");
-
- template.add("type", type);
+ if (VariableType.MATRIX.equals(type)) {
+ ST template = group.getInstanceOf("matrix");
template.add("id", containerId);
- template.add("variable", variable);
-
- return template.render(1).trim().replaceAll("\r\n", "")
- .replaceAll("\t", " ");
-
+ template.add("variable", expression);
+ return template.render(1).trim().replaceAll("\r\n", "").replaceAll("\t", " ");
} else {
-
- String type = "Matrix";
-
- ST template = group.getInstanceOf("matrix");
- template.add("type", type);
+ ST template = group.getInstanceOf("variable");
template.add("id", containerId);
- template.add("variable", variable);
-
- return template.render(1).trim().replaceAll("\r\n", "")
- .replaceAll("\t", " ");
+ template.add("variable", expression);
+ return template.render(1).trim().replaceAll("\r\n", "").replaceAll("\t", " ");
}
- } else {
- return "";
+ }
+
+ private String getName(VariableType type) {
+ switch (type) {
+ case DOUBLE:
+ return "double";
+ case INT:
+ return "int";
+ case MATRIX:
+ return "Jama.Matrix";
+ default:
+ return null;
}
}
@@ -917,19 +891,7 @@ private void parse() {
int fieldOffset = fieldSourceRange.getOffset();
if (fPosition > fieldOffset) {
- if (type.matches("D")) {
- if (!fDoubleFields.contains(name))
- fDoubleFields.add(name);
- } else if (type.matches("QMatrix;")) {
- if (!fMatrixFields.contains(name))
- fMatrixFields.add(name);
- } else if (type.matches("I")) {
- if (!fIntegerFields.contains(name))
- fIntegerFields.add(name);
- } else {
- if (!fOtherFields.contains(name))
- fOtherFields.add(name);
- }
+ fFields.put(name, type);
}
}
}
@@ -940,21 +902,7 @@ private void parse() {
ILocalVariable param = methodParams[i];
String name = param.getElementName();
String type = param.getTypeSignature();
-
- if (type.matches("D")) {
- if (!fDoubleFields.contains(name))
- fDoubleFields.add(name);
- } else if (type.matches("QMatrix;")) {
- if (!fMatrixFields.contains(name))
- fMatrixFields.add(name);
- } else if (type.matches("I")) {
- if (!fIntegerFields.contains(name))
- fIntegerFields.add(name);
- } else {
- if (!fOtherFields.contains(name))
- fOtherFields.add(name);
- }
-
+ fFields.put(name, type);
}
IJavaElement[] innerElements = fMethod.getChildren();
@@ -990,20 +938,7 @@ public boolean visit(VariableDeclarationStatement node) {
VariableDeclarationFragment fragment = (VariableDeclarationFragment) fragments
.get(i);
String name = fragment.getName().toString();
-
- if (type.matches("double")) {
- if (!fDoubleFields.contains(name))
- fDoubleFields.add(name);
- } else if (type.matches("Matrix")) {
- if (!fMatrixFields.contains(name))
- fMatrixFields.add(name);
- } else if (type.matches("int")) {
- if (!fIntegerFields.contains(name))
- fIntegerFields.add(name);
- } else {
- if (!fOtherFields.contains(name))
- fOtherFields.add(name);
- }
+ fFields.put(name, type);
}
}
} catch (JavaModelException e) {
@@ -1029,71 +964,8 @@ public boolean visit(VariableDeclarationStatement node) {
logger.debug("fMethod: " + fMethod.getElementName());
logger.debug("fMethodClasses: " + fMethodClasses.toString());
}
- logger.debug("fMatrixFields: " + fMatrixFields.toString());
- logger.debug("fDoubleFields: " + fDoubleFields.toString());
- logger.debug("fIntegerFields: " + fIntegerFields.toString());
- logger.debug("fOtherFields: " + fOtherFields.toString());
-
- }
-
- private String getType(final int position, final String assignment) {
- fVariableTypeString = "double";
-
- try {
-
- IBuffer buffer = fCompilationUnit.getBuffer();
- buffer.replace(position, 0, assignment);
- fCompilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
-
- // logger.debug("CopySource" + copy.getSource());
-
- CompilationUnit unit = (CompilationUnit) createAST(fCompilationUnit);
- unit.accept(new ASTVisitor() {
- @Override
- public boolean visit(Assignment node) {
- int startPosition = node.getStartPosition();
- if (startPosition >= position
- && startPosition < (position + assignment.length())) {
- Expression rightSide = node.getRightHandSide();
- logger.debug("expr: " + rightSide.toString());
- ITypeBinding typeBinding = rightSide
- .resolveTypeBinding();
- if (typeBinding != null) {
- fVariableTypeString = rightSide
- .resolveTypeBinding().getName();
- logger.debug("expr type: " + fVariableTypeString);
- } else
- logger.debug("expr type: undefined variable");
- }
-
- return true;
- }
- });
-
- buffer.replace(position, assignment.length(), "");
- fCompilationUnit.reconcile(AST.JLS4, false, null, null);
-
- } catch (JavaModelException e) {
- e.printStackTrace();
- }
-
- logger.debug("Type: " + fVariableTypeString);
-
- if (fVariableTypeString.matches("double"))
- fVariableType = VariableType.DOUBLE;
- else if (fVariableTypeString.matches("int")) {
- /*
- * If user want's use integer variables, he should define it before
- */
- // fVariableType = VariableType.INT;
- fVariableTypeString = "double";
- fVariableType = VariableType.DOUBLE;
- } else if (fVariableTypeString.matches("Matrix"))
- fVariableType = VariableType.MATRIX;
- else
- fVariableType = VariableType.OTHER;
+ logger.debug("fFields: " + fFields.toString());
- return fVariableTypeString;
}
private static String translateName(String name) {
diff --git a/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/TexTranslator.java b/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/TexTranslator.java
index 2a4d5c7f..12b35990 100644
--- a/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/TexTranslator.java
+++ b/org.eclipse.iee.translator.antlr/src/org/eclipse/iee/translator/antlr/translator/TexTranslator.java
@@ -70,9 +70,8 @@ public String visitFunctionDefinition(
return visitStandardFunction(ctx.name) + "=" + visit(ctx.value);
}
- public String visitVariableAssignment(
- MathParser.VariableAssignmentContext ctx) {
- return visit(ctx.name) + "=" + visit(ctx.value);
+ public String visitVariableAssignment(MathParser.VariableAssignmentContext ctx) {
+ return translateName(ctx.name.getText()) + "=" + visit(ctx.value);
}
public String visitLogicComparison(MathParser.LogicComparisonContext ctx) {
diff --git a/org.eclipse.iee.translator.antlr/templates/matrix.st b/org.eclipse.iee.translator.antlr/templates/matrix.st
index 5f8c0dcc..eb7a9e6c 100644
--- a/org.eclipse.iee.translator.antlr/templates/matrix.st
+++ b/org.eclipse.iee.translator.antlr/templates/matrix.st
@@ -1,31 +1,23 @@
-
-matrix(type, id, variable, path) ::= <<
- new Runnable() {
- private <type> variable;
- private Runnable init (<type> var)
+matrix(id, variable) ::= <<
+{
+ Jama.Matrix tmpMtx = <variable>;
+ int i=0, j=0; String matrix = "{";
+ for (i = 0; i \< tmpMtx.getRowDimension(); i++)
+ {
+ matrix += "{";
+
+ for (j = 0; j \< tmpMtx.getColumnDimension(); j++)
{
- variable = var; return this;
+ matrix += tmpMtx.get(i,j);
+ if (j != tmpMtx.getColumnDimension() - 1)
+ matrix += ",";
+ else
+ matrix += "}";
}
- @Override
- public void run() {
- int i=0, j=0; String matrix = "{";
- for (i = 0; i \< variable.getRowDimension(); i++)
- {
- matrix += "{";
-
- for (j = 0; j \< variable.getColumnDimension(); j++)
- {
- matrix += variable.get(i,j);
- if (j != variable.getColumnDimension() - 1)
- matrix += ",";
- else
- matrix += "}";
- }
- if (i != variable.getRowDimension() - 1)
- matrix += ",";
- }
- matrix += "}";
- org.eclipse.iee.core.EvaluationContextHolder.putResult("<id>", String.valueOf(matrix));
- }
- }.init(<variable>).run();
+ if (i != tmpMtx.getRowDimension() - 1)
+ matrix += ",";
+ }
+ matrix += "}";
+ org.eclipse.iee.core.EvaluationContextHolder.putResult("<id>", String.valueOf(matrix));
+}
>>
diff --git a/org.eclipse.iee.translator.antlr/templates/variable.st b/org.eclipse.iee.translator.antlr/templates/variable.st
index c99a4172..7f14a673 100644
--- a/org.eclipse.iee.translator.antlr/templates/variable.st
+++ b/org.eclipse.iee.translator.antlr/templates/variable.st
@@ -1,14 +1,6 @@
-variable(type, id, variable, path) ::= <<
- new Runnable() {
- private <type> variable;
- private Runnable init (<type> var)
- {
- variable = var;return this;
- }
- @Override
- public void run() {
- org.eclipse.iee.core.EvaluationContextHolder.putResult("<id>", String.valueOf(variable));
- }
- }.init(<variable>).run();
+variable(id, variable) ::= <<
+{
+ org.eclipse.iee.core.EvaluationContextHolder.putResult("<id>", String.valueOf(<variable>));
+}
>>
\ No newline at end of file
|
ff788e8f9da140e9a2cc08d4615fb878dbdb1c7d
|
camel
|
CAMEL-2636 Fixed the issue of IOException: Bad- file descriptor--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@934852 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/converter/stream/CachedOutputStream.java b/camel-core/src/main/java/org/apache/camel/converter/stream/CachedOutputStream.java
index b1765f0fe824a..804730f8efd35 100644
--- a/camel-core/src/main/java/org/apache/camel/converter/stream/CachedOutputStream.java
+++ b/camel-core/src/main/java/org/apache/camel/converter/stream/CachedOutputStream.java
@@ -68,37 +68,7 @@ public CachedOutputStream(Exchange exchange) {
if (dir != null) {
this.outputDir = exchange.getContext().getTypeConverter().convertTo(File.class, dir);
}
-
- // add on completion so we can cleanup after the exchange is done such as deleting temporary files
- exchange.addOnCompletion(new SynchronizationAdapter() {
- @Override
- public void onDone(Exchange exchange) {
- try {
- // close the stream and FileInputStreamCache
- close();
- for (FileInputStreamCache cache : fileInputStreamCaches) {
- cache.close();
- }
- // cleanup temporary file
- if (tempFile != null) {
- boolean deleted = tempFile.delete();
- if (!deleted) {
- LOG.warn("Cannot delete temporary cache file: " + tempFile);
- } else if (LOG.isTraceEnabled()) {
- LOG.trace("Deleted temporary cache file: " + tempFile);
- }
- tempFile = null;
- }
- } catch (Exception e) {
- LOG.warn("Error deleting temporary cache file: " + tempFile, e);
- }
- }
-
- @Override
- public String toString() {
- return "OnCompletion[CachedOutputStream]";
- }
- });
+
}
public void flush() throws IOException {
@@ -107,6 +77,20 @@ public void flush() throws IOException {
public void close() throws IOException {
currentStream.close();
+ try {
+ // cleanup temporary file
+ if (tempFile != null) {
+ boolean deleted = tempFile.delete();
+ if (!deleted) {
+ LOG.warn("Cannot delete temporary cache file: " + tempFile);
+ } else if (LOG.isTraceEnabled()) {
+ LOG.trace("Deleted temporary cache file: " + tempFile);
+ }
+ tempFile = null;
+ }
+ } catch (Exception e) {
+ LOG.warn("Error deleting temporary cache file: " + tempFile, e);
+ }
}
public boolean equals(Object obj) {
diff --git a/camel-core/src/main/java/org/apache/camel/converter/stream/FileInputStreamCache.java b/camel-core/src/main/java/org/apache/camel/converter/stream/FileInputStreamCache.java
index 8341ea2f04af5..ec002f2c087f7 100644
--- a/camel-core/src/main/java/org/apache/camel/converter/stream/FileInputStreamCache.java
+++ b/camel-core/src/main/java/org/apache/camel/converter/stream/FileInputStreamCache.java
@@ -41,19 +41,24 @@ public FileInputStreamCache(File file, CachedOutputStream cos) throws FileNotFou
@Override
public void close() {
try {
- getInputStream().close();
+ if (isSteamOpened()) {
+ getInputStream().close();
+ }
+ // when close the FileInputStreamCache we should also close the cachedOutputStream
if (cachedOutputStream != null) {
cachedOutputStream.close();
}
} catch (Exception e) {
throw new RuntimeCamelException(e);
- }
+ }
}
@Override
public void reset() {
try {
- getInputStream().close();
+ if (isSteamOpened()) {
+ getInputStream().close();
+ }
// reset by creating a new stream based on the file
stream = new FileInputStream(file);
} catch (Exception e) {
@@ -78,5 +83,13 @@ public int read() throws IOException {
protected InputStream getInputStream() {
return stream;
}
+
+ private boolean isSteamOpened() {
+ if (stream != null && stream instanceof FileInputStream) {
+ return ((FileInputStream) stream).getChannel().isOpen();
+ } else {
+ return stream != null;
+ }
+ }
}
diff --git a/camel-core/src/test/java/org/apache/camel/converter/stream/CachedOutputStreamTest.java b/camel-core/src/test/java/org/apache/camel/converter/stream/CachedOutputStreamTest.java
index ee84671e9c91c..6049c55c93602 100644
--- a/camel-core/src/test/java/org/apache/camel/converter/stream/CachedOutputStreamTest.java
+++ b/camel-core/src/test/java/org/apache/camel/converter/stream/CachedOutputStreamTest.java
@@ -78,8 +78,6 @@ public void testCacheStreamToFileAndCloseStream() throws IOException {
((InputStream)cache).close();
assertEquals("Cached a wrong file", temp, TEST_STRING);
- exchange.getUnitOfWork().done(exchange);
-
try {
cache.reset();
// The stream is closed, so the temp file is gone.
@@ -110,7 +108,6 @@ public void testCacheStreamToFileAndNotCloseStream() throws IOException {
temp = toString((InputStream)cache);
assertEquals("Cached a wrong file", temp, TEST_STRING);
- exchange.getUnitOfWork().done(exchange);
((InputStream)cache).close();
files = file.list();
@@ -131,8 +128,6 @@ public void testCacheStreamToMemory() throws IOException {
assertTrue("Should get the InputStreamCache", cache instanceof InputStreamCache);
String temp = IOConverter.toString((InputStream)cache, null);
assertEquals("Cached a wrong file", temp, TEST_STRING);
-
- exchange.getUnitOfWork().done(exchange);
}
public void testCacheStreamToMemoryAsDiskIsdisabled() throws IOException {
diff --git a/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpFileCacheTest.java b/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpFileCacheTest.java
new file mode 100644
index 0000000000000..cf45479375bb6
--- /dev/null
+++ b/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpFileCacheTest.java
@@ -0,0 +1,83 @@
+/**
+ * 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 java.io.File;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.converter.stream.CachedOutputStream;
+import org.apache.camel.impl.DefaultExchange;
+import org.apache.camel.impl.DefaultUnitOfWork;
+import org.apache.camel.spi.UnitOfWork;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.Before;
+import org.junit.Test;
+
+public class JettyHttpFileCacheTest extends CamelTestSupport {
+ private static final String TEST_STRING = "This is a test string and it has enough"
+ + " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ";
+
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+
+ context.getProperties().put(CachedOutputStream.TEMP_DIR, "./target/cachedir");
+ context.getProperties().put(CachedOutputStream.THRESHOLD, "16");
+ deleteDirectory("./target/cachedir");
+ createDirectory("./target/cachedir");
+ }
+
+ @Test
+ public void testGetWithRelativePath() throws Exception {
+
+ String response = template.requestBody("http://localhost:8201/clipboard/download/file", " ", String.class);
+ assertEquals("should get the right response", TEST_STRING, response);
+
+ File file = new File("./target/cachedir");
+ String[] files = file.list();
+ assertTrue("There should not have any temp file", files.length == 0);
+
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() throws Exception {
+ return new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+
+
+ from("jetty:http://localhost:8201/clipboard/download?chunked=true&matchOnUriPrefix=true")
+ .to("http://localhost:9101?bridgeEndpoint=true");
+
+ from("jetty:http://localhost:9101?chunked=true&matchOnUriPrefix=true")
+ .process(new Processor() {
+
+ public void process(Exchange exchange) throws Exception {
+ exchange.getOut().setBody(TEST_STRING);
+ }
+
+ });
+
+
+ }
+ };
+ }
+
+}
|
4a6101a697475b6f0f5b5da7cf280ad372725ebb
|
spring-framework
|
Guard against null in -visitInnerClass--Issue: SPR-8358
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.core/src/main/java/org/springframework/core/type/classreading/ClassMetadataReadingVisitor.java b/org.springframework.core/src/main/java/org/springframework/core/type/classreading/ClassMetadataReadingVisitor.java
index 4e21320fbd06..d69a75bb3d17 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/type/classreading/ClassMetadataReadingVisitor.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/type/classreading/ClassMetadataReadingVisitor.java
@@ -80,9 +80,9 @@ public void visitOuterClass(String owner, String name, String desc) {
}
public void visitInnerClass(String name, String outerName, String innerName, int access) {
- String fqName = ClassUtils.convertResourcePathToClassName(name);
- String fqOuterName = ClassUtils.convertResourcePathToClassName(outerName);
if (outerName != null) {
+ String fqName = ClassUtils.convertResourcePathToClassName(name);
+ String fqOuterName = ClassUtils.convertResourcePathToClassName(outerName);
if (this.className.equals(fqName)) {
this.enclosingClassName = fqOuterName;
this.independentInnerClass = ((access & Opcodes.ACC_STATIC) != 0);
|
bf025c0972c742d450442630739801b8e4c6a163
|
Valadoc
|
gtkdoc: Improve documentation for _get and _set
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/doclets/gtkdoc/generator.vala b/src/doclets/gtkdoc/generator.vala
index 75b3b1e10f..6efd54ae2b 100644
--- a/src/doclets/gtkdoc/generator.vala
+++ b/src/doclets/gtkdoc/generator.vala
@@ -630,6 +630,24 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
eval.accept_all_children (this);
}
+ private string combine_comments (string? brief, string? @long) {
+ StringBuilder builder = new StringBuilder ();
+ if (brief != null) {
+ builder.append (brief.strip ());
+ }
+
+ string _long = (@long != null)? @long.strip () : "";
+ if (builder.len > 0 && _long != "") {
+ builder.append ("\n\n");
+ }
+
+ if (_long != "") {
+ builder.append (_long);
+ }
+
+ return (owned) builder.str;
+ }
+
public override void visit_property (Api.Property prop) {
if (prop.is_override || prop.is_private || (!prop.is_abstract && !prop.is_virtual && prop.base_property != null)) {
return;
@@ -646,6 +664,7 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
getter_gcomment.headers.add (new Header ("self", "the %s instance to query".printf (get_docbook_link (prop.parent)), 1));
getter_gcomment.returns = "the value of the %s property".printf (get_docbook_link (prop));
getter_gcomment.brief_comment = "Get and return the current value of the %s property.".printf (get_docbook_link (prop));
+ getter_gcomment.long_comment = combine_comments (gcomment.brief_comment, gcomment.long_comment);
if (prop.property_type != null && prop.property_type.data_type is Api.Array) {
var array_type = prop.property_type.data_type;
@@ -663,6 +682,7 @@ It is important that your <link linkend=\"GValue\"><type>GValue</type></link> ho
setter_gcomment.headers.add (new Header ("self", "the %s instance to modify".printf (get_docbook_link (prop.parent)), 1));
setter_gcomment.headers.add (new Header ("value", "the new value of the %s property".printf (get_docbook_link (prop)), 2));
setter_gcomment.brief_comment = "Set the value of the %s property to @value.".printf (get_docbook_link (prop));
+ setter_gcomment.long_comment = combine_comments (gcomment.brief_comment, gcomment.long_comment);
if (prop.property_type != null && prop.property_type.data_type is Api.Array) {
var array_type = prop.property_type.data_type;
|
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");
+
+ }
+ };
+ }
+}
|
1596f988357e666df08193bfb7f41a61f6397afe
|
hbase
|
HBASE-3746 Clean up CompressionTest to not- directly reference DistributedFileSystem--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1089684 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index ca26637919d4..032652cd313a 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -169,6 +169,12 @@ Release 0.91.0 - Unreleased
HBASE-3488 Add CellCounter to count multiple versions of rows
(Subbu M. Iyer via Stack)
+Release 0.90.3 - Unreleased
+
+ BUG FIXES
+ HBASE-3746 Clean up CompressionTest to not directly reference
+ DistributedFileSystem (todd)
+
Release 0.90.2 - Unreleased
diff --git a/src/main/java/org/apache/hadoop/hbase/util/CompressionTest.java b/src/main/java/org/apache/hadoop/hbase/util/CompressionTest.java
index ee241918a173..d58d7b3c29ba 100644
--- a/src/main/java/org/apache/hadoop/hbase/util/CompressionTest.java
+++ b/src/main/java/org/apache/hadoop/hbase/util/CompressionTest.java
@@ -22,6 +22,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.io.hfile.Compression;
import org.apache.hadoop.hbase.io.hfile.HFile;
@@ -92,55 +93,48 @@ public static void testCompression(Compression.Algorithm algo)
protected static Path path = new Path(".hfile-comp-test");
public static void usage() {
- System.err.println("Usage: CompressionTest HDFS_PATH none|gz|lzo");
+ System.err.println(
+ "Usage: CompressionTest <path> none|gz|lzo\n" +
+ "\n" +
+ "For example:\n" +
+ " hbase " + CompressionTest.class + " file:///tmp/testfile gz\n");
System.exit(1);
}
- protected static DistributedFileSystem openConnection(String urlString)
- throws java.net.URISyntaxException, java.io.IOException {
- URI dfsUri = new URI(urlString);
- Configuration dfsConf = new Configuration();
- DistributedFileSystem dfs = new DistributedFileSystem();
- dfs.initialize(dfsUri, dfsConf);
- return dfs;
+ public static void doSmokeTest(FileSystem fs, Path path, String codec)
+ throws Exception {
+ HFile.Writer writer = new HFile.Writer(
+ fs, path, HFile.DEFAULT_BLOCKSIZE, codec, null);
+ writer.append(Bytes.toBytes("testkey"), Bytes.toBytes("testval"));
+ writer.appendFileInfo(Bytes.toBytes("infokey"), Bytes.toBytes("infoval"));
+ writer.close();
+
+ HFile.Reader reader = new HFile.Reader(fs, path, null, false, false);
+ reader.loadFileInfo();
+ byte[] key = reader.getFirstKey();
+ boolean rc = Bytes.toString(key).equals("testkey");
+ reader.close();
+
+ if (!rc) {
+ throw new Exception("Read back incorrect result: " +
+ Bytes.toStringBinary(key));
+ }
}
- protected static boolean closeConnection(DistributedFileSystem dfs) {
- if (dfs != null) {
- try {
- dfs.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
+ public static void main(String[] args) throws Exception {
+ if (args.length != 2) {
+ usage();
+ System.exit(1);
}
- return dfs == null;
- }
- public static void main(String[] args) {
- if (args.length != 2) usage();
+ Configuration conf = new Configuration();
+ Path path = new Path(args[0]);
+ FileSystem fs = path.getFileSystem(conf);
try {
- DistributedFileSystem dfs = openConnection(args[0]);
- dfs.delete(path, false);
- HFile.Writer writer = new HFile.Writer(dfs, path,
- HFile.DEFAULT_BLOCKSIZE, args[1], null);
- writer.append(Bytes.toBytes("testkey"), Bytes.toBytes("testval"));
- writer.appendFileInfo(Bytes.toBytes("infokey"), Bytes.toBytes("infoval"));
- writer.close();
-
- HFile.Reader reader = new HFile.Reader(dfs, path, null, false, false);
- reader.loadFileInfo();
- byte[] key = reader.getFirstKey();
- boolean rc = Bytes.toString(key).equals("testkey");
- reader.close();
-
- dfs.delete(path, false);
- closeConnection(dfs);
-
- if (rc) System.exit(0);
- } catch (Exception e) {
- e.printStackTrace();
+ doSmokeTest(fs, path, args[1]);
+ } finally {
+ fs.delete(path, false);
}
- System.out.println("FAILED");
- System.exit(1);
+ System.out.println("SUCCESS");
}
}
|
bdde8687937ef1ff16af3d8daa743cf75222cb51
|
Vala
|
gtk+-2.0: Hide many unwanted user data and destroy notify arguments
Fixes bug 611021.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gtk+-2.0.vapi b/vapi/gtk+-2.0.vapi
index 66c9d6894e..f14830a69a 100644
--- a/vapi/gtk+-2.0.vapi
+++ b/vapi/gtk+-2.0.vapi
@@ -221,7 +221,7 @@ namespace Gtk {
public GLib.List<weak Gtk.Action> list_actions ();
public void remove_action (Gtk.Action action);
public void set_sensitive (bool sensitive);
- public void set_translate_func (Gtk.TranslateFunc func, void* data, GLib.DestroyNotify notify);
+ public void set_translate_func (owned Gtk.TranslateFunc func);
public void set_translation_domain (string domain);
public void set_visible (bool visible);
public unowned string translate_string (string str);
@@ -1476,7 +1476,7 @@ namespace Gtk {
public class FileFilter : Gtk.Object {
[CCode (has_construct_function = false)]
public FileFilter ();
- public void add_custom (Gtk.FileFilterFlags needed, Gtk.FileFilterFunc func, void* data, GLib.DestroyNotify notify);
+ public void add_custom (Gtk.FileFilterFlags needed, owned Gtk.FileFilterFunc func);
public void add_mime_type (string mime_type);
public void add_pattern (string pattern);
public void add_pixbuf_formats ();
@@ -2574,7 +2574,7 @@ namespace Gtk {
public void set_tab_label_text (Gtk.Widget child, string tab_text);
public void set_tab_pos (Gtk.PositionType pos);
public void set_tab_reorderable (Gtk.Widget child, bool reorderable);
- public static void set_window_creation_hook (Gtk.NotebookWindowCreationFunc func, void* data, GLib.DestroyNotify destroy);
+ public static void set_window_creation_hook (owned Gtk.NotebookWindowCreationFunc func);
[NoAccessorMethod]
public bool enable_popup { get; set; }
public void* group { get; set; }
@@ -3184,7 +3184,7 @@ namespace Gtk {
public RecentFilter ();
public void add_age (int days);
public void add_application (string application);
- public void add_custom (Gtk.RecentFilterFlags needed, Gtk.RecentFilterFunc func, void* data, GLib.DestroyNotify data_destroy);
+ public void add_custom (Gtk.RecentFilterFlags needed, owned Gtk.RecentFilterFunc func);
public void add_group (string group);
public void add_mime_type (string mime_type);
public void add_pattern (string pattern);
@@ -4057,9 +4057,9 @@ namespace Gtk {
public void move_mark_by_name (string name, Gtk.TextIter where);
public void paste_clipboard (Gtk.Clipboard clipboard, Gtk.TextIter? override_location, bool default_editable);
public void place_cursor (Gtk.TextIter where);
- public Gdk.Atom register_deserialize_format (string mime_type, Gtk.TextBufferDeserializeFunc function, GLib.DestroyNotify user_data_destroy);
+ public Gdk.Atom register_deserialize_format (string mime_type, owned Gtk.TextBufferDeserializeFunc function);
public Gdk.Atom register_deserialize_tagset (string tagset_name);
- public Gdk.Atom register_serialize_format (string mime_type, Gtk.TextBufferSerializeFunc function, GLib.DestroyNotify user_data_destroy);
+ public Gdk.Atom register_serialize_format (string mime_type, owned Gtk.TextBufferSerializeFunc function);
public Gdk.Atom register_serialize_tagset (string tagset_name);
public void remove_all_tags (Gtk.TextIter start, Gtk.TextIter end);
public void remove_selection_clipboard (Gtk.Clipboard clipboard);
@@ -4592,7 +4592,7 @@ namespace Gtk {
public unowned Gtk.TreePath convert_path_to_child_path (Gtk.TreePath filter_path);
public unowned Gtk.TreeModel get_model ();
public void refilter ();
- public void set_modify_func (int n_columns, GLib.Type[] types, Gtk.TreeModelFilterModifyFunc func, void* data, GLib.DestroyNotify destroy);
+ public void set_modify_func (int n_columns, GLib.Type[] types, owned Gtk.TreeModelFilterModifyFunc func);
public void set_visible_column (int column);
public void set_visible_func (owned Gtk.TreeModelFilterVisibleFunc func);
[NoAccessorMethod]
@@ -4695,7 +4695,7 @@ namespace Gtk {
public void select_range (Gtk.TreePath start_path, Gtk.TreePath end_path);
public void selected_foreach (Gtk.TreeSelectionForeachFunc func);
public void set_mode (Gtk.SelectionMode type);
- public void set_select_function (Gtk.TreeSelectionFunc func, GLib.DestroyNotify? destroy);
+ public void set_select_function (owned Gtk.TreeSelectionFunc func);
public void unselect_all ();
public void unselect_iter (Gtk.TreeIter iter);
public void unselect_path (Gtk.TreePath path);
@@ -4812,10 +4812,10 @@ namespace Gtk {
public int remove_column (Gtk.TreeViewColumn column);
public void scroll_to_cell (Gtk.TreePath? path, Gtk.TreeViewColumn? column, bool use_align, float row_align, float col_align);
public void scroll_to_point (int tree_x, int tree_y);
- public void set_column_drag_function (Gtk.TreeViewColumnDropFunc func, GLib.DestroyNotify destroy);
+ public void set_column_drag_function (owned Gtk.TreeViewColumnDropFunc func);
public void set_cursor (Gtk.TreePath path, Gtk.TreeViewColumn? focus_column, bool start_editing);
public void set_cursor_on_cell (Gtk.TreePath path, Gtk.TreeViewColumn focus_column, Gtk.CellRenderer focus_cell, bool start_editing);
- public void set_destroy_count_func (Gtk.TreeDestroyCountFunc func, void* data, GLib.DestroyNotify destroy);
+ public void set_destroy_count_func (owned Gtk.TreeDestroyCountFunc func);
public void set_drag_dest_row (Gtk.TreePath? path, Gtk.TreeViewDropPosition pos);
public void set_enable_search (bool enable_search);
public void set_enable_tree_lines (bool enabled);
@@ -4836,7 +4836,7 @@ namespace Gtk {
public void set_search_column (int column);
public void set_search_entry (Gtk.Entry entry);
public void set_search_equal_func (owned Gtk.TreeViewSearchEqualFunc search_equal_func);
- public void set_search_position_func (Gtk.TreeViewSearchPositionFunc func, void* data, GLib.DestroyNotify destroy);
+ public void set_search_position_func (owned Gtk.TreeViewSearchPositionFunc func);
public void set_show_expanders (bool enabled);
public void set_tooltip_cell (Gtk.Tooltip tooltip, Gtk.TreePath path, Gtk.TreeViewColumn column, Gtk.CellRenderer cell);
public void set_tooltip_column (int column);
@@ -5741,7 +5741,7 @@ namespace Gtk {
public void set_show_not_found (bool show_not_found);
public void set_show_private (bool show_private);
public void set_show_tips (bool show_tips);
- public abstract void set_sort_func (Gtk.RecentSortFunc sort_func, void* sort_data, GLib.DestroyNotify data_destroy);
+ public abstract void set_sort_func (owned Gtk.RecentSortFunc sort_func);
public void set_sort_type (Gtk.RecentSortType sort_type);
public abstract void unselect_all ();
public abstract void unselect_uri (string uri);
@@ -7059,16 +7059,16 @@ namespace Gtk {
public delegate bool RecentFilterFunc (Gtk.RecentFilterInfo filter_info);
[CCode (cheader_filename = "gtk/gtk.h")]
public delegate int RecentSortFunc (Gtk.RecentInfo a, Gtk.RecentInfo b);
- [CCode (cheader_filename = "gtk/gtk.h", has_target = false)]
- public delegate bool TextBufferDeserializeFunc (Gtk.TextBuffer register_buffer, Gtk.TextBuffer content_buffer, Gtk.TextIter iter, uchar data, size_t length, bool create_tags, void* user_data, GLib.Error error);
+ [CCode (cheader_filename = "gtk/gtk.h")]
+ public delegate bool TextBufferDeserializeFunc (Gtk.TextBuffer register_buffer, Gtk.TextBuffer content_buffer, Gtk.TextIter iter, uchar data, size_t length, bool create_tags, GLib.Error error);
[CCode (cheader_filename = "gtk/gtk.h")]
public delegate uchar TextBufferSerializeFunc (Gtk.TextBuffer register_buffer, Gtk.TextBuffer content_buffer, Gtk.TextIter start, Gtk.TextIter end, size_t length);
[CCode (cheader_filename = "gtk/gtk.h")]
public delegate bool TextCharPredicate (unichar ch);
[CCode (cheader_filename = "gtk/gtk.h")]
public delegate void TextTagTableForeach (Gtk.TextTag tag);
- [CCode (cheader_filename = "gtk/gtk.h", has_target = false)]
- public delegate unowned string TranslateFunc (string path, void* func_data);
+ [CCode (cheader_filename = "gtk/gtk.h")]
+ public delegate unowned string TranslateFunc (string path);
[CCode (cheader_filename = "gtk/gtk.h")]
public delegate void TreeCellDataFunc (Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel tree_model, Gtk.TreeIter iter);
[CCode (cheader_filename = "gtk/gtk.h")]
@@ -7708,7 +7708,7 @@ namespace Gtk {
[CCode (cheader_filename = "gtk/gtk.h")]
public static bool stock_lookup (string stock_id, Gtk.StockItem item);
[CCode (cheader_filename = "gtk/gtk.h")]
- public static void stock_set_translate_func (string domain, Gtk.TranslateFunc func, void* data, GLib.DestroyNotify notify);
+ public static void stock_set_translate_func (string domain, owned Gtk.TranslateFunc func);
[CCode (cheader_filename = "gtk/gtk.h")]
public static void target_table_free (Gtk.TargetEntry[] targets);
[CCode (cheader_filename = "gtk/gtk.h")]
diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
index 1210297d66..896453dfb2 100644
--- a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
+++ b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata
@@ -30,6 +30,9 @@ gtk_action_group_add_radio_actions_full.destroy nullable="1"
gtk_action_group_add_toggle_actions.user_data hidden="0"
gtk_action_group_add_toggle_actions_full.user_data hidden="0"
gtk_action_group_add_toggle_actions_full.destroy nullable="1"
+gtk_action_group_set_translate_func.func transfer_ownership="1"
+gtk_action_group_set_translate_func.data hidden="1"
+gtk_action_group_set_translate_func.notify hidden="1"
gtk_action_group_list_actions transfer_ownership="1" type_arguments="unowned Action"
GtkAdjustment::changed has_emitter="1"
GtkAdjustment::value_changed has_emitter="1"
@@ -168,6 +171,9 @@ gtk_file_chooser_dialog_new.title nullable="1"
gtk_file_chooser_dialog_new.parent nullable="1"
gtk_file_chooser_dialog_new_with_backend.title nullable="1"
gtk_file_chooser_dialog_new_with_backend.parent nullable="1"
+gtk_file_filter_add_custom.func transfer_ownership="1"
+gtk_file_filter_add_custom.data hidden="1"
+gtk_file_filter_add_custom.notify hidden="1"
gtk_file_chooser_list_filters transfer_ownership="1" type_arguments="unowned FileFilter"
gtk_file_chooser_list_shortcut_folder_uris nullable="1" transfer_ownership="1" type_arguments="string"
gtk_file_chooser_list_shortcut_folders nullable="1" transfer_ownership="1" type_arguments="string"
@@ -296,6 +302,9 @@ gtk_notebook_append_page_menu.menu_label nullable="1"
gtk_notebook_prepend_page.tab_label nullable="1"
gtk_notebook_prepend_page_menu.tab_label nullable="1"
gtk_notebook_prepend_page_menu.menu_label nullable="1"
+gtk_notebook_set_window_creation_hook.func transfer_ownership="1"
+gtk_notebook_set_window_creation_hook.data hidden="1"
+gtk_notebook_set_window_creation_hook.destroy hidden="1"
gtk_notebook_insert_page virtual="0"
gtk_notebook_insert_page.tab_label nullable="1"
gtk_notebook_insert_page_menu virtual="1" vfunc_name="insert_page"
@@ -403,6 +412,9 @@ gtk_radio_tool_button_get_group type_arguments="RadioToolButton"
gtk_radio_tool_button_new.group nullable="1" type_arguments="RadioToolButton"
gtk_radio_tool_button_new_from_stock.group nullable="1" type_arguments="RadioToolButton"
gtk_radio_tool_button_set_group.group type_arguments="RadioToolButton"
+gtk_recent_chooser_set_sort_func.sort_func transfer_ownership="1"
+gtk_recent_chooser_set_sort_func.sort_data hidden="1"
+gtk_recent_chooser_set_sort_func.data_destroy hidden="1"
gtk_recent_chooser_get_items transfer_ownership="1" type_arguments="RecentInfo"
gtk_recent_chooser_list_filters transfer_ownership="1" type_arguments="unowned RecentFilter"
gtk_recent_manager_get_items transfer_ownership="1" type_arguments="RecentInfo"
@@ -413,6 +425,9 @@ GtkRecentData.mime_type weak="0"
GtkRecentData.app_name weak="0"
GtkRecentData.app_exec weak="0"
GtkRecentData.groups is_array="1" weak="0" array_null_terminated="1"
+gtk_recent_filter_add_custom.func transfer_ownership="1"
+gtk_recent_filter_add_custom.data hidden="1"
+gtk_recent_filter_add_custom.data_destroy hidden="1"
GtkRequisition is_value_type="1"
gtk_rc_get_style_by_paths nullable="1"
gtk_rc_get_style_by_paths.widget_path nullable="1"
@@ -446,6 +461,9 @@ GtkStatusIcon::button_release_event.event namespace_name="Gdk" type_name="EventB
gtk_status_icon_get_geometry.area is_out="1"
gtk_status_icon_get_geometry.orientation is_out="1"
gtk_status_icon_position_menu hidden="1"
+gtk_stock_set_translate_func.func transfer_ownership="1"
+gtk_stock_set_translate_func.data hidden="1"
+gtk_stock_set_translate_func.notify hidden="1"
gtk_stock_list_ids transfer_ownership="1" type_arguments="string"
GtkStockItem is_value_type="1"
GtkStyle.fg weak="0"
@@ -495,7 +513,13 @@ gtk_text_buffer_get_selection_bounds.start is_out="1"
gtk_text_buffer_get_selection_bounds.end is_out="1"
gtk_text_buffer_get_start_iter.iter is_out="1"
gtk_text_buffer_paste_clipboard.override_location nullable="1"
+gtk_text_buffer_register_deserialize_format.function transfer_ownership="1"
+gtk_text_buffer_register_deserialize_format.user_data_destroy hidden="1"
+gtk_text_buffer_register_serialize_format.function transfer_ownership="1"
+gtk_text_buffer_register_serialize_format.user_data_destroy hidden="1"
gtk_text_buffer_new.table nullable="1"
+GtkTextBufferDeserializeFunc.user_data hidden="1"
+GtkTextBufferDeserializeFunc has_target="1"
GtkTextIter is_value_type="1"
gtk_text_iter_get_marks transfer_ownership="1" type_arguments="unowned TextMark"
gtk_text_iter_get_tags transfer_ownership="1" type_arguments="unowned TextTag"
@@ -539,6 +563,8 @@ gtk_tool_button_new.icon_widget nullable="1"
gtk_tool_button_new.label nullable="1"
gtk_tool_item_toolbar_reconfigured hidden="1"
GtkToolItem::set_tooltip hidden="1"
+GtkTranslateFunc has_target="1"
+GtkTranslateFunc.func_data hidden="1"
GtkTreeIter is_value_type="1"
GtkTreeRowReference is_value_type="0" is_immutable="1"
gtk_tree_row_reference_copy transfer_ownership="1"
@@ -564,6 +590,9 @@ GtkTreeModel::row_inserted has_emitter="1"
GtkTreeModel::rows_reordered has_emitter="1"
gtk_tree_model_filter_convert_child_iter_to_iter.filter_iter is_out="1"
gtk_tree_model_filter_convert_iter_to_child_iter.child_iter is_out="1"
+gtk_tree_model_filter_set_modify_func.func transfer_ownership="1"
+gtk_tree_model_filter_set_modify_func.data hidden="1"
+gtk_tree_model_filter_set_modify_func.destroy hidden="1"
gtk_tree_model_filter_set_visible_func.func transfer_ownership="1"
gtk_tree_model_filter_set_visible_func.data hidden="1"
gtk_tree_model_filter_set_visible_func.destroy hidden="1"
@@ -580,8 +609,9 @@ gtk_tree_row_reference_get_path transfer_ownership="1"
gtk_tree_selection_get_selected.iter is_out="1"
gtk_tree_selection_get_selected_rows transfer_ownership="1" type_arguments="TreePath"
gtk_tree_selection_selected_foreach.data hidden="1"
+gtk_tree_selection_set_select_function.func transfer_ownership="1"
gtk_tree_selection_set_select_function.data hidden="1"
-gtk_tree_selection_set_select_function.destroy nullable="1"
+gtk_tree_selection_set_select_function.destroy hidden="1"
gtk_tree_store_new ellipsis="1"
gtk_tree_store_newv.n_columns hidden="1"
gtk_tree_store_newv.types array_length_pos="0.9"
@@ -662,6 +692,11 @@ gtk_tree_view_insert_column_with_data_func.func transfer_ownership="1"
gtk_tree_view_insert_column_with_data_func.data hidden="1"
gtk_tree_view_insert_column_with_data_func.dnotify hidden="1"
gtk_tree_view_row_expanded name="is_row_expanded"
+gtk_tree_view_set_column_drag_function.func transfer_ownership="1"
+gtk_tree_view_set_column_drag_function.destroy hidden="1"
+gtk_tree_view_set_destroy_count_func.func transfer_ownership="1"
+gtk_tree_view_set_destroy_count_func.data hidden="1"
+gtk_tree_view_set_destroy_count_func.destroy hidden="1"
gtk_tree_view_set_model.model nullable="1"
gtk_tree_view_set_row_separator_func.func transfer_ownership="1"
gtk_tree_view_set_row_separator_func.data hidden="1"
@@ -669,6 +704,9 @@ gtk_tree_view_set_row_separator_func.destroy hidden="1"
gtk_tree_view_set_search_equal_func.search_equal_func transfer_ownership="1"
gtk_tree_view_set_search_equal_func.search_user_data hidden="1"
gtk_tree_view_set_search_equal_func.search_destroy hidden="1"
+gtk_tree_view_set_search_position_func.func transfer_ownership="1"
+gtk_tree_view_set_search_position_func.data hidden="1"
+gtk_tree_view_set_search_position_func.destroy hidden="1"
gtk_tree_view_scroll_to_cell.path nullable="1"
gtk_tree_view_scroll_to_cell.column nullable="1"
gtk_tree_view_set_cursor.focus_column nullable="1"
|
3608ceda0894e4db6d742c33fb85a9af5d6775f1
|
cyberfox$jbidwatcher
|
Move the caching functionality out into its own ActiveRecordCache class, so it doesn't complexify the ActiveRecord class unnecessarily.
git-svn-id: svn://svn.jbidwatcher.com/jbidwatcher/trunk@509 b1acfa68-eb39-11db-b167-a3a8cd6b847e
|
p
|
https://github.com/cyberfox/jbidwatcher
|
diff --git a/src/com/jbidwatcher/app/MacFriendlyFrame.java b/src/com/jbidwatcher/app/MacFriendlyFrame.java
index 67095e7e..b43cef05 100644
--- a/src/com/jbidwatcher/app/MacFriendlyFrame.java
+++ b/src/com/jbidwatcher/app/MacFriendlyFrame.java
@@ -2,7 +2,7 @@
import com.jbidwatcher.util.config.JConfig;
import com.jbidwatcher.util.queue.MQFactory;
-import com.jbidwatcher.util.db.ActiveRecord;
+import com.jbidwatcher.util.db.ActiveRecordCache;
import com.jbidwatcher.util.Constants;
import com.jbidwatcher.auction.server.AuctionStats;
import com.jbidwatcher.auction.server.AuctionServerManager;
@@ -82,7 +82,7 @@ public void windowClosing(WindowEvent we) {
}
public void handleQuit() {
- ActiveRecord.saveCached();
+ ActiveRecordCache.saveCached();
if (!(JConfig.queryConfiguration("prompt.snipe_quit", "false").equals("true")) &&
(AuctionsManager.getInstance().anySnipes())) {
MQFactory.getConcrete("Swing").enqueue(UIBackbone.QUIT_MSG);
@@ -141,7 +141,7 @@ public static Properties getColumnProperties() {
* if there are any outstanding snipes.
*/
public void shutdown() {
- ActiveRecord.saveCached();
+ ActiveRecordCache.saveCached();
if (AuctionsManager.getInstance().anySnipes()) {
OptionUI oui = new OptionUI();
// Use the right parent! FIXME -- mrs: 17-February-2003 23:53
diff --git a/src/com/jbidwatcher/auction/AuctionEntry.java b/src/com/jbidwatcher/auction/AuctionEntry.java
index e7a02ff2..e76e6ced 100644
--- a/src/com/jbidwatcher/auction/AuctionEntry.java
+++ b/src/com/jbidwatcher/auction/AuctionEntry.java
@@ -18,6 +18,7 @@
import com.jbidwatcher.util.queue.MQFactory;
import com.jbidwatcher.util.db.ActiveRecord;
import com.jbidwatcher.util.db.Table;
+import com.jbidwatcher.util.db.ActiveRecordCache;
import com.jbidwatcher.util.xml.XMLElement;
import java.io.FileNotFoundException;
@@ -300,7 +301,7 @@ public static AuctionEntry buildEntry(String auctionIdentifier) {
if(ae.isLoaded()) {
String id = ae.saveDB();
if (id != null) {
- cache(ae.getClass(), "id", id, ae);
+ ActiveRecordCache.cache(ae.getClass(), "id", id, ae);
return ae;
}
}
@@ -1750,6 +1751,10 @@ public String saveDB() {
private static Table sDB = null;
protected static String getTableName() { return "entries"; }
protected Table getDatabase() {
+ return getRealDatabase();
+ }
+
+ private static Table getRealDatabase() {
if(sDB == null) {
sDB = openDB(getTableName());
}
@@ -1760,6 +1765,10 @@ public static AuctionEntry findFirstBy(String key, String value) {
return (AuctionEntry) ActiveRecord.findFirstBy(AuctionEntry.class, key, value);
}
+ public static List<AuctionEntry> findAllSniped() {
+ return (List<AuctionEntry>) ActiveRecord.findAllBySQL(AuctionEntry.class, "SELECT * FROM " + getTableName() + " WHERE (snipe_id is not null or multisnipe_id is not null)");
+ }
+
public static AuctionEntry findByIdentifier(String identifier) {
AuctionInfo ai = AuctionInfo.findFirstBy("identifier", identifier);
AuctionEntry ae = null;
diff --git a/src/com/jbidwatcher/auction/AuctionInfo.java b/src/com/jbidwatcher/auction/AuctionInfo.java
index 5aab627f..a46a3536 100644
--- a/src/com/jbidwatcher/auction/AuctionInfo.java
+++ b/src/com/jbidwatcher/auction/AuctionInfo.java
@@ -449,7 +449,7 @@ protected void setSellerName(String sellerName) {
if (raw_id != null && raw_id.length() != 0) seller_id = Integer.parseInt(raw_id);
}
setInteger("seller_id", seller_id);
- cache(AuctionInfo.class);
+ ActiveRecordCache.cache(this);
}
public Currency getUSCur() { return getMonetary("us_cur", Currency.US_DOLLAR); }
@@ -520,7 +520,7 @@ public static AuctionInfo findFirstBy(String key, String value) {
}
public static int precache() {
- return precacheBySQL(AuctionInfo.class, "SELECT * FROM auctions WHERE id IN (SELECT auction_id FROM entries)", "id", "identifier");
+ return ActiveRecordCache.precacheBySQL(AuctionInfo.class, "SELECT * FROM auctions WHERE id IN (SELECT auction_id FROM entries)", "id", "identifier");
}
public static boolean deleteAll(List<AuctionInfo> toDelete) {
@@ -531,7 +531,7 @@ public static boolean deleteAll(List<AuctionInfo> toDelete) {
}
public void delete() {
- super.uncache(AuctionInfo.class, "identifier", get("identifier"));
+ ActiveRecordCache.uncache(AuctionInfo.class, "identifier", get("identifier"));
super.delete(AuctionInfo.class);
}
}
diff --git a/src/com/jbidwatcher/auction/server/AuctionServerManager.java b/src/com/jbidwatcher/auction/server/AuctionServerManager.java
index 778d8d65..9a83f6f7 100644
--- a/src/com/jbidwatcher/auction/server/AuctionServerManager.java
+++ b/src/com/jbidwatcher/auction/server/AuctionServerManager.java
@@ -13,6 +13,7 @@
import com.jbidwatcher.util.config.ErrorManagement;
import com.jbidwatcher.util.StringTools;
import com.jbidwatcher.util.db.ActiveRecord;
+import com.jbidwatcher.util.db.ActiveRecordCache;
import com.jbidwatcher.util.xml.XMLElement;
import com.jbidwatcher.util.xml.XMLParseException;
import com.jbidwatcher.util.xml.XMLSerialize;
@@ -115,17 +116,17 @@ public void fromXML(XMLElement inXML) {
public void loadAuctionsFromDB(AuctionServer newServer) {
MQFactory.getConcrete("splash").enqueue("SET 0");
- ActiveRecord.precache(Seller.class);
+ ActiveRecordCache.precache(Seller.class);
MQFactory.getConcrete("splash").enqueue("SET 25");
- ActiveRecord.precache(Seller.class, "seller");
+ ActiveRecordCache.precache(Seller.class, "seller");
MQFactory.getConcrete("splash").enqueue("SET 50");
- ActiveRecord.precache(Category.class);
+ ActiveRecordCache.precache(Category.class);
MQFactory.getConcrete("splash").enqueue("SET 75");
- ActiveRecord.precache(AuctionEntry.class, "auction_id");
+ ActiveRecordCache.precache(AuctionEntry.class, "auction_id");
MQFactory.getConcrete("splash").enqueue("SET 0");
int count = 0;
- Map<String, ActiveRecord> entries = ActiveRecord.getCache(AuctionEntry.class);
+ Map<String, ActiveRecord> entries = ActiveRecordCache.getCache(AuctionEntry.class);
for(String auction_id : entries.keySet()) {
AuctionEntry ae = (AuctionEntry) entries.get(auction_id);
ae.setServer(newServer);
diff --git a/src/com/jbidwatcher/ui/JBidMouse.java b/src/com/jbidwatcher/ui/JBidMouse.java
index 19350106..bbb7dd7b 100644
--- a/src/com/jbidwatcher/ui/JBidMouse.java
+++ b/src/com/jbidwatcher/ui/JBidMouse.java
@@ -20,7 +20,7 @@
import com.jbidwatcher.ui.config.JConfigFrame;
import com.jbidwatcher.ui.config.JConfigTab;
import com.jbidwatcher.ui.util.OptionUI;
-import com.jbidwatcher.util.db.ActiveRecord;
+import com.jbidwatcher.util.db.ActiveRecordCache;
import com.jbidwatcher.util.queue.MQFactory;
import com.jbidwatcher.util.queue.AuctionQObject;
import com.jbidwatcher.util.queue.MessageQueue;
@@ -1601,7 +1601,7 @@ protected void DoAction(Object src, String actionString, AuctionEntry whichAucti
else if(actionString.equals("Toolbar")) DoHideShowToolbar();
else if(actionString.equals("Search")) DoSearch();
else if(actionString.equals("Scripting")) DoScripting();
- else if(actionString.equals("Dump")) ActiveRecord.saveCached();
+ else if(actionString.equals("Dump")) ActiveRecordCache.saveCached();
else if(actionString.equals("Forum")) MQFactory.getConcrete("browse").enqueue("http://forum.jbidwatcher.com");
else if(actionString.equals("View Log")) DoViewLog();
else if(actionString.equals("View Activity")) DoViewActivity();
diff --git a/src/com/jbidwatcher/util/HashBacked.java b/src/com/jbidwatcher/util/HashBacked.java
index 1c3fc218..2eabdcc2 100644
--- a/src/com/jbidwatcher/util/HashBacked.java
+++ b/src/com/jbidwatcher/util/HashBacked.java
@@ -37,7 +37,7 @@ public HashBacked(Record data) {
public void setTranslationTable(Map<String, String> table) { if(mTranslationTable == null) mTranslationTable = table; }
- protected boolean isDirty() { return mDirty; }
+ public boolean isDirty() { return mDirty; }
protected void clearDirty() { mDirty = false; }
protected void setDirty() { mDirty = true; }
@@ -225,7 +225,7 @@ protected XMLElement addBooleanChild(XMLElement parent, String name) {
}
public Record getBacking() { return mBacking; }
- protected void setBacking(Record r) {
+ public void setBacking(Record r) {
mBacking = r;
if(get("currency") == null) mDefaultCurrency = ONE_DOLLAR.fullCurrencyName();
else mDefaultCurrency = get("currency");
diff --git a/src/com/jbidwatcher/util/db/ActiveRecord.java b/src/com/jbidwatcher/util/db/ActiveRecord.java
deleted file mode 100644
index 5b4a8070..00000000
--- a/src/com/jbidwatcher/util/db/ActiveRecord.java
+++ /dev/null
@@ -1,259 +0,0 @@
-package com.jbidwatcher.util.db;
-
-import com.jbidwatcher.util.HashBacked;
-import com.jbidwatcher.util.SoftMap;
-import com.jbidwatcher.util.Record;
-
-import java.util.*;
-import java.lang.reflect.Field;
-import java.lang.reflect.Member;
-
-/**
- * Provides utility methods for database-backed objects.
- *
- * User: Morgan
- * Date: Oct 21, 2007
- * Time: 1:54:46 PM
- * To change this template use File | Settings | File Templates.
- */
-public abstract class ActiveRecord extends HashBacked {
- protected static Table openDB(String tableName) {
- if (tableName == null) return null;
-
- Table db;
- try {
- db = new Table(tableName);
- } catch (Exception e) {
- throw new RuntimeException("Can't access the " + tableName + " database table", e);
- }
- return db;
- }
-
- private static Table getTable(Object o) {
- ActiveRecord record = (ActiveRecord) o;
- return record.getDatabase();
- }
-
- protected abstract Table getDatabase();
-
- /**
- * This returns the count of entries in the table.
- *
- * @return - The count of entries in the database table.
- */
- public int count() {
- return getDatabase().count();
- }
-
- public void commit() {
- getDatabase().commit();
- }
-
- private void saveAssociations() {
- Set<String> colNames=getDatabase().getColumns();
- for(String name : colNames) {
- if(name.endsWith("_id")) {
- String className = name.substring(0, name.length()-3);
- String member = "m" + classify(className);
-
- // TODO -- Inspect for 'member', instanceof ActiveRecord.
- // TODO -- set("#{name}", member.saveDB())
- }
- }
- }
-
- // Upcase first letter, and each letter after an '_', and remove all '_'...
- private String classify(String className) {
- return String.valueOf(className.charAt(0)).toUpperCase() + className.substring(1);
- }
-
- // TODO -- Look for columns of type: {foo}_id
- // For each of those, introspect for 'm{Foo}'.
- // For each non-null of those, call 'saveDB' on it.
- // Store the result of that call as '{foo}_id'.
- public String saveDB() {
- if(getDatabase().hasColumn("currency")) {
- setString("currency", getDefaultCurrency().fullCurrencyName());
- }
- if(!isDirty() && get("id") != null && get("id").length() != 0) return get("id");
- String id = getDatabase().insertOrUpdate(getBacking());
- commit();
- if(id != null && id.length() != 0) set("id", id); else id = get("id");
- clearDirty();
- return id;
- }
-
- public boolean delete(Class klass) {
- String id = get("id");
- uncache(klass, "id", id);
- return id != null && getDatabase().delete(Integer.parseInt(id));
- }
-
- protected static ActiveRecord findFirstBy(Class klass, String key, String value) {
- ActiveRecord cached = cached(klass, key, value);
- if(cached != null) return cached;
-
- return findFirstByUncached(klass, key, value);
- }
-
- private static ActiveRecord findFirstByUncached(Class klass, String key, String value) {
- ActiveRecord found;
- try {
- found = (ActiveRecord)klass.newInstance();
- } catch (Exception e) {
- throw new RuntimeException("Can't instantiate " + klass.getName(), e);
- }
- Record result = getTable(found).findFirstBy(key, value);
- if (result != null && !result.isEmpty()) {
- found.setBacking(result);
- } else {
- found = null;
- }
- if(found != null) cache(klass, key, value, found);
- return found;
- }
-
- protected static List<ActiveRecord> findAllBy(Class klass, String key, String value) {
- return findAllBy(klass, key, value, null);
- }
-
- protected static List<ActiveRecord> findAllBy(Class klass, String key, String value, String order) {
- ActiveRecord found;
- try {
- found = (ActiveRecord) klass.newInstance();
- } catch (Exception e) {
- throw new RuntimeException("Can't instantiate " + klass.getName(), e);
- }
-
- List<Record> results = getTable(found).findAll(key, value, order);
- List<ActiveRecord> rval = new ArrayList<ActiveRecord>();
-
- try {
- for (Record record : results) {
- ActiveRecord row = (ActiveRecord) klass.newInstance();
- row.setBacking(record);
- rval.add(row);
- }
-
- return rval;
- } catch (InstantiationException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- } catch (IllegalAccessException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
-
- return null;
- }
-
- private final static Map<Class, SoftMap<String, ActiveRecord>> sCache=new HashMap<Class, SoftMap<String, ActiveRecord>>();
-
- public static Map<String, ActiveRecord> getCache(final Class klass) {
- SoftMap<String, ActiveRecord> klassCache = sCache.get(klass);
- if(klassCache == null) {
- klassCache = new SoftMap<String, ActiveRecord>() {
- public ActiveRecord reload(Object key) {
- String[] pair = ((String)key).split(":");
- return findFirstByUncached(klass, pair[0], pair[1]);
- }
- };
- sCache.put(klass, klassCache);
- }
- return klassCache;
- }
-
- protected void uncache(Class klass, String key, String value) {
- String combined = key + ':' + value;
- getCache(klass).remove(combined);
- }
-
- private static ActiveRecord cached(Class klass, String key, String value) {
- String combined = key + ':' + value;
- return getCache(klass).get(combined);
- }
-
- protected static void cache(Class klass, String key, String value, ActiveRecord result) {
- String combined = key + ':' + value;
- getCache(klass).put(combined, result);
- }
-
- protected void cache(Class klass) {
- cache(klass, "id", getString("id"), this);
- }
-
- public static int precache(Class klass, String key) {
- List<Record> results = null;
- try {
- ActiveRecord o = (ActiveRecord) klass.newInstance();
- results = getTable(o).findAll();
-// boolean first = true;
- for (Record record : results) {
- ActiveRecord row = (ActiveRecord) klass.newInstance();
- row.setBacking(record);
- cache(klass, key, row.get(key), row);
- }
- } catch (Exception e) {
- // Ignore, as this is just for pre-caching...
- }
- return results == null ? 0 : results.size();
- }
-
- public static int precacheBySQL(Class klass, String sql, String... columns) {
- List<Record> results = null;
- try {
- ActiveRecord o = (ActiveRecord) klass.newInstance();
- results = getTable(o).findAll(sql);
-
- for (Record record : results) {
- ActiveRecord row = (ActiveRecord) klass.newInstance();
- row.setBacking(record);
- if(columns == null) {
- cache(klass, "id", row.get("id"), row);
- } else {
- for (String col : columns) {
- cache(klass, col, row.get(col), row);
- }
- }
- }
- } catch (Exception e) {
- // Ignore, as this is just for pre-caching...
- }
- return results == null ? 0 : results.size();
- }
-
- public static void saveCached() {
- if(sCache == null) return;
-
- synchronized(sCache) {
- for (Class klass : sCache.keySet()) {
- Map<String, ActiveRecord> klassCache = sCache.get(klass);
- Collection<ActiveRecord> values = klassCache.values();
- if(values != null) for (ActiveRecord record : values) {
- if (record != null && record.isDirty()) {
- record.saveDB();
- }
- }
- }
- sCache.clear();
- }
- }
-
- public static int precache(Class klass) {
- return precache(klass, "id");
- }
-
- public Integer getId() { return getInteger("id"); }
-
- protected static String makeCommaList(List<? extends ActiveRecord> records) {
- StringBuffer ids = new StringBuffer("");
-
- boolean first = true;
- for(ActiveRecord id : records) {
- if(!first) {
- ids.append(", ");
- }
- ids.append(id.getId());
- first = false;
- }
- return ids.toString();
- }
-}
|
4dfb9b11c8a8ccfca75bb282c1b7ddef04c4e1c7
|
tapiji
|
adapt plugin versions
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml b/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml
index aa9fa0dc..fc68241c 100644
--- a/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml
+++ b/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml
@@ -130,7 +130,7 @@ This Agreement is governed by the laws of the State of New York and the intellec
id="org.eclipselabs.tapiji.tools.jsf"
download-size="0"
install-size="0"
- version="0.0.0"
+ version="0.0.1.qualifier"
unpack="false"/>
</feature>
|
829bc369078a940aa757f96b1cbf310fa4ac705f
|
intellij-community
|
fix--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/lang-api/src/com/intellij/psi/ResolveState.java b/lang-api/src/com/intellij/psi/ResolveState.java
index 34533739244d7..4915c2f1604fa 100644
--- a/lang-api/src/com/intellij/psi/ResolveState.java
+++ b/lang-api/src/com/intellij/psi/ResolveState.java
@@ -10,18 +10,19 @@
public class ResolveState {
private Map<Object, Object> myValues = null;
- private static final ResolveState ourInitialState = new ResolveState();
+ private static final ResolveState ourInitialState;
static {
- ResolveState.defaultsTo(PsiSubstitutor.KEY, PsiSubstitutor.EMPTY);
- }
+ ourInitialState = new ResolveState();
+ ourInitialState.myValues = new THashMap<Object, Object>();
+ }
public static ResolveState initial() {
return ourInitialState;
}
public static <T> void defaultsTo(Key<T> key, T value) {
- initial().put(key, value);
+ ourInitialState.myValues.put(key, value);
}
public <T> ResolveState put(Key<T> key, T value) {
diff --git a/openapi/src/com/intellij/psi/JavaPsiFacade.java b/openapi/src/com/intellij/psi/JavaPsiFacade.java
index 26e0879268edc..f5fc856185cfe 100644
--- a/openapi/src/com/intellij/psi/JavaPsiFacade.java
+++ b/openapi/src/com/intellij/psi/JavaPsiFacade.java
@@ -18,6 +18,9 @@ public static JavaPsiFacade getInstance(Project project) {
return ServiceManager.getService(project, JavaPsiFacade.class);
}
+ static {
+ ResolveState.defaultsTo(PsiSubstitutor.KEY, PsiSubstitutor.EMPTY);
+ }
/**
* Searches the project and all its libraries for a class with the specified full-qualified
|
e5ec49b123c4070355182f04397d8c8c347c9aff
|
hbase
|
HBASE-10818. Add integration test for bulkload- with replicas (Nick Dimiduk and Devaraj Das)--
|
p
|
https://github.com/apache/hbase
|
diff --git a/hbase-it/src/test/java/org/apache/hadoop/hbase/IntegrationTestRegionReplicaPerf.java b/hbase-it/src/test/java/org/apache/hadoop/hbase/IntegrationTestRegionReplicaPerf.java
index ca3a8f0e36e3..8ea27bfd5536 100644
--- a/hbase-it/src/test/java/org/apache/hadoop/hbase/IntegrationTestRegionReplicaPerf.java
+++ b/hbase-it/src/test/java/org/apache/hadoop/hbase/IntegrationTestRegionReplicaPerf.java
@@ -32,7 +32,6 @@
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.ipc.RpcClient;
import org.apache.hadoop.hbase.regionserver.DisabledRegionSplitPolicy;
-import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.mapreduce.Counters;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.ToolRunner;
@@ -222,42 +221,6 @@ protected Set<String> getColumnFamilies() {
return null;
}
- /**
- * Modify a table, synchronous. Waiting logic similar to that of {@code admin.rb#alter_status}.
- */
- private static void modifyTableSync(HBaseAdmin admin, HTableDescriptor desc) throws Exception {
- admin.modifyTable(desc.getTableName(), desc);
- Pair<Integer, Integer> status = new Pair<Integer, Integer>() {{
- setFirst(0);
- setSecond(0);
- }};
- for (int i = 0; status.getFirst() != 0 && i < 500; i++) { // wait up to 500 seconds
- status = admin.getAlterStatus(desc.getTableName());
- if (status.getSecond() != 0) {
- LOG.debug(status.getSecond() - status.getFirst() + "/" + status.getSecond()
- + " regions updated.");
- Thread.sleep(1 * 1000l);
- } else {
- LOG.debug("All regions updated.");
- }
- }
- if (status.getSecond() != 0) {
- throw new Exception("Failed to update replica count after 500 seconds.");
- }
- }
-
- /**
- * Set the number of Region replicas.
- */
- private static void setReplicas(HBaseAdmin admin, TableName table, int replicaCount)
- throws Exception {
- admin.disableTable(table);
- HTableDescriptor desc = admin.getTableDescriptor(table);
- desc.setRegionReplication(replicaCount);
- modifyTableSync(admin, desc);
- admin.enableTable(table);
- }
-
public void test() throws Exception {
int maxIters = 3;
String mr = nomapred ? "--nomapred" : "";
@@ -294,7 +257,7 @@ public void test() throws Exception {
// disable monkey, enable region replicas, enable monkey
cleanUpMonkey("Altering table.");
LOG.debug("Altering " + tableName + " replica count to " + replicaCount);
- setReplicas(util.getHBaseAdmin(), tableName, replicaCount);
+ util.setReplicas(util.getHBaseAdmin(), tableName, replicaCount);
setUpMonkey();
startMonkey();
diff --git a/hbase-it/src/test/java/org/apache/hadoop/hbase/mapreduce/IntegrationTestBulkLoad.java b/hbase-it/src/test/java/org/apache/hadoop/hbase/mapreduce/IntegrationTestBulkLoad.java
index dd4415bf5258..4112014bd2c9 100644
--- a/hbase-it/src/test/java/org/apache/hadoop/hbase/mapreduce/IntegrationTestBulkLoad.java
+++ b/hbase-it/src/test/java/org/apache/hadoop/hbase/mapreduce/IntegrationTestBulkLoad.java
@@ -18,8 +18,6 @@
*/
package org.apache.hadoop.hbase.mapreduce;
-import static org.junit.Assert.assertEquals;
-
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
@@ -28,6 +26,7 @@
import java.util.Map;
import java.util.Random;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.lang.RandomStringUtils;
@@ -38,14 +37,25 @@
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.HBaseTestingUtility;
+import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.IntegrationTestBase;
import org.apache.hadoop.hbase.IntegrationTestingUtility;
import org.apache.hadoop.hbase.IntegrationTests;
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.client.Consistency;
+import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
+import org.apache.hadoop.hbase.coprocessor.ObserverContext;
+import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
+import org.apache.hadoop.hbase.regionserver.InternalScanner;
+import org.apache.hadoop.hbase.regionserver.RegionScanner;
+import org.apache.hadoop.hbase.regionserver.StorefileRefresherChore;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.RegionSplitter;
@@ -69,6 +79,9 @@
import org.junit.Test;
import org.junit.experimental.categories.Category;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
/**
* Test Bulk Load and MR on a distributed cluster.
* It starts an MR job that creates linked chains
@@ -99,15 +112,17 @@
* hbase.IntegrationTestBulkLoad.tableName
* The name of the table.
*
+ * hbase.IntegrationTestBulkLoad.replicaCount
+ * How many region replicas to configure for the table under test.
*/
@Category(IntegrationTests.class)
public class IntegrationTestBulkLoad extends IntegrationTestBase {
private static final Log LOG = LogFactory.getLog(IntegrationTestBulkLoad.class);
- private static byte[] CHAIN_FAM = Bytes.toBytes("L");
- private static byte[] SORT_FAM = Bytes.toBytes("S");
- private static byte[] DATA_FAM = Bytes.toBytes("D");
+ private static final byte[] CHAIN_FAM = Bytes.toBytes("L");
+ private static final byte[] SORT_FAM = Bytes.toBytes("S");
+ private static final byte[] DATA_FAM = Bytes.toBytes("D");
private static String CHAIN_LENGTH_KEY = "hbase.IntegrationTestBulkLoad.chainLength";
private static int CHAIN_LENGTH = 500000;
@@ -123,9 +138,73 @@ public class IntegrationTestBulkLoad extends IntegrationTestBase {
private static String TABLE_NAME_KEY = "hbase.IntegrationTestBulkLoad.tableName";
private static String TABLE_NAME = "IntegrationTestBulkLoad";
+ private static String NUM_REPLICA_COUNT_KEY = "hbase.IntegrationTestBulkLoad.replicaCount";
+ private static int NUM_REPLICA_COUNT_DEFAULT = 1;
+
+ private static final String OPT_LOAD = "load";
+ private static final String OPT_CHECK = "check";
+
+ private boolean load = false;
+ private boolean check = false;
+
+ public static class SlowMeCoproScanOperations extends BaseRegionObserver {
+ static final AtomicLong sleepTime = new AtomicLong(2000);
+ Random r = new Random();
+ AtomicLong countOfNext = new AtomicLong(0);
+ AtomicLong countOfOpen = new AtomicLong(0);
+ public SlowMeCoproScanOperations() {}
+ @Override
+ public RegionScanner preScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> e,
+ final Scan scan, final RegionScanner s) throws IOException {
+ if (countOfOpen.incrementAndGet() % 4 == 0) { //slowdown openScanner randomly
+ slowdownCode(e);
+ }
+ return s;
+ }
+
+ @Override
+ public boolean preScannerNext(final ObserverContext<RegionCoprocessorEnvironment> e,
+ final InternalScanner s, final List<Result> results,
+ final int limit, final boolean hasMore) throws IOException {
+ //this will slow down a certain next operation if the conditions are met. The slowness
+ //will allow the call to go to a replica
+ if (countOfNext.incrementAndGet() % 4 == 0) {
+ slowdownCode(e);
+ }
+ return true;
+ }
+ protected void slowdownCode(final ObserverContext<RegionCoprocessorEnvironment> e) {
+ if (e.getEnvironment().getRegion().getRegionInfo().getReplicaId() == 0) {
+ try {
+ if (sleepTime.get() > 0) {
+ LOG.info("Sleeping for " + sleepTime.get() + " ms");
+ Thread.sleep(sleepTime.get());
+ }
+ } catch (InterruptedException e1) {
+ LOG.error(e1);
+ }
+ }
+ }
+ }
+
+ /**
+ * Modify table {@code getTableName()} to carry {@link SlowMeCoproScanOperations}.
+ */
+ private void installSlowingCoproc() throws IOException, InterruptedException {
+ int replicaCount = conf.getInt(NUM_REPLICA_COUNT_KEY, NUM_REPLICA_COUNT_DEFAULT);
+ if (replicaCount == NUM_REPLICA_COUNT_DEFAULT) return;
+
+ TableName t = TableName.valueOf(getTablename());
+ HBaseAdmin admin = util.getHBaseAdmin();
+ HTableDescriptor desc = admin.getTableDescriptor(t);
+ desc.addCoprocessor(SlowMeCoproScanOperations.class.getName());
+ HBaseTestingUtility.modifyTableSync(admin, desc);
+ }
+
@Test
public void testBulkLoad() throws Exception {
runLoad();
+ installSlowingCoproc();
runCheck();
}
@@ -145,7 +224,7 @@ private byte[][] getSplits(int numRegions) {
return split.split(numRegions);
}
- private void setupTable() throws IOException {
+ private void setupTable() throws IOException, InterruptedException {
if (util.getHBaseAdmin().tableExists(getTablename())) {
util.deleteTable(getTablename());
}
@@ -155,6 +234,12 @@ private void setupTable() throws IOException {
new byte[][]{CHAIN_FAM, SORT_FAM, DATA_FAM},
getSplits(16)
);
+
+ int replicaCount = conf.getInt(NUM_REPLICA_COUNT_KEY, NUM_REPLICA_COUNT_DEFAULT);
+ if (replicaCount == NUM_REPLICA_COUNT_DEFAULT) return;
+
+ TableName t = TableName.valueOf(getTablename());
+ HBaseTestingUtility.setReplicas(util.getHBaseAdmin(), t, replicaCount);
}
private void runLinkedListMRJob(int iteration) throws Exception {
@@ -556,23 +641,23 @@ private void runCheck() throws IOException, ClassNotFoundException, InterruptedE
Path p = util.getDataTestDirOnTestFS(jobName);
Job job = new Job(conf);
-
job.setJarByClass(getClass());
+ job.setJobName(jobName);
job.setPartitionerClass(NaturalKeyPartitioner.class);
job.setGroupingComparatorClass(NaturalKeyGroupingComparator.class);
job.setSortComparatorClass(CompositeKeyComparator.class);
- Scan s = new Scan();
- s.addFamily(CHAIN_FAM);
- s.addFamily(SORT_FAM);
- s.setMaxVersions(1);
- s.setCacheBlocks(false);
- s.setBatch(1000);
+ Scan scan = new Scan();
+ scan.addFamily(CHAIN_FAM);
+ scan.addFamily(SORT_FAM);
+ scan.setMaxVersions(1);
+ scan.setCacheBlocks(false);
+ scan.setBatch(1000);
TableMapReduceUtil.initTableMapperJob(
Bytes.toBytes(getTablename()),
- new Scan(),
+ scan,
LinkedListCheckingMapper.class,
LinkKey.class,
LinkChain.class,
@@ -595,6 +680,10 @@ private void runCheck() throws IOException, ClassNotFoundException, InterruptedE
public void setUpCluster() throws Exception {
util = getTestingUtil(getConf());
util.initializeCluster(1);
+ int replicaCount = getConf().getInt(NUM_REPLICA_COUNT_KEY, NUM_REPLICA_COUNT_DEFAULT);
+ if (LOG.isDebugEnabled() && replicaCount != NUM_REPLICA_COUNT_DEFAULT) {
+ LOG.debug("Region Replicas enabled: " + replicaCount);
+ }
// Scale this up on a real cluster
if (util.isDistributedCluster()) {
@@ -607,12 +696,6 @@ public void setUpCluster() throws Exception {
}
}
- private static final String OPT_LOAD = "load";
- private static final String OPT_CHECK = "check";
-
- private boolean load = false;
- private boolean check = false;
-
@Override
protected void addOptions() {
super.addOptions();
@@ -632,6 +715,7 @@ public int runTestFromCommandLine() throws Exception {
if (load) {
runLoad();
} else if (check) {
+ installSlowingCoproc();
runCheck();
} else {
testBulkLoad();
@@ -655,5 +739,4 @@ public static void main(String[] args) throws Exception {
int status = ToolRunner.run(conf, new IntegrationTestBulkLoad(), args);
System.exit(status);
}
-
-}
\ No newline at end of file
+}
diff --git a/hbase-it/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestTimeBoundedRequestsWithRegionReplicas.java b/hbase-it/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestTimeBoundedRequestsWithRegionReplicas.java
index 66f31552d7e9..eb3bb706b0d2 100644
--- a/hbase-it/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestTimeBoundedRequestsWithRegionReplicas.java
+++ b/hbase-it/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestTimeBoundedRequestsWithRegionReplicas.java
@@ -234,6 +234,7 @@ public static class TimeBoundedMultiThreadedReader extends MultiThreadedReader {
protected AtomicLong timedOutReads = new AtomicLong();
protected long runTime;
protected Thread timeoutThread;
+ protected AtomicLong staleReads = new AtomicLong();
public TimeBoundedMultiThreadedReader(LoadTestDataGenerator dataGen, Configuration conf,
TableName tableName, double verifyPercent) throws IOException {
@@ -263,6 +264,7 @@ public void waitForFinish() {
@Override
protected String progressInfo() {
StringBuilder builder = new StringBuilder(super.progressInfo());
+ appendToStatus(builder, "stale_reads", staleReads.get());
appendToStatus(builder, "get_timeouts", timedOutReads.get());
return builder.toString();
}
@@ -327,6 +329,9 @@ protected void verifyResultsAndUpdateMetrics(boolean verify, Get[] gets, long el
Result[] results, HTableInterface table, boolean isNullExpected)
throws IOException {
super.verifyResultsAndUpdateMetrics(verify, gets, elapsedNano, results, table, isNullExpected);
+ for (Result r : results) {
+ if (r.isStale()) staleReads.incrementAndGet();
+ }
// we actually do not timeout and cancel the reads after timeout. We just wait for the RPC
// to complete, but if the request took longer than timeout, we treat that as error.
if (elapsedNano > timeoutNano) {
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/TableRecordReaderImpl.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/TableRecordReaderImpl.java
index 7eb7871d3af6..e8e6e8bb73e9 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/TableRecordReaderImpl.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/TableRecordReaderImpl.java
@@ -65,6 +65,7 @@ public class TableRecordReaderImpl {
private TaskAttemptContext context = null;
private Method getCounter = null;
private long numRestarts = 0;
+ private long numStale = 0;
private long timestamp;
private int rowcount;
private boolean logScannerActivity = false;
@@ -203,6 +204,7 @@ public boolean nextKeyValue() throws IOException, InterruptedException {
try {
try {
value = this.scanner.next();
+ if (value != null && value.isStale()) numStale++;
if (logScannerActivity) {
rowcount ++;
if (rowcount >= logPerRowCount) {
@@ -230,6 +232,7 @@ public boolean nextKeyValue() throws IOException, InterruptedException {
scanner.next(); // skip presumed already mapped row
}
value = scanner.next();
+ if (value != null && value.isStale()) numStale++;
numRestarts++;
}
if (value != null && value.size() > 0) {
@@ -270,11 +273,11 @@ private void updateCounters() throws IOException {
ScanMetrics scanMetrics = ProtobufUtil.toScanMetrics(serializedMetrics);
- updateCounters(scanMetrics, numRestarts, getCounter, context);
+ updateCounters(scanMetrics, numRestarts, getCounter, context, numStale);
}
protected static void updateCounters(ScanMetrics scanMetrics, long numScannerRestarts,
- Method getCounter, TaskAttemptContext context) {
+ Method getCounter, TaskAttemptContext context, long numStale) {
// we can get access to counters only if hbase uses new mapreduce APIs
if (getCounter == null) {
return;
@@ -289,6 +292,8 @@ protected static void updateCounters(ScanMetrics scanMetrics, long numScannerRes
}
((Counter) getCounter.invoke(context, HBASE_COUNTER_GROUP_NAME,
"NUM_SCANNER_RESTARTS")).increment(numScannerRestarts);
+ ((Counter) getCounter.invoke(context, HBASE_COUNTER_GROUP_NAME,
+ "NUM_SCAN_RESULTS_STALE")).increment(numStale);
} catch (Exception e) {
LOG.debug("can't update counter." + StringUtils.stringifyException(e));
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/TableSnapshotInputFormat.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/TableSnapshotInputFormat.java
index f8d4d1805990..8071c5648b6c 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/TableSnapshotInputFormat.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/TableSnapshotInputFormat.java
@@ -152,7 +152,7 @@ public boolean nextKeyValue() throws IOException, InterruptedException {
if (result) {
ScanMetrics scanMetrics = delegate.getScanner().getScanMetrics();
if (scanMetrics != null && context != null) {
- TableRecordReaderImpl.updateCounters(scanMetrics, 0, getCounter, context);
+ TableRecordReaderImpl.updateCounters(scanMetrics, 0, getCounter, context, 0);
}
}
return result;
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
index 79bda274d7e5..3b64b735dea6 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
@@ -92,6 +92,7 @@
import org.apache.hadoop.hbase.util.JVMClusterUtil;
import org.apache.hadoop.hbase.util.JVMClusterUtil.MasterThread;
import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
+import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.util.RegionSplitter;
import org.apache.hadoop.hbase.util.RetryCounter;
import org.apache.hadoop.hbase.util.Threads;
@@ -1463,6 +1464,44 @@ public HTable createTable(byte[] tableName, byte[][] families, byte[][] splitRow
return new HTable(getConfiguration(), tableName);
}
+ /**
+ * Modify a table, synchronous. Waiting logic similar to that of {@code admin.rb#alter_status}.
+ */
+ public static void modifyTableSync(HBaseAdmin admin, HTableDescriptor desc)
+ throws IOException, InterruptedException {
+ admin.modifyTable(desc.getTableName(), desc);
+ Pair<Integer, Integer> status = new Pair<Integer, Integer>() {{
+ setFirst(0);
+ setSecond(0);
+ }};
+ for (int i = 0; status.getFirst() != 0 && i < 500; i++) { // wait up to 500 seconds
+ status = admin.getAlterStatus(desc.getTableName());
+ if (status.getSecond() != 0) {
+ LOG.debug(status.getSecond() - status.getFirst() + "/" + status.getSecond()
+ + " regions updated.");
+ Thread.sleep(1 * 1000l);
+ } else {
+ LOG.debug("All regions updated.");
+ break;
+ }
+ }
+ if (status.getSecond() != 0) {
+ throw new IOException("Failed to update replica count after 500 seconds.");
+ }
+ }
+
+ /**
+ * Set the number of Region replicas.
+ */
+ public static void setReplicas(HBaseAdmin admin, TableName table, int replicaCount)
+ throws IOException, InterruptedException {
+ admin.disableTable(table);
+ HTableDescriptor desc = admin.getTableDescriptor(table);
+ desc.setRegionReplication(replicaCount);
+ modifyTableSync(admin, desc);
+ admin.enableTable(table);
+ }
+
/**
* Drop an existing table
* @param tableName existing table
|
279d85bb562cc3dd2b20549d037f9ef44ffdbcff
|
Delta Spike
|
DELTASPIKE-278 remove unecessary checks for Message return values
Why should we restrict the return value?
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleExtension.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleExtension.java
index f17993c5d..511b79427 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleExtension.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleExtension.java
@@ -39,7 +39,6 @@
import javax.enterprise.inject.spi.ProcessProducerMethod;
import org.apache.deltaspike.core.api.message.Message;
-import org.apache.deltaspike.core.api.message.MessageContext;
import org.apache.deltaspike.core.api.message.annotation.MessageBundle;
import org.apache.deltaspike.core.api.message.annotation.MessageTemplate;
import org.apache.deltaspike.core.util.bean.WrappingBeanBuilder;
@@ -115,34 +114,16 @@ private boolean validateMessageBundle(Class<?> currentClass)
if (Message.class.isAssignableFrom(currentMethod.getReturnType()))
{
- ok |= validateMessageContextAwareMethod(currentMethod);
- }
- else
- {
- deploymentErrors.add(currentMethod.getReturnType().getName() + " isn't supported. Details: " +
- currentMethod.getDeclaringClass().getName() + "#" + currentMethod.getName() +
- " only " + String.class.getName() + " or " + Message.class.getName());
- ok = false;
+ continue;
}
- }
-
- return ok;
- }
- private boolean validateMessageContextAwareMethod(Method currentMethod)
- {
- for (Class currentParameterType : currentMethod.getParameterTypes())
- {
- if (MessageContext.class.isAssignableFrom(currentParameterType))
- {
- return true;
- }
+ deploymentErrors.add(currentMethod.getReturnType().getName() + " isn't supported. Details: " +
+ currentMethod.getDeclaringClass().getName() + "#" + currentMethod.getName() +
+ " only " + String.class.getName() + " or " + Message.class.getName());
+ ok = false;
}
- deploymentErrors.add("No " + MessageContext.class.getName() + " parameter found at: " +
- currentMethod.getDeclaringClass().getName() + "#" + currentMethod.getName() +
- ". That is required for return-type " + Message.class.getName());
- return false;
+ return ok;
}
/**
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.